storage manager, removing db logic from ocfile
[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.Context;
43 import android.net.Uri;
44 import android.text.TextUtils;
45 import android.util.Log;
46 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
47 import eu.alefzero.owncloud.datamodel.DataStorageManager;
48 import eu.alefzero.owncloud.datamodel.OCFile;
49 import eu.alefzero.webdav.HttpPropFind;
50 import eu.alefzero.webdav.TreeNode;
51 import eu.alefzero.webdav.TreeNode.NodeProperty;
52 import eu.alefzero.webdav.WebdavClient;
53 import eu.alefzero.webdav.WebdavUtils;
54
55 /**
56 * Base SyncAdapter for OwnCloud Designed to be subclassed for the concrete
57 * SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc..
58 *
59 * @author sassman
60 *
61 */
62 public abstract class AbstractOwnCloudSyncAdapter extends
63 AbstractThreadedSyncAdapter {
64
65 private AccountManager accountManager;
66 private Account account;
67 private ContentProviderClient contentProvider;
68 private Date lastUpdated;
69 private DataStorageManager mStoreManager;
70
71 private HttpHost mHost;
72 private WebdavClient mClient = null;
73 private static String TAG = "AbstractOwnCloudSyncAdapter";
74
75 public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
76 super(context, autoInitialize);
77 this.setAccountManager(AccountManager.get(context));
78 }
79
80 public AccountManager getAccountManager() {
81 return accountManager;
82 }
83
84 public void setAccountManager(AccountManager accountManager) {
85 this.accountManager = accountManager;
86 }
87
88 public Account getAccount() {
89 return account;
90 }
91
92 public void setAccount(Account account) {
93 this.account = account;
94 }
95
96 public ContentProviderClient getContentProvider() {
97 return contentProvider;
98 }
99
100 public void setContentProvider(ContentProviderClient contentProvider) {
101 this.contentProvider = contentProvider;
102 }
103
104 public Date getLastUpdated() {
105 return lastUpdated;
106 }
107
108 public void setLastUpdated(Date lastUpdated) {
109 this.lastUpdated = lastUpdated;
110 }
111
112 public void setStorageManager(DataStorageManager storage_manager) {
113 mStoreManager = storage_manager;
114 }
115
116 public DataStorageManager getStorageManager() {
117 return mStoreManager;
118 }
119
120 protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {
121 return new ConnectionKeepAliveStrategy() {
122 public long getKeepAliveDuration(HttpResponse response,
123 HttpContext context) {
124 // Change keep alive straategy basing on response: ie
125 // forbidden/not found/etc
126 // should have keep alive 0
127 // default return: 5s
128 int statusCode = response.getStatusLine().getStatusCode();
129
130 // HTTP 400, 500 Errors as well as HTTP 118 - Connection timed
131 // out
132 if ((statusCode >= 400 && statusCode <= 418)
133 || (statusCode >= 421 && statusCode <= 426)
134 || (statusCode >= 500 && statusCode <= 510)
135 || statusCode == 118) {
136 return 0;
137 }
138
139 return 5 * 1000;
140 }
141 };
142 }
143
144 protected HttpPropFind getPropFindQuery()
145 throws OperationCanceledException, AuthenticatorException,
146 IOException {
147 HttpPropFind query = new HttpPropFind(getUri().toString());
148 query.setHeader("Content-type", "text/xml");
149 query.setHeader("User-Agent", "Android-ownCloud");
150 return query;
151 }
152
153 protected HttpResponse fireRawRequest(HttpRequest query)
154 throws ClientProtocolException, OperationCanceledException,
155 AuthenticatorException, IOException {
156 BasicHttpContext httpContext = new BasicHttpContext();
157 BasicScheme basicAuth = new BasicScheme();
158 httpContext.setAttribute("preemptive-auth", basicAuth);
159
160 HttpResponse response = getClient().execute(mHost, query, httpContext);
161 return response;
162 }
163
164 protected TreeNode fireRequest(HttpRequest query)
165 throws ClientProtocolException, OperationCanceledException,
166 AuthenticatorException, IOException {
167 HttpResponse response = fireRawRequest(query);
168
169 TreeNode root = new TreeNode();
170 root.setProperty(TreeNode.NodeProperty.NAME, "");
171 this.parseResponse(response, getUri(), getClient(), mHost,
172 root.getChildList(), false, 0);
173 return root;
174 }
175
176 protected Uri getUri() {
177 return Uri.parse(this.getAccountManager().getUserData(getAccount(),
178 AccountAuthenticator.KEY_OC_URL));
179 }
180
181 private DefaultHttpClient getClient() throws OperationCanceledException,
182 AuthenticatorException, IOException {
183 if (mClient == null) {
184 String username = getAccount().name.split("@")[0];
185 String password = this.getAccountManager().blockingGetAuthToken(
186 getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);
187 if (this.getAccountManager().getUserData(getAccount(),
188 AccountAuthenticator.KEY_OC_URL) == null) {
189 throw new UnknownHostException();
190 }
191 Uri uri = getUri();
192
193 mClient = new WebdavClient(uri);
194 mClient.setCredentials(username, password);
195 mClient.allowUnsignedCertificates();
196 mHost = mClient.getTargetHost();
197 }
198
199 return mClient.getHttpClient();
200 }
201
202 private void parseResponse(HttpResponse resp, Uri uri,
203 DefaultHttpClient client, HttpHost targetHost,
204 LinkedList<TreeNode> insertList, boolean sf, long parent_id)
205 throws IOException, OperationCanceledException,
206 AuthenticatorException {
207 boolean skipFirst = sf, override_parent = !sf;
208 for (TreeNode n : WebdavUtils.parseResponseToNodes(resp.getEntity()
209 .getContent())) {
210 if (skipFirst) {
211 skipFirst = false;
212 continue;
213 }
214 String path = n.stripPathFromFilename(uri.getPath());
215
216 long mod = n.getProperty(NodeProperty.LAST_MODIFIED_DATE) == null ? 0
217 : Long.parseLong(n
218 .getProperty(NodeProperty.LAST_MODIFIED_DATE));
219
220 OCFile file = getStorageManager().getFileByPath(n.getProperty(NodeProperty.PATH));
221 if (file != null && file.fileExists() && file.getModificationTimestamp() >= mod) {
222 Log.d(TAG, "No update for file/dir " + file.getFileName()
223 + " is needed");
224 } else {
225 Log.d(TAG, "File " + n.getProperty(NodeProperty.PATH)
226 + " will be "
227 + (file.fileExists() ? "updated" : "created"));
228 long len = n.getProperty(NodeProperty.CONTENT_LENGTH) == null ? 0
229 : Long.parseLong(n
230 .getProperty(NodeProperty.CONTENT_LENGTH));
231 long create = n.getProperty(NodeProperty.CREATE_DATE) == null ? 0
232 : Long.parseLong(n
233 .getProperty(NodeProperty.CREATE_DATE));
234 file = new OCFile(n.getProperty(NodeProperty.PATH));
235 file.setFileLength(len);
236 file.setCreationTimestamp(create);
237 file.setModificationTimestamp(mod);
238 file.setMimetype(n.getProperty(NodeProperty.RESOURCE_TYPE));
239 file.setParentId(parent_id);
240 getStorageManager().saveFile(file);
241 if (override_parent) {
242 parent_id = file.getFileId();
243 override_parent = false;
244 }
245 }
246
247 if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME))
248 && n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {
249
250 HttpPropFind method = new HttpPropFind(uri.getPath() + path
251 + n.getProperty(NodeProperty.NAME).replace(" ", "%20")
252 + "/");
253 HttpResponse response = fireRawRequest(method);
254 parseResponse(response, uri, client, targetHost,
255 n.getChildList(), true, file.getFileId());
256 }
257 }
258 }
259 }