tryToLogin must get parameters now
[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 * Gets a WebdavClient setup for the current account
63 * @param account The client accout
64 * @param context The application context
65 * @return
66 */
67 public static synchronized WebdavClient getInstance(Account account, Context context){
68 WebdavClient instance = clients.get(account.name);
69 if(instance == null ){
70 OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account,
71 AccountAuthenticator.KEY_OC_VERSION));
72 String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
73 String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
74 WebdavClient client = new WebdavClient();
75
76 String username = account.name.substring(0, account.name.indexOf('@'));
77 String password = AccountManager.get(context).getPassword(account);
78
79 client.mUri = Uri.parse(baseUrl + webDavPath);
80 client.getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
81 client.setCredentials(username, password);
82 client.allowSelfsignedCertificates();
83 clients.put(account.name, client);
84 }
85 return instance;
86 }
87
88 public void setCredentials(String username, String password) {
89 getParams().setAuthenticationPreemptive(true);
90 getState().setCredentials(AuthScope.ANY,
91 getCredentials(username, password));
92 }
93
94 private Credentials getCredentials(String username, String password) {
95 if (mCredentials == null)
96 mCredentials = new UsernamePasswordCredentials(username, password);
97 return mCredentials;
98 }
99
100 public void allowSelfsignedCertificates() {
101 // https
102 Protocol.registerProtocol("https", new Protocol("https",
103 new EasySSLSocketFactory(), 443));
104 }
105
106 public boolean downloadFile(String remoteFilepath, File targetPath) {
107 // HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ",
108 // "%20"));
109 /* dvelasco - this is not necessary anymore; OCFile.mRemotePath (the origin of remoteFielPath) keeps valid URL strings
110 String[] splitted_filepath = remoteFilepath.split("/");
111 remoteFilepath = "";
112 for (String s : splitted_filepath) {
113 if (s.equals("")) continue;
114 remoteFilepath += "/" + URLEncoder.encode(s);
115 }
116
117 Log.e("ASD", mUri.toString() + remoteFilepath.replace(" ", "%20") + "");
118 GetMethod get = new GetMethod(mUri.toString()
119 + remoteFilepath.replace(" ", "%20"));
120 */
121 GetMethod get = new GetMethod(mUri.toString() + remoteFilepath);
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 return false;
131 }
132 BufferedInputStream bis = new BufferedInputStream(
133 get.getResponseBodyAsStream());
134 FileOutputStream fos = new FileOutputStream(targetPath);
135
136 byte[] bytes = new byte[4096];
137 int readResult;
138 while ((readResult = bis.read(bytes)) != -1) {
139 if (mDataTransferListener != null)
140 mDataTransferListener.transferProgress(readResult);
141 fos.write(bytes, 0, readResult);
142 }
143
144 } catch (IOException e) {
145 e.printStackTrace();
146 return false;
147 }
148 return true;
149 }
150
151 /**
152 * Deletes a remote file via webdav
153 * @param remoteFilePath
154 * @return
155 */
156 public boolean deleteFile(String remoteFilePath){
157 DavMethod delete = new DeleteMethod(mUri.toString() + remoteFilePath);
158 try {
159 executeMethod(delete);
160 } catch (IOException e) {
161 Log.e(TAG, "Logging failed with error: " + e.getMessage(), e);
162 return false;
163 }
164 return true;
165 }
166
167 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
168 mDataTransferListener = listener;
169 }
170
171 public boolean putFile(String localFile, String remoteTarget,
172 String contentType) {
173 boolean result = true;
174
175 try {
176 Log.e("ASD", contentType + "");
177 File f = new File(localFile);
178 FileRequestEntity entity = new FileRequestEntity(f, contentType);
179 entity.setOnDatatransferProgressListener(mDataTransferListener);
180 Log.e("ASD", f.exists() + " " + entity.getContentLength());
181 PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
182 put.setRequestEntity(entity);
183 Log.d(TAG, "" + put.getURI().toString());
184 int status = executeMethod(put);
185 Log.d(TAG, "PUT method return with status " + status);
186
187 Log.i(TAG, "Uploading, done");
188 } catch (final Exception e) {
189 Log.i(TAG, "" + e.getMessage());
190 result = false;
191 }
192
193 return result;
194 }
195
196 /**
197 * Tries to log in to the given WedDavURI, with the given credentials
198 * @param uri To test
199 * @param username Username to check
200 * @param password Password to verify
201 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
202 */
203 public int tryToLogin(Uri uri, String username, String password) {
204 int returnCode = 0;
205 setCredentials(username, password);
206 HeadMethod head = new HeadMethod(uri.toString());
207 try {
208 returnCode = executeMethod(head);
209 } catch (Exception e) {
210 Log.e(TAG, "Error: " + e.getMessage());
211 }
212 return returnCode;
213 }
214
215 public boolean createDirectory(String path) {
216 try {
217 MkColMethod mkcol = new MkColMethod(mUri.toString() + path);
218 int status = executeMethod(mkcol);
219 Log.d(TAG, "Status returned " + status);
220 Log.d(TAG, "uri: " + mkcol.getURI().toString());
221 Log.i(TAG, "Creating dir completed");
222 } catch (final Exception e) {
223 e.printStackTrace();
224 return false;
225 }
226 return true;
227 }
228 }