a1dbd098e814479a1312801b03ca34311c520abe
[pub/Android/ownCloud.git] / src / eu / alefzero / webdav / WebdavClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package eu.alefzero.webdav;
19
20 import java.io.BufferedInputStream;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.util.HashMap;
25
26 import org.apache.commons.httpclient.Credentials;
27 import org.apache.commons.httpclient.HttpClient;
28 import org.apache.commons.httpclient.UsernamePasswordCredentials;
29 import org.apache.commons.httpclient.auth.AuthScope;
30 import org.apache.commons.httpclient.methods.GetMethod;
31 import org.apache.commons.httpclient.methods.HeadMethod;
32 import org.apache.commons.httpclient.methods.PutMethod;
33 import org.apache.commons.httpclient.params.HttpMethodParams;
34 import org.apache.commons.httpclient.protocol.Protocol;
35 import org.apache.http.HttpStatus;
36 import org.apache.jackrabbit.webdav.client.methods.DavMethod;
37 import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
38 import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
39
40 import android.accounts.Account;
41 import android.accounts.AccountManager;
42 import android.content.Context;
43 import android.net.Uri;
44 import android.util.Log;
45 import eu.alefzero.owncloud.AccountUtils;
46 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
47 import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
48 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
49 import eu.alefzero.owncloud.utils.OwnCloudVersion;
50
51 public class WebdavClient extends HttpClient {
52 private Uri mUri;
53 private Credentials mCredentials;
54 final private static String TAG = "WebdavClient";
55 private static final String USER_AGENT = "Android-ownCloud";
56 private OnDatatransferProgressListener mDataTransferListener;
57 private static HashMap<String, WebdavClient> clients = new HashMap<String, WebdavClient>();
58
59 /**
60 * Creates a WebdavClient setup for the current account
61 * @param account The client accout
62 * @param context The application context
63 * @return
64 */
65 public WebdavClient (Account account, Context context){
66 OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account,
67 AccountAuthenticator.KEY_OC_VERSION));
68 String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
69 String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
70 String username = account.name.substring(0, account.name.indexOf('@'));
71 String password = AccountManager.get(context).getPassword(account);
72
73 mUri = Uri.parse(baseUrl + webDavPath);
74 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
75 setCredentials(username, password);
76 allowSelfsignedCertificates();
77 }
78
79 public WebdavClient(){}
80
81 public void setCredentials(String username, String password) {
82 getParams().setAuthenticationPreemptive(true);
83 getState().setCredentials(AuthScope.ANY,
84 getCredentials(username, password));
85 }
86
87 private Credentials getCredentials(String username, String password) {
88 if (mCredentials == null)
89 mCredentials = new UsernamePasswordCredentials(username, password);
90 return mCredentials;
91 }
92
93 public void allowSelfsignedCertificates() {
94 // https
95 Protocol.registerProtocol("https", new Protocol("https",
96 new EasySSLSocketFactory(), 443));
97 }
98
99 public boolean downloadFile(String remoteFilepath, File targetPath) {
100 // HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ",
101 // "%20"));
102 /* dvelasco - this is not necessary anymore; OCFile.mRemotePath (the origin of remoteFielPath) keeps valid URL strings
103 String[] splitted_filepath = remoteFilepath.split("/");
104 remoteFilepath = "";
105 for (String s : splitted_filepath) {
106 if (s.equals("")) continue;
107 remoteFilepath += "/" + URLEncoder.encode(s);
108 }
109
110 Log.e("ASD", mUri.toString() + remoteFilepath.replace(" ", "%20") + "");
111 GetMethod get = new GetMethod(mUri.toString()
112 + remoteFilepath.replace(" ", "%20"));
113 */
114 GetMethod get = new GetMethod(mUri.toString() + remoteFilepath);
115
116 // get.setHeader("Host", mUri.getHost());
117 // get.setHeader("User-Agent", "Android-ownCloud");
118
119 try {
120 int status = executeMethod(get);
121 Log.e(TAG, "status return: " + status);
122 if (status != HttpStatus.SC_OK) {
123 return false;
124 }
125 BufferedInputStream bis = new BufferedInputStream(
126 get.getResponseBodyAsStream());
127 FileOutputStream fos = new FileOutputStream(targetPath);
128
129 byte[] bytes = new byte[4096];
130 int readResult;
131 while ((readResult = bis.read(bytes)) != -1) {
132 if (mDataTransferListener != null)
133 mDataTransferListener.transferProgress(readResult);
134 fos.write(bytes, 0, readResult);
135 }
136
137 } catch (IOException e) {
138 e.printStackTrace();
139 return false;
140 }
141 return true;
142 }
143
144 /**
145 * Deletes a remote file via webdav
146 * @param remoteFilePath
147 * @return
148 */
149 public boolean deleteFile(String remoteFilePath){
150 DavMethod delete = new DeleteMethod(mUri.toString() + remoteFilePath);
151 try {
152 executeMethod(delete);
153 } catch (Throwable e) {
154 Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
155 return false;
156 }
157 return true;
158 }
159
160 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
161 mDataTransferListener = listener;
162 }
163
164 public boolean putFile(String localFile, String remoteTarget,
165 String contentType) {
166 boolean result = true;
167
168 try {
169 Log.e("ASD", contentType + "");
170 File f = new File(localFile);
171 FileRequestEntity entity = new FileRequestEntity(f, contentType);
172 entity.setOnDatatransferProgressListener(mDataTransferListener);
173 Log.e("ASD", f.exists() + " " + entity.getContentLength());
174 PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
175 put.setRequestEntity(entity);
176 Log.d(TAG, "" + put.getURI().toString());
177 int status = executeMethod(put);
178 Log.d(TAG, "PUT method return with status " + status);
179
180 Log.i(TAG, "Uploading, done");
181 } catch (final Exception e) {
182 Log.i(TAG, "" + e.getMessage());
183 result = false;
184 }
185
186 return result;
187 }
188
189 /**
190 * Tries to log in to the given WedDavURI, with the given credentials
191 * @param uri To test
192 * @param username Username to check
193 * @param password Password to verify
194 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
195 */
196 public static int tryToLogin(Uri uri, String username, String password) {
197 int returnCode = 0;
198 WebdavClient client = new WebdavClient();
199 client.setCredentials(username, password);
200 HeadMethod head = new HeadMethod(uri.toString());
201 try {
202 returnCode = client.executeMethod(head);
203 } catch (Exception e) {
204 Log.e(TAG, "Error: " + e.getMessage());
205 }
206 return returnCode;
207 }
208
209 public boolean createDirectory(String path) {
210 try {
211 MkColMethod mkcol = new MkColMethod(mUri.toString() + path);
212 int status = executeMethod(mkcol);
213 Log.d(TAG, "Status returned " + status);
214 Log.d(TAG, "uri: " + mkcol.getURI().toString());
215 Log.i(TAG, "Creating dir completed");
216 } catch (final Exception e) {
217 e.printStackTrace();
218 return false;
219 }
220 return true;
221 }
222 }