0088899895152b23b0b34ab3ec2d9ca83587bd2c
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.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 com.owncloud.android.syncadapter;
20
21 import java.io.IOException;
22 import java.util.List;
23 import java.util.Vector;
24
25 import org.apache.http.HttpStatus;
26 import org.apache.jackrabbit.webdav.DavException;
27 import org.apache.jackrabbit.webdav.MultiStatus;
28 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
29
30 import com.owncloud.android.R;
31 import com.owncloud.android.datamodel.FileDataStorageManager;
32 import com.owncloud.android.datamodel.OCFile;
33 import com.owncloud.android.files.services.FileDownloader;
34
35 import android.accounts.Account;
36 import android.app.Notification;
37 import android.app.NotificationManager;
38 import android.app.PendingIntent;
39 import android.content.ContentProviderClient;
40 import android.content.ContentResolver;
41 import android.content.Context;
42 import android.content.Intent;
43 import android.content.SyncResult;
44 import android.os.Bundle;
45 import android.util.Log;
46 import eu.alefzero.webdav.WebdavEntry;
47 import eu.alefzero.webdav.WebdavUtils;
48
49 /**
50 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
51 * platform ContactOperations provider.
52 *
53 * @author Bartek Przybylski
54 */
55 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
56
57 private final static String TAG = "FileSyncAdapter";
58
59 /* Commented code for ugly performance tests
60 private final static int MAX_DELAYS = 100;
61 private static long[] mResponseDelays = new long[MAX_DELAYS];
62 private static long[] mSaveDelays = new long[MAX_DELAYS];
63 private int mDelaysIndex = 0;
64 private int mDelaysCount = 0;
65 */
66
67 private long mCurrentSyncTime;
68 private boolean mCancellation;
69 private boolean mIsManualSync;
70 private boolean mRightSync;
71
72 public FileSyncAdapter(Context context, boolean autoInitialize) {
73 super(context, autoInitialize);
74 }
75
76 @Override
77 public synchronized void onPerformSync(Account account, Bundle extras,
78 String authority, ContentProviderClient provider,
79 SyncResult syncResult) {
80
81 mCancellation = false;
82 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
83 mRightSync = true;
84
85 this.setAccount(account);
86 this.setContentProvider(provider);
87 this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
88
89 /* Commented code for ugly performance tests
90 mDelaysIndex = 0;
91 mDelaysCount = 0;
92 */
93
94 Log.d(TAG, "syncing owncloud account " + account.name);
95
96 sendStickyBroadcast(true, null); // message to signal the start to the UI
97
98 String uri = getUri().toString();
99 PropFindMethod query = null;
100 try {
101 mCurrentSyncTime = System.currentTimeMillis();
102 query = new PropFindMethod(uri + "/");
103 int status = getClient().executeMethod(query);
104 if (status != HttpStatus.SC_UNAUTHORIZED) {
105 MultiStatus resp = query.getResponseBodyAsMultiStatus();
106
107 if (resp.getResponses().length > 0) {
108 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());
109 OCFile file = fillOCFile(we);
110 file.setParentId(0);
111 getStorageManager().saveFile(file);
112 if (!mCancellation) {
113 fetchData(uri, syncResult, file.getFileId());
114 }
115 }
116
117 } else {
118 syncResult.stats.numAuthExceptions++;
119 }
120 } catch (IOException e) {
121 syncResult.stats.numIoExceptions++;
122 logException(e, uri + "/");
123
124 } catch (DavException e) {
125 syncResult.stats.numParseExceptions++;
126 logException(e, uri + "/");
127
128 } catch (Exception e) {
129 // TODO something smart with syncresult
130 logException(e, uri + "/");
131 mRightSync = false;
132
133 } finally {
134 if (query != null)
135 query.releaseConnection(); // let the connection available for other methods
136 mRightSync &= (syncResult.stats.numIoExceptions == 0 && syncResult.stats.numAuthExceptions == 0 && syncResult.stats.numParseExceptions == 0);
137 if (!mRightSync && mIsManualSync) {
138 /// don't let the system synchronization manager retries MANUAL synchronizations
139 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
140 syncResult.tooManyRetries = true;
141
142 /// notify the user about the failure of MANUAL synchronization
143 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
144 notification.flags |= Notification.FLAG_AUTO_CANCEL;
145 // TODO put something smart in the contentIntent below
146 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
147 notification.setLatestEventInfo(getContext().getApplicationContext(),
148 getContext().getString(R.string.sync_fail_ticker),
149 String.format(getContext().getString(R.string.sync_fail_content), account.name),
150 notification.contentIntent);
151 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
152 }
153 sendStickyBroadcast(false, null); // message to signal the end to the UI
154 }
155
156 /* Commented code for ugly performance tests
157 long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;
158 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
159 sum += mResponseDelays[i];
160 max = Math.max(max, mResponseDelays[i]);
161 min = Math.min(min, mResponseDelays[i]);
162 }
163 mean = sum / mDelaysCount;
164 Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
165
166 sum = 0; max = 0; min = Long.MAX_VALUE;
167 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
168 sum += mSaveDelays[i];
169 max = Math.max(max, mSaveDelays[i]);
170 min = Math.min(min, mSaveDelays[i]);
171 }
172 mean = sum / mDelaysCount;
173 Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
174 Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);
175 */
176
177 }
178
179 private void fetchData(String uri, SyncResult syncResult, long parentId) {
180 PropFindMethod query = null;
181 try {
182 Log.d(TAG, "fetching " + uri);
183
184 // remote request
185 query = new PropFindMethod(uri);
186 /* Commented code for ugly performance tests
187 long responseDelay = System.currentTimeMillis();
188 */
189 int status = getClient().executeMethod(query);
190 /* Commented code for ugly performance tests
191 responseDelay = System.currentTimeMillis() - responseDelay;
192 Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");
193 */
194 if (status != HttpStatus.SC_UNAUTHORIZED) {
195 MultiStatus resp = query.getResponseBodyAsMultiStatus();
196
197 // insertion or update of files
198 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
199 for (int i = 1; i < resp.getResponses().length; ++i) {
200 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());
201 OCFile file = fillOCFile(we);
202 file.setParentId(parentId);
203 if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&
204 getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&
205 file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())
206 .getModificationTimestamp()) {
207 Intent intent = new Intent(this.getContext(), FileDownloader.class);
208 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
209 intent.putExtra(FileDownloader.EXTRA_FILE, file);
210 /*intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath());
211 intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath());
212 intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength());*/
213 file.setKeepInSync(true);
214 getContext().startService(intent);
215 }
216 if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
217 file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
218
219 // Log.v(TAG, "adding file: " + file);
220 updatedFiles.add(file);
221 if (parentId == 0)
222 parentId = file.getFileId();
223 }
224 /* Commented code for ugly performance tests
225 long saveDelay = System.currentTimeMillis();
226 */
227 getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update
228 /* Commented code for ugly performance tests
229 saveDelay = System.currentTimeMillis() - saveDelay;
230 Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");
231 */
232
233 // removal of obsolete files
234 Vector<OCFile> files = getStorageManager().getDirectoryContent(
235 getStorageManager().getFileById(parentId));
236 OCFile file;
237 String currentSavePath = FileDownloader.getSavePath(getAccount().name);
238 for (int i=0; i < files.size(); ) {
239 file = files.get(i);
240 if (file.getLastSyncDate() != mCurrentSyncTime) {
241 Log.v(TAG, "removing file: " + file);
242 getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
243 files.remove(i);
244 } else {
245 i++;
246 }
247 }
248
249 // recursive fetch
250 for (int i=0; i < files.size() && !mCancellation; i++) {
251 OCFile newFile = files.get(i);
252 if (newFile.getMimetype().equals("DIR")) {
253 fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());
254 }
255 }
256 if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");
257
258 /* Commented code for ugly performance tests
259 mResponseDelays[mDelaysIndex] = responseDelay;
260 mSaveDelays[mDelaysIndex] = saveDelay;
261 mDelaysCount++;
262 mDelaysIndex++;
263 if (mDelaysIndex >= MAX_DELAYS)
264 mDelaysIndex = 0;
265 */
266
267 } else {
268 syncResult.stats.numAuthExceptions++;
269 }
270 } catch (IOException e) {
271 syncResult.stats.numIoExceptions++;
272 logException(e, uri);
273
274 } catch (DavException e) {
275 syncResult.stats.numParseExceptions++;
276 logException(e, uri);
277
278 } catch (Exception e) {
279 // TODO something smart with syncresult
280 mRightSync = false;
281 logException(e, uri);
282
283 } finally {
284 if (query != null)
285 query.releaseConnection(); // let the connection available for other methods
286
287 // synchronized folder -> notice to UI
288 sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());
289 }
290 }
291
292 private OCFile fillOCFile(WebdavEntry we) {
293 OCFile file = new OCFile(we.decodedPath());
294 file.setCreationTimestamp(we.createTimestamp());
295 file.setFileLength(we.contentLength());
296 file.setMimetype(we.contentType());
297 file.setModificationTimestamp(we.modifiedTimesamp());
298 file.setLastSyncDate(mCurrentSyncTime);
299 return file;
300 }
301
302
303 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {
304 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
305 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
306 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
307 if (dirRemotePath != null) {
308 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
309 }
310 getContext().sendStickyBroadcast(i);
311 }
312
313 /**
314 * Called by system SyncManager when a synchronization is required to be cancelled.
315 *
316 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
317 * fetched will be still saved in the database. See onPerformSync implementation.
318 */
319 @Override
320 public void onSyncCanceled() {
321 Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
322 mCancellation = true;
323 super.onSyncCanceled();
324 }
325
326
327 /**
328 * Logs an exception triggered in a synchronization request.
329 *
330 * @param e Caught exception.
331 * @param uri Uri to the remote directory that was fetched when the synchronization failed
332 */
333 private void logException(Exception e, String uri) {
334 if (e instanceof IOException) {
335 Log.e(TAG, "Unrecovered transport exception while synchronizing " + uri + " at " + getAccount().name, e);
336
337 } else if (e instanceof DavException) {
338 Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);
339
340 } else {
341 Log.e(TAG, "Unexpected exception while synchronizing " + uri + " at " + getAccount().name, e);
342 }
343 }
344
345
346 }