e7867e2d766c090337fe3e937a3ab727f12a08f4
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.apache.jackrabbit.webdav.DavException;
28
29 import com.owncloud.android.MainApp;
30 import com.owncloud.android.R;
31 import com.owncloud.android.authentication.AuthenticatorActivity;
32 import com.owncloud.android.datamodel.FileDataStorageManager;
33 import com.owncloud.android.datamodel.OCFile;
34 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
35 import com.owncloud.android.operations.SynchronizeFolderOperation;
36 import com.owncloud.android.operations.UpdateOCVersionOperation;
37 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;
38 import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
39 import com.owncloud.android.utils.DisplayUtils;
40 import com.owncloud.android.utils.Log_OC;
41
42
43 import android.accounts.Account;
44 import android.accounts.AccountsException;
45 import android.app.Notification;
46 import android.app.NotificationManager;
47 import android.app.PendingIntent;
48 import android.content.AbstractThreadedSyncAdapter;
49 import android.content.ContentProviderClient;
50 import android.content.ContentResolver;
51 import android.content.Context;
52 import android.content.Intent;
53 import android.content.SyncResult;
54 import android.os.Bundle;
55
56 /**
57 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
58 * ownCloud files.
59 *
60 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
61 *
62 * @author Bartek Przybylski
63 * @author David A. Velasco
64 */
65 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
66
67 private final static String TAG = FileSyncAdapter.class.getSimpleName();
68
69 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
70 private static final int MAX_FAILED_RESULTS = 3;
71
72
73 /** Time stamp for the current synchronization process, used to distinguish fresh data */
74 private long mCurrentSyncTime;
75
76 /** Flag made 'true' when a request to cancel the synchronization is received */
77 private boolean mCancellation;
78
79 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
80 private boolean mIsManualSync;
81
82 /** Counter for failed operations in the synchronization process */
83 private int mFailedResultsCounter;
84
85 /** Result of the last failed operation */
86 private RemoteOperationResult mLastFailedResult;
87
88 /** Counter of conflicts found between local and remote files */
89 private int mConflictsFound;
90
91 /** Counter of failed operations in synchronization of kept-in-sync files */
92 private int mFailsInFavouritesFound;
93
94 /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
95 private Map<String, String> mForgottenLocalFiles;
96
97 /** {@link SyncResult} instance to return to the system when the synchronization finish */
98 private SyncResult mSyncResult;
99
100
101 /**
102 * Creates a {@link FileSyncAdapter}
103 *
104 * {@inheritDoc}
105 */
106 public FileSyncAdapter(Context context, boolean autoInitialize) {
107 super(context, autoInitialize);
108 }
109
110
111 /**
112 * Creates a {@link FileSyncAdapter}
113 *
114 * {@inheritDoc}
115 */
116 public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
117 super(context, autoInitialize, allowParallelSyncs);
118 }
119
120
121 /**
122 * {@inheritDoc}
123 */
124 @Override
125 public synchronized void onPerformSync(Account account, Bundle extras,
126 String authority, ContentProviderClient providerClient,
127 SyncResult syncResult) {
128
129 mCancellation = false;
130 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
131 mFailedResultsCounter = 0;
132 mLastFailedResult = null;
133 mConflictsFound = 0;
134 mFailsInFavouritesFound = 0;
135 mForgottenLocalFiles = new HashMap<String, String>();
136 mSyncResult = syncResult;
137 mSyncResult.fullSyncRequested = false;
138 mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
139
140 this.setAccount(account);
141 this.setContentProviderClient(providerClient);
142 this.setStorageManager(new FileDataStorageManager(account, providerClient));
143 try {
144 this.initClientForCurrentAccount();
145 } catch (IOException e) {
146 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
147 mSyncResult.tooManyRetries = true;
148 notifyFailedSynchronization();
149 return;
150 } catch (AccountsException e) {
151 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
152 mSyncResult.tooManyRetries = true;
153 notifyFailedSynchronization();
154 return;
155 }
156
157 Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
158 sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
159
160 try {
161 updateOCVersion();
162 mCurrentSyncTime = System.currentTimeMillis();
163 if (!mCancellation) {
164 synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
165
166 } else {
167 Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder because cancelation request");
168 }
169
170
171 } finally {
172 // it's important making this although very unexpected errors occur; that's the reason for the finally
173
174 if (mFailedResultsCounter > 0 && mIsManualSync) {
175 /// don't let the system synchronization manager retries MANUAL synchronizations
176 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
177 mSyncResult.tooManyRetries = true;
178
179 /// notify the user about the failure of MANUAL synchronization
180 notifyFailedSynchronization();
181 }
182 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
183 notifyFailsInFavourites();
184 }
185 if (mForgottenLocalFiles.size() > 0) {
186 notifyForgottenLocalFiles();
187 }
188 sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
189 }
190
191 }
192
193 /**
194 * Called by system SyncManager when a synchronization is required to be cancelled.
195 *
196 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
197 * before a new folder is fetched. Data of the last folder synchronized will be still
198 * locally saved.
199 *
200 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
201 * and {@link #synchronizeFolder(String, long)}.
202 */
203 @Override
204 public void onSyncCanceled() {
205 Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
206 mCancellation = true;
207 super.onSyncCanceled();
208 }
209
210
211 /**
212 * Updates the locally stored version value of the ownCloud server
213 */
214 private void updateOCVersion() {
215 UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
216 RemoteOperationResult result = update.execute(getClient());
217 if (!result.isSuccess()) {
218 mLastFailedResult = result;
219 }
220 }
221
222
223 /**
224 * Synchronizes the list of files contained in a folder identified with its remote path.
225 *
226 * Fetches the list and properties of the files contained in the given folder, including their
227 * properties, and updates the local database with them.
228 *
229 * Enters in the child folders to synchronize their contents also, following a recursive
230 * depth first strategy.
231 *
232 * @param folder Folder to synchronize.
233 */
234 private void synchronizeFolder(OCFile folder) {
235
236 if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
237 return;
238
239 /*
240 OCFile folder,
241 long currentSyncTime,
242 boolean updateFolderProperties,
243 boolean syncFullAccount,
244 DataStorageManager dataStorageManager,
245 Account account,
246 Context context ) {
247
248 }
249 */
250 // folder synchronization
251 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( folder,
252 mCurrentSyncTime,
253 true,
254 getStorageManager(),
255 getAccount(),
256 getContext()
257 );
258 RemoteOperationResult result = synchFolderOp.execute(getClient());
259
260
261 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
262 sendStickyBroadcast(true, folder.getRemotePath(), null);
263
264 // check the result of synchronizing the folder
265 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
266
267 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
268 mConflictsFound += synchFolderOp.getConflictsFound();
269 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
270 }
271 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
272 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
273 }
274 if (result.isSuccess()) {
275 // synchronize children folders
276 List<OCFile> children = synchFolderOp.getChildren();
277 fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
278 }
279
280 } else {
281 // in failures, the statistics for the global result are updated
282 if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
283 ( result.isIdPRedirection() &&
284 getClient().getCredentials() == null )) {
285 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))) {
286 mSyncResult.stats.numAuthExceptions++;
287
288 } else if (result.getException() instanceof DavException) {
289 mSyncResult.stats.numParseExceptions++;
290
291 } else if (result.getException() instanceof IOException) {
292 mSyncResult.stats.numIoExceptions++;
293 }
294 mFailedResultsCounter++;
295 mLastFailedResult = result;
296 }
297
298 }
299
300 /**
301 * Checks if a failed result should terminate the synchronization process immediately, according to
302 * OUR OWN POLICY
303 *
304 * @param failedResult Remote operation result to check.
305 * @return 'True' if the result should immediately finish the synchronization
306 */
307 private boolean isFinisher(RemoteOperationResult failedResult) {
308 if (failedResult != null) {
309 RemoteOperationResult.ResultCode code = failedResult.getCode();
310 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
311 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
312 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
313 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
314 }
315 return false;
316 }
317
318 /**
319 * Triggers the synchronization of any folder contained in the list of received files.
320 *
321 * @param files Files to recursively synchronize.
322 */
323 private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
324 int i;
325 OCFile newFile = null;
326 String etag = null;
327 boolean syncDown = false;
328 for (i=0; i < files.size() && !mCancellation; i++) {
329 newFile = files.get(i);
330 if (newFile.isFolder()) {
331 /*
332 etag = newFile.getEtag();
333 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
334 if(syncDown) { */
335 synchronizeFolder(newFile);
336 // update the size of the parent folder again after recursive synchronization
337 //getStorageManager().updateFolderSize(parent.getFileId());
338 sendStickyBroadcast(true, parent.getRemotePath(), null); // notify again to refresh size in UI
339 //}
340 }
341 }
342
343 if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " due to cancelation request");
344 }
345
346
347 /**
348 * Sends a message to any application component interested in the progress of the synchronization.
349 *
350 * @param inProgress 'True' when the synchronization progress is not finished.
351 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
352 */
353 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
354 Intent i = new Intent(FileSyncService.getSyncMessage());
355 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
356 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
357 if (dirRemotePath != null) {
358 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
359 }
360 if (result != null) {
361 i.putExtra(FileSyncService.SYNC_RESULT, result);
362 }
363 getContext().sendStickyBroadcast(i);
364 }
365
366
367
368 /**
369 * Notifies the user about a failed synchronization through the status notification bar
370 */
371 private void notifyFailedSynchronization() {
372 Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
373 notification.flags |= Notification.FLAG_AUTO_CANCEL;
374 boolean needsToUpdateCredentials = (mLastFailedResult != null &&
375 ( mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
376 ( mLastFailedResult.isIdPRedirection() &&
377 getClient().getCredentials() == null )
378 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))
379 )
380 );
381 // TODO put something smart in the contentIntent below for all the possible errors
382 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
383 if (needsToUpdateCredentials) {
384 // let the user update credentials with one click
385 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
386 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
387 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
388 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
389 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
390 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
391 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
392 notification.contentIntent = PendingIntent.getActivity(getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
393 notification.setLatestEventInfo(getContext().getApplicationContext(),
394 getContext().getString(R.string.sync_fail_ticker),
395 String.format(getContext().getString(R.string.sync_fail_content_unauthorized), getAccount().name),
396 notification.contentIntent);
397 } else {
398 notification.setLatestEventInfo(getContext().getApplicationContext(),
399 getContext().getString(R.string.sync_fail_ticker),
400 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
401 notification.contentIntent);
402 }
403 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
404 }
405
406
407 /**
408 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
409 *
410 * By now, we won't consider a failed synchronization.
411 */
412 private void notifyFailsInFavourites() {
413 if (mFailedResultsCounter > 0) {
414 Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
415 notification.flags |= Notification.FLAG_AUTO_CANCEL;
416 // TODO put something smart in the contentIntent below
417 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
418 notification.setLatestEventInfo(getContext().getApplicationContext(),
419 getContext().getString(R.string.sync_fail_in_favourites_ticker),
420 String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
421 notification.contentIntent);
422 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
423
424 } else {
425 Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
426 notification.flags |= Notification.FLAG_AUTO_CANCEL;
427 // TODO put something smart in the contentIntent below
428 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
429 notification.setLatestEventInfo(getContext().getApplicationContext(),
430 getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
431 String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
432 notification.contentIntent);
433 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
434 }
435 }
436
437 /**
438 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
439 * copying them inside the ownCloud local directory was not possible.
440 *
441 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
442 * synchronization problems if a local file is linked to more than one remote file.
443 *
444 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
445 */
446 private void notifyForgottenLocalFiles() {
447 Notification notification = new Notification(DisplayUtils.getSeasonalIconId(), getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
448 notification.flags |= Notification.FLAG_AUTO_CANCEL;
449
450 /// includes a pending intent in the notification showing a more detailed explanation
451 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
452 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
453 ArrayList<String> remotePaths = new ArrayList<String>();
454 ArrayList<String> localPaths = new ArrayList<String>();
455 remotePaths.addAll(mForgottenLocalFiles.keySet());
456 localPaths.addAll(mForgottenLocalFiles.values());
457 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
458 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
459 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
460
461 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
462 notification.setLatestEventInfo(getContext().getApplicationContext(),
463 getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
464 String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size(), getContext().getString(R.string.app_name)),
465 notification.contentIntent);
466 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
467
468 }
469
470
471 }