keep file in sync and initial commit for file sharing
[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 GetMethod get = new GetMethod(mUri.toString() + remoteFilepath);
118 HttpMethodParams params = get.getParams();
119 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
120 get.setParams(params);
121
122 // get.setHeader("Host", mUri.getHost());
123 // get.setHeader("User-Agent", "Android-ownCloud");
124
125 try {
126 int status = executeMethod(get);
127 Log.e(TAG, "status return: " + status);
128 if (status != HttpStatus.SC_OK) {
129 return false;
130 }
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 } catch (IOException e) {
144 e.printStackTrace();
145 return false;
146 }
147 return true;
148 }
149
150 /**
151 * Deletes a remote file via webdav
152 * @param remoteFilePath
153 * @return
154 */
155 public boolean deleteFile(String remoteFilePath){
156 DavMethod delete = new DeleteMethod(mUri.toString() + remoteFilePath);
157 try {
158 executeMethod(delete);
159 } catch (Throwable e) {
160 Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
161 return false;
162 }
163 return true;
164 }
165
166 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
167 mDataTransferListener = listener;
168 }
169
170 public boolean putFile(String localFile, String remoteTarget,
171 String contentType) {
172 boolean result = true;
173
174 try {
175 Log.e("ASD", contentType + "");
176 File f = new File(localFile);
177 FileRequestEntity entity = new FileRequestEntity(f, contentType);
178 entity.setOnDatatransferProgressListener(mDataTransferListener);
179 Log.e("ASD", f.exists() + " " + entity.getContentLength());
180 PutMethod put = new PutMethod(mUri.toString() + remoteTarget);
181 HttpMethodParams params = put.getParams();
182 params.setSoTimeout(0); // that means "infinite timeout"; it's the default value, but let's make it explicit
183 put.setParams(params);
184 put.setRequestEntity(entity);
185 Log.d(TAG, "" + put.getURI().toString());
186 int status = executeMethod(put);
187 Log.d(TAG, "PUT method return with status " + status);
188
189 Log.i(TAG, "Uploading, done");
190 } catch (final Exception e) {
191 Log.i(TAG, "" + e.getMessage());
192 result = false;
193 }
194
195 return result;
196 }
197
198 /**
199 * Tries to log in to the given WedDavURI, with the given credentials
200 * @param uri To test
201 * @param username Username to check
202 * @param password Password to verify
203 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
204 */
205 public static int tryToLogin(Uri uri, String username, String password) {
206 int returnCode = 0;
207 WebdavClient client = new WebdavClient();
208 client.setCredentials(username, password);
209 HeadMethod head = new HeadMethod(uri.toString());
210 try {
211 returnCode = client.executeMethod(head);
212 } catch (Exception e) {
213 Log.e(TAG, "Error: " + e.getMessage());
214 }
215 return returnCode;
216 }
217
218 public boolean createDirectory(String path) {
219 try {
220 MkColMethod mkcol = new MkColMethod(mUri.toString() + path);
221 int status = executeMethod(mkcol);
222 Log.d(TAG, "Status returned " + status);
223 Log.d(TAG, "uri: " + mkcol.getURI().toString());
224 Log.i(TAG, "Creating dir completed");
225 } catch (final Exception e) {
226 e.printStackTrace();
227 return false;
228 }
229 return true;
230 }
231 }