b06ac539c79b7a880f8c444859b6ad85de04782f
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / syncadapter / AbstractOwnCloudSyncAdapter.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
19 package eu.alefzero.owncloud.syncadapter;
20
21 import java.io.IOException;
22 import java.net.UnknownHostException;
23 import java.util.Date;
24 import java.util.LinkedList;
25
26 import org.apache.http.HttpHost;
27 import org.apache.http.HttpRequest;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.ClientProtocolException;
30 import org.apache.http.conn.ConnectionKeepAliveStrategy;
31 import org.apache.http.impl.auth.BasicScheme;
32 import org.apache.http.impl.client.DefaultHttpClient;
33 import org.apache.http.protocol.BasicHttpContext;
34 import org.apache.http.protocol.HttpContext;
35
36 import android.accounts.Account;
37 import android.accounts.AccountManager;
38 import android.accounts.AuthenticatorException;
39 import android.accounts.OperationCanceledException;
40 import android.content.AbstractThreadedSyncAdapter;
41 import android.content.ContentProviderClient;
42 import android.content.ContentResolver;
43 import android.content.Context;
44 import android.net.Uri;
45 import android.text.TextUtils;
46 import android.util.Log;
47 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
48 import eu.alefzero.owncloud.datamodel.OCFile;
49 import eu.alefzero.webdav.HttpPropFind;
50 import eu.alefzero.webdav.TreeNode;
51 import eu.alefzero.webdav.WebdavClient;
52 import eu.alefzero.webdav.WebdavUtils;
53 import eu.alefzero.webdav.TreeNode.NodeProperty;
54
55 /**
56 * Base SyncAdapter for OwnCloud
57 * Designed to be subclassed for the concreete SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc..
58 *
59 * @author sassman
60 *
61 */
62 public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter {
63
64 private AccountManager accountManager;
65 private Account account;
66 private ContentProviderClient contentProvider;
67 private Date lastUpdated;
68
69 private HttpHost mHost;
70 private WebdavClient mClient = null;
71
72 public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
73 super(context, autoInitialize);
74 this.setAccountManager(AccountManager.get(context));
75 }
76
77 public AccountManager getAccountManager() {
78 return accountManager;
79 }
80
81 public void setAccountManager(AccountManager accountManager) {
82 this.accountManager = accountManager;
83 }
84
85 public Account getAccount() {
86 return account;
87 }
88
89 public void setAccount(Account account) {
90 this.account = account;
91 }
92
93 public ContentProviderClient getContentProvider() {
94 return contentProvider;
95 }
96
97 public void setContentProvider(ContentProviderClient contentProvider) {
98 this.contentProvider = contentProvider;
99 }
100
101 public Date getLastUpdated() {
102 return lastUpdated;
103 }
104
105 public void setLastUpdated(Date lastUpdated) {
106 this.lastUpdated = lastUpdated;
107 }
108
109 protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {
110 return new ConnectionKeepAliveStrategy() {
111 public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
112 // TODO: change keep alive straategy basing on response: ie forbidden/not found/etc
113 // should have keep alive 0
114 // default return: 5s
115 return 5 * 1000;
116 }
117 };
118 }
119
120 protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException {
121 HttpPropFind query = new HttpPropFind(getUri().toString());
122 query.setHeader("Content-type", "text/xml");
123 query.setHeader("User-Agent", "Android-ownCloud");
124 return query;
125 }
126
127 protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
128 BasicHttpContext httpContext = new BasicHttpContext();
129 BasicScheme basicAuth = new BasicScheme();
130 httpContext.setAttribute("preemptive-auth", basicAuth);
131
132 HttpResponse response = getClient().execute(mHost, query, httpContext);
133 return response;
134 }
135
136 protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
137 HttpResponse response = fireRawRequest(query);
138
139 TreeNode root = new TreeNode();
140 root.setProperty(TreeNode.NodeProperty.NAME, "");
141 this.parseResponse(response, getUri(), getClient(), mHost, root.getChildList(), false, 0);
142 return root;
143 }
144
145 protected Uri getUri() {
146 return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL));
147 }
148
149 private DefaultHttpClient getClient() throws OperationCanceledException, AuthenticatorException, IOException {
150 if(mClient == null) {
151 String username = getAccount().name.split("@")[0];
152 String password = this.getAccountManager().blockingGetAuthToken(getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);
153 if (this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL) == null) {
154 throw new UnknownHostException();
155 }
156 Uri uri = getUri();
157
158 mClient = new WebdavClient(uri);
159 mClient.setCredentials(username, password);
160 mClient.allowUnsignedCertificates();
161 mHost = mClient.getTargetHost();
162 }
163
164 return mClient.getHttpClient();
165 }
166
167 private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList<TreeNode> insertList, boolean sf, long parent_id) throws IOException, OperationCanceledException, AuthenticatorException {
168 boolean skipFirst = sf, override_parent = !sf;
169 for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) {
170 if (skipFirst) {
171 skipFirst = false;
172 continue;
173 }
174 String path = n.stripPathFromFilename(uri.getPath());
175 OCFile new_file = OCFile.createNewFile(getContentProvider(),
176 getAccount(),
177 n.getProperty(NodeProperty.PATH),
178 0,//Long.parseLong(n.getProperty(NodeProperty.CONTENT_LENGTH)),
179 0,//Long.parseLong(n.getProperty(NodeProperty.CREATE_DATE)),
180 0,//Long.parseLong(n.getProperty(NodeProperty.LAST_MODIFIED_DATE)),
181 n.getProperty(NodeProperty.RESOURCE_TYPE),
182 parent_id);
183 new_file.save();
184 if (override_parent) {
185 parent_id = new_file.getFileId();
186 override_parent = false;
187 }
188
189 if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) &&
190 n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {
191
192 HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/");
193 HttpResponse response = fireRawRequest(method);
194 parseResponse(response, uri, client, targetHost, n.getChildList(), true, new_file.getFileId());
195 }
196 }
197 }
198 }