1fabe3ad3b06aab479ba371f937eaca4a6c78b33
[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
25 import org.apache.commons.httpclient.Credentials;
26 import org.apache.commons.httpclient.HttpClient;
27 import org.apache.commons.httpclient.HttpException;
28 import org.apache.commons.httpclient.HttpMethodBase;
29 import org.apache.commons.httpclient.HttpVersion;
30 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
31 import org.apache.commons.httpclient.UsernamePasswordCredentials;
32 import org.apache.commons.httpclient.auth.AuthScope;
33 import org.apache.commons.httpclient.methods.GetMethod;
34 import org.apache.commons.httpclient.methods.HeadMethod;
35 import org.apache.commons.httpclient.methods.PutMethod;
36 import org.apache.commons.httpclient.params.HttpMethodParams;
37 import org.apache.commons.httpclient.protocol.Protocol;
38 import org.apache.http.HttpStatus;
39 import org.apache.http.params.CoreProtocolPNames;
40 import org.apache.jackrabbit.webdav.client.methods.DavMethod;
41 import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
42 import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
43
44 import com.owncloud.android.AccountUtils;
45 import com.owncloud.android.authenticator.AccountAuthenticator;
46 import com.owncloud.android.authenticator.EasySSLSocketFactory;
47 import com.owncloud.android.files.interfaces.OnDatatransferProgressListener;
48 import com.owncloud.android.utils.OwnCloudVersion;
49
50 import android.accounts.Account;
51 import android.accounts.AccountManager;
52 import android.content.Context;
53 import android.net.Uri;
54 import android.util.Log;
55
56 public class WebdavClient extends HttpClient {
57 private Uri mUri;
58 private Credentials mCredentials;
59 final private static String TAG = "WebdavClient";
60 private static final String USER_AGENT = "Android-ownCloud";
61
62 /** Default timeout for waiting data from the server: 10 seconds */
63 public static final int DEFAULT_DATA_TIMEOUT = 10000;
64
65 /** Default timeout for establishing a connection: infinite */
66 public static final int DEFAULT_CONNECTION_TIMEOUT = 0;
67
68 private OnDatatransferProgressListener mDataTransferListener;
69 static private MultiThreadedHttpConnectionManager mConnManager = null;
70
71 static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
72 if (mConnManager == null) {
73 mConnManager = new MultiThreadedHttpConnectionManager();
74 mConnManager.setMaxConnectionsPerHost(5);
75 mConnManager.setMaxTotalConnections(5);
76 }
77 return mConnManager;
78 }
79
80 /**
81 * Creates a WebdavClient setup for the current account
82 * @param account The client accout
83 * @param context The application context
84 * @return
85 */
86 public WebdavClient (Account account, Context context) {
87 setDefaultTimeouts();
88
89 OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account,
90 AccountAuthenticator.KEY_OC_VERSION));
91 String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
92 String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
93 String username = account.name.substring(0, account.name.lastIndexOf('@'));
94 String password = AccountManager.get(context).getPassword(account);
95
96 mUri = Uri.parse(baseUrl + webDavPath);
97 Log.e("ASD", ""+username);
98 setCredentials(username, password);
99 }
100
101 public WebdavClient() {
102 super(getMultiThreadedConnManager());
103
104 setDefaultTimeouts();
105
106 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
107 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
108 allowSelfsignedCertificates();
109 }
110
111 public void setCredentials(String username, String password) {
112 getParams().setAuthenticationPreemptive(true);
113 getState().setCredentials(AuthScope.ANY,
114 getCredentials(username, password));
115 }
116
117 private Credentials getCredentials(String username, String password) {
118 if (mCredentials == null)
119 mCredentials = new UsernamePasswordCredentials(username, password);
120 return mCredentials;
121 }
122
123 /**
124 * Sets the connection and wait-for-data timeouts to be applied by default.
125 */
126 private void setDefaultTimeouts() {
127 getParams().setSoTimeout(DEFAULT_DATA_TIMEOUT);
128 getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
129 }
130
131 public void allowSelfsignedCertificates() {
132 // https
133 Protocol.registerProtocol("https", new Protocol("https",
134 new EasySSLSocketFactory(), 443));
135 }
136
137 /**
138 * Downloads a file in remoteFilepath to the local targetPath.
139 *
140 * @param remoteFilepath Path to the file in the remote server, URL DECODED.
141 * @param targetFile Local path to save the downloaded file.
142 * @return 'True' when the file is successfully downloaded.
143 */
144 public boolean downloadFile(String remoteFilepath, File targetFile) {
145 boolean ret = false;
146 GetMethod get = new GetMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilepath));
147
148 int status = -1;
149 try {
150 status = executeMethod(get);
151 if (status == HttpStatus.SC_OK) {
152 targetFile.createNewFile();
153 BufferedInputStream bis = new BufferedInputStream(
154 get.getResponseBodyAsStream());
155 FileOutputStream fos = new FileOutputStream(targetFile);
156
157 byte[] bytes = new byte[4096];
158 int readResult;
159 while ((readResult = bis.read(bytes)) != -1) {
160 if (mDataTransferListener != null)
161 mDataTransferListener.transferProgress(readResult);
162 fos.write(bytes, 0, readResult);
163 }
164 ret = true;
165 }
166
167 } catch (HttpException e) {
168 Log.e(TAG, "HTTP exception downloading " + remoteFilepath, e);
169
170 } catch (IOException e) {
171 Log.e(TAG, "I/O exception downloading " + remoteFilepath, e);
172
173 } catch (Exception e) {
174 Log.e(TAG, "Unexpected exception downloading " + remoteFilepath, e);
175
176 } finally {
177 if (!ret) {
178 if (status >= 0) {
179 Log.e(TAG, "Download of " + remoteFilepath + " to " + targetFile + " failed with HTTP status " + status);
180 }
181 if (targetFile.exists()) {
182 targetFile.delete();
183 }
184 }
185 }
186 return ret;
187 }
188
189 /**
190 * Deletes a remote file via webdav
191 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
192 * @return
193 */
194 public boolean deleteFile(String remoteFilePath){
195 DavMethod delete = new DeleteMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
196 try {
197 executeMethod(delete);
198 } catch (Throwable e) {
199 Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
200 return false;
201 }
202 return true;
203 }
204
205 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
206 mDataTransferListener = listener;
207 }
208
209 /**
210 * Creates or update a file in the remote server with the contents of a local file.
211 *
212 *
213 * @param localFile Path to the local file to upload.
214 * @param remoteTarget Remote path to the file to create or update, URL DECODED
215 * @param contentType MIME type of the file.
216 * @return 'True' then the upload was successfully completed
217 */
218 public boolean putFile(String localFile, String remoteTarget, String contentType) {
219 boolean result = false;
220 int status = -1;
221
222 try {
223 File f = new File(localFile);
224 FileRequestEntity entity = new FileRequestEntity(f, contentType);
225 entity.setOnDatatransferProgressListener(mDataTransferListener);
226 PutMethod put = new PutMethod(mUri.toString() + WebdavUtils.encodePath(remoteTarget));
227 put.setRequestEntity(entity);
228 status = executeMethod(put);
229
230 result = (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT);
231
232 Log.d(TAG, "PUT response for " + remoteTarget + " finished with HTTP status " + status);
233
234 } catch (HttpException e) {
235 Log.e(TAG, "HTTP exception uploading " + localFile + " to " + remoteTarget, e);
236
237 } catch (IOException e) {
238 Log.e(TAG, "I/O exception uploading " + localFile + " to " + remoteTarget, e);
239
240 } catch (Exception e) {
241 Log.e(TAG, "Unexpected exception uploading " + localFile + " to " + remoteTarget, e);
242 }
243
244 if (!result && status >= 0) Log.e(TAG, "Upload of " + localFile + " to " + remoteTarget + " FAILED with HTTP status " + status);
245
246 return result;
247 }
248
249 /**
250 * Tries to log in to the given WedDavURI, with the given credentials
251 * @param uri To test
252 * @param username Username to check
253 * @param password Password to verify
254 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
255 */
256 public static int tryToLogin(Uri uri, String username, String password) {
257 int returnCode = 0;
258 try {
259 WebdavClient client = new WebdavClient();
260 client.setCredentials(username, password);
261 HeadMethod head = new HeadMethod(uri.toString());
262 returnCode = client.executeMethod(head);
263 } catch (HttpException e) {
264 Log.e(TAG, "HTTP exception trying to login at " + uri.getEncodedPath(), e);
265 } catch (IOException e) {
266 Log.e(TAG, "I/O exception trying to login at " + uri.getEncodedPath(), e);
267 } catch (Exception e) {
268 Log.e(TAG, "Unexpected exception trying to login at " + uri.getEncodedPath(), e);
269 }
270 return returnCode;
271 }
272
273 /**
274 * Creates a remote directory with the received path.
275 *
276 * @param path Path of the directory to create, URL DECODED
277 * @return 'True' when the directory is successfully created
278 */
279 public boolean createDirectory(String path) {
280 boolean result = false;
281 int status = -1;
282 try {
283 MkColMethod mkcol = new MkColMethod(mUri.toString() + WebdavUtils.encodePath(path));
284 Log.d(TAG, "Creating directory " + path);
285 status = executeMethod(mkcol);
286 Log.d(TAG, "Status returned: " + status);
287 result = mkcol.succeeded();
288
289 } catch (HttpException e) {
290 Log.e(TAG, "HTTP exception creating directory " + path, e);
291
292 } catch (IOException e) {
293 Log.e(TAG, "I/O exception creating directory " + path, e);
294
295 } catch (Exception e) {
296 Log.e(TAG, "Unexpected exception creating directory " + path, e);
297
298 }
299 if (!result && status >= 0) {
300 Log.e(TAG, "Creation of directory " + path + " failed with HTTP status " + status);
301 }
302 return result;
303 }
304
305
306 /**
307 * Check if a file exists in the OC server
308 *
309 * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
310 */
311 public Boolean existsFile(String path) {
312 try {
313 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
314 int status = executeMethod(head);
315 return (status == HttpStatus.SC_OK);
316 } catch (Exception e) {
317 e.printStackTrace();
318 return null;
319 }
320 }
321
322
323 /**
324 * Requests the received method with the received timeout (milliseconds).
325 *
326 * Executes the method through the inherited HttpClient.executedMethod(method).
327 *
328 * Sets the socket timeout for the HttpMethodBase method received.
329 *
330 * @param method HTTP method request.
331 * @param timeout Timeout to set, in milliseconds; <= 0 means infinite.
332 */
333 public int executeMethod(HttpMethodBase method, int readTimeout) throws HttpException, IOException {
334 int oldSoTimeout = getParams().getSoTimeout();
335 try {
336 if (readTimeout < 0) {
337 readTimeout = 0;
338 }
339 HttpMethodParams params = method.getParams();
340 params.setSoTimeout(readTimeout);
341 method.setParams(params); // this should be enough...
342 getParams().setSoTimeout(readTimeout); // ... but this is necessary for HTTPS
343 return executeMethod(method);
344 } finally {
345 getParams().setSoTimeout(oldSoTimeout);
346 }
347 }
348 }