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