fd1ec5049e9f01dd0ad95aa412c7a3b1079b6abe
[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 GetMethod get = new GetMethod(mUri.toString() + remoteFilepath);
101 HttpMethodParams params = get.getParams();
102 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
103 get.setParams(params);
104
105 // get.setHeader("Host", mUri.getHost());
106 // get.setHeader("User-Agent", "Android-ownCloud");
107
108 try {
109 int status = executeMethod(get);
110 Log.e(TAG, "status return: " + status);
111 if (status != HttpStatus.SC_OK) {
112 return false;
113 }
114 BufferedInputStream bis = new BufferedInputStream(
115 get.getResponseBodyAsStream());
116 FileOutputStream fos = new FileOutputStream(targetPath);
117
118 byte[] bytes = new byte[4096];
119 int readResult;
120 while ((readResult = bis.read(bytes)) != -1) {
121 if (mDataTransferListener != null)
122 mDataTransferListener.transferProgress(readResult);
123 fos.write(bytes, 0, readResult);
124 }
125
126 } catch (IOException e) {
127 e.printStackTrace();
128 return false;
129 }
130 return true;
131 }
132
133 /**
134 * Deletes a remote file via webdav
135 * @param remoteFilePath
136 * @return
137 */
138 public boolean deleteFile(String remoteFilePath){
139 DavMethod delete = new DeleteMethod(mUri.toString() + remoteFilePath);
140 try {
141 executeMethod(delete);
142 } catch (Throwable e) {
143 Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
144 return false;
145 }
146 return true;
147 }
148
149 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
150 mDataTransferListener = listener;
151 }
152
153 public boolean putFile(String localFile, String remoteTarget,
154 String contentType) {
155 boolean result = true;
156
157 try {
158 Log.e("ASD", contentType + "");
159 File f = new File(localFile);
160 FileRequestEntity entity = new FileRequestEntity(f, contentType);
161 entity.setOnDatatransferProgressListener(mDataTransferListener);
162 Log.e("ASD", f.exists() + " " + entity.getContentLength());
163 PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
164 HttpMethodParams params = put.getParams();
165 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
166 put.setParams(params);
167 put.setRequestEntity(entity);
168 Log.d(TAG, "" + put.getURI().toString());
169 int status = executeMethod(put);
170 Log.d(TAG, "PUT method return with status " + status);
171
172 Log.i(TAG, "Uploading, done");
173 } catch (final Exception e) {
174 Log.i(TAG, "" + e.getMessage());
175 result = false;
176 }
177
178 return result;
179 }
180
181 /**
182 * Tries to log in to the given WedDavURI, with the given credentials
183 * @param uri To test
184 * @param username Username to check
185 * @param password Password to verify
186 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
187 */
188 public static int tryToLogin(Uri uri, String username, String password) {
189 int returnCode = 0;
190 WebdavClient client = new WebdavClient();
191 client.setCredentials(username, password);
192 HeadMethod head = new HeadMethod(uri.toString());
193 try {
194 returnCode = client.executeMethod(head);
195 } catch (Exception e) {
196 Log.e(TAG, "Error: " + e.getMessage());
197 }
198 return returnCode;
199 }
200
201 public boolean createDirectory(String path) {
202 try {
203 MkColMethod mkcol = new MkColMethod(mUri.toString() + path);
204 int status = executeMethod(mkcol);
205 Log.d(TAG, "Status returned " + status);
206 Log.d(TAG, "uri: " + mkcol.getURI().toString());
207 Log.i(TAG, "Creating dir completed");
208 } catch (final Exception e) {
209 e.printStackTrace();
210 return false;
211 }
212 return true;
213 }
214 }