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