dd3b4eaefd54038dadebb746a02a2fede1eafe5d
[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.HttpConnectionManager;
28 import org.apache.commons.httpclient.HttpVersion;
29 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
30 import org.apache.commons.httpclient.UsernamePasswordCredentials;
31 import org.apache.commons.httpclient.auth.AuthScope;
32 import org.apache.commons.httpclient.methods.GetMethod;
33 import org.apache.commons.httpclient.methods.HeadMethod;
34 import org.apache.commons.httpclient.methods.PutMethod;
35 import org.apache.commons.httpclient.params.HttpMethodParams;
36 import org.apache.commons.httpclient.protocol.Protocol;
37 import org.apache.http.HttpStatus;
38 import org.apache.http.params.CoreProtocolPNames;
39 import org.apache.jackrabbit.webdav.client.methods.DavMethod;
40 import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
41 import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
42
43 import android.accounts.Account;
44 import android.accounts.AccountManager;
45 import android.content.Context;
46 import android.net.Uri;
47 import android.util.Log;
48 import eu.alefzero.owncloud.AccountUtils;
49 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
50 import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
51 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
52 import eu.alefzero.owncloud.utils.OwnCloudVersion;
53
54 public class WebdavClient extends HttpClient {
55 private Uri mUri;
56 private Credentials mCredentials;
57 final private static String TAG = "WebdavClient";
58 private static final String USER_AGENT = "Android-ownCloud";
59 private OnDatatransferProgressListener mDataTransferListener;
60 static private MultiThreadedHttpConnectionManager mConnManager = null;
61
62 static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
63 if (mConnManager == null) {
64 mConnManager = new MultiThreadedHttpConnectionManager();
65 mConnManager.setMaxConnectionsPerHost(5);
66 mConnManager.setMaxTotalConnections(5);
67 }
68 return mConnManager;
69 }
70
71 /**
72 * Creates a WebdavClient setup for the current account
73 * @param account The client accout
74 * @param context The application context
75 * @return
76 */
77 public WebdavClient (Account account, Context context) {
78 OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account,
79 AccountAuthenticator.KEY_OC_VERSION));
80 String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
81 String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
82 String username = account.name.substring(0, account.name.indexOf('@'));
83 String password = AccountManager.get(context).getPassword(account);
84
85 mUri = Uri.parse(baseUrl + webDavPath);
86
87 setCredentials(username, password);
88 }
89
90 public WebdavClient() {
91 super(getMultiThreadedConnManager());
92
93 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
94 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
95 allowSelfsignedCertificates();
96 }
97
98 public void setCredentials(String username, String password) {
99 //getParams().setAuthenticationPreemptive(true);
100 getState().setCredentials(AuthScope.ANY,
101 getCredentials(username, password));
102 }
103
104 private Credentials getCredentials(String username, String password) {
105 if (mCredentials == null)
106 mCredentials = new UsernamePasswordCredentials(username, password);
107 return mCredentials;
108 }
109
110 public void allowSelfsignedCertificates() {
111 // https
112 Protocol.registerProtocol("https", new Protocol("https",
113 new EasySSLSocketFactory(), 443));
114 }
115
116 public boolean downloadFile(String remoteFilepath, File targetPath) {
117 boolean ret = false;
118 GetMethod get = new GetMethod(mUri.toString() + remoteFilepath);
119 HttpMethodParams params = get.getParams();
120 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
121 get.setParams(params);
122
123 // get.setHeader("Host", mUri.getHost());
124 // get.setHeader("User-Agent", "Android-ownCloud");
125
126 try {
127 int status = executeMethod(get);
128 Log.e(TAG, "status return: " + status);
129 if (status == HttpStatus.SC_OK) {
130 targetPath.createNewFile();
131 BufferedInputStream bis = new BufferedInputStream(
132 get.getResponseBodyAsStream());
133 FileOutputStream fos = new FileOutputStream(targetPath);
134
135 byte[] bytes = new byte[4096];
136 int readResult;
137 while ((readResult = bis.read(bytes)) != -1) {
138 if (mDataTransferListener != null)
139 mDataTransferListener.transferProgress(readResult);
140 fos.write(bytes, 0, readResult);
141 }
142
143 }
144 ret = true;
145 } catch (Throwable e) {
146 e.printStackTrace();
147 targetPath.delete();
148 }
149
150 return ret;
151 }
152
153 /**
154 * Deletes a remote file via webdav
155 * @param remoteFilePath
156 * @return
157 */
158 public boolean deleteFile(String remoteFilePath){
159 DavMethod delete = new DeleteMethod(mUri.toString() + remoteFilePath);
160 try {
161 executeMethod(delete);
162 } catch (Throwable e) {
163 Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
164 return false;
165 }
166 return true;
167 }
168
169 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
170 mDataTransferListener = listener;
171 }
172
173 public boolean putFile(String localFile, String remoteTarget,
174 String contentType) {
175 boolean result = true;
176
177 try {
178 Log.e("ASD", contentType + "");
179 File f = new File(localFile);
180 FileRequestEntity entity = new FileRequestEntity(f, contentType);
181 entity.setOnDatatransferProgressListener(mDataTransferListener);
182 Log.e("ASD", f.exists() + " " + entity.getContentLength());
183 PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
184 HttpMethodParams params = put.getParams();
185 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
186 put.setParams(params);
187 put.setRequestEntity(entity);
188 Log.d(TAG, "" + put.getURI().toString());
189 int status = executeMethod(put);
190 Log.d(TAG, "PUT method return with status " + status);
191
192 Log.i(TAG, "Uploading, done");
193 } catch (final Exception e) {
194 Log.i(TAG, "" + e.getMessage());
195 result = false;
196 }
197
198 return result;
199 }
200
201 /**
202 * Tries to log in to the given WedDavURI, with the given credentials
203 * @param uri To test
204 * @param username Username to check
205 * @param password Password to verify
206 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
207 */
208 public static int tryToLogin(Uri uri, String username, String password) {
209 int returnCode = 0;
210 WebdavClient client = new WebdavClient();
211 client.setCredentials(username, password);
212 HeadMethod head = new HeadMethod(uri.toString());
213 try {
214 returnCode = client.executeMethod(head);
215 } catch (Exception e) {
216 Log.e(TAG, "Error: " + e.getMessage());
217 }
218 return returnCode;
219 }
220
221 public boolean createDirectory(String path) {
222 try {
223 MkColMethod mkcol = new MkColMethod(mUri.toString() + path);
224 int status = executeMethod(mkcol);
225 Log.d(TAG, "Status returned " + status);
226 Log.d(TAG, "uri: " + mkcol.getURI().toString());
227 Log.i(TAG, "Creating dir completed");
228 } catch (final Exception e) {
229 e.printStackTrace();
230 return false;
231 }
232 return true;
233 }
234 }