Merge branch 'master' into sync_full_folder
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
8 *
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 */
22
23 package com.owncloud.android.syncadapter;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import org.apache.jackrabbit.webdav.DavException;
32
33 import com.owncloud.android.R;
34 import com.owncloud.android.authentication.AuthenticatorActivity;
35 import com.owncloud.android.datamodel.FileDataStorageManager;
36 import com.owncloud.android.datamodel.OCFile;
37 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
38 import com.owncloud.android.operations.RefreshFolderOperation;
39 import com.owncloud.android.operations.UpdateOCVersionOperation;
40 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
41 import com.owncloud.android.lib.common.utils.Log_OC;
42 import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
43
44 import android.accounts.Account;
45 import android.accounts.AccountsException;
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 import android.support.v4.app.NotificationCompat;
56
57 /**
58 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
59 * ownCloud files.
60 *
61 * Performs a full synchronization of the account received in {@link #onPerformSync(Account, Bundle,
62 * String, ContentProviderClient, SyncResult)}.
63 */
64 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
65
66 private final static String TAG = FileSyncAdapter.class.getSimpleName();
67
68 /** Maximum number of failed folder synchronizations that are supported before finishing
69 * the synchronization operation */
70 private static final int MAX_FAILED_RESULTS = 3;
71
72
73 public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() +
74 ".EVENT_FULL_SYNC_START";
75 public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() +
76 ".EVENT_FULL_SYNC_END";
77 public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED =
78 FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
79
80 public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() +
81 ".EXTRA_ACCOUNT_NAME";
82 public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() +
83 ".EXTRA_FOLDER_PATH";
84 public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
85
86
87 /** Time stamp for the current synchronization process, used to distinguish fresh data */
88 private long mCurrentSyncTime;
89
90 /** Flag made 'true' when a request to cancel the synchronization is received */
91 private boolean mCancellation;
92
93 /** When 'true' the process was requested by the user through the user interface;
94 * when 'false', it was requested automatically by the system */
95 private boolean mIsManualSync;
96
97 /** Counter for failed operations in the synchronization process */
98 private int mFailedResultsCounter;
99
100 /** Result of the last failed operation */
101 private RemoteOperationResult mLastFailedResult;
102
103 /** Counter of conflicts found between local and remote files */
104 private int mConflictsFound;
105
106 /** Counter of failed operations in synchronization of kept-in-sync files */
107 private int mFailsInFavouritesFound;
108
109 /** Map of remote and local paths to files that where locally stored in a location out
110 * of the ownCloud folder and couldn't be copied automatically into it */
111 private Map<String, String> mForgottenLocalFiles;
112
113 /** {@link SyncResult} instance to return to the system when the synchronization finish */
114 private SyncResult mSyncResult;
115
116 /** 'True' means that the server supports the share API */
117 private boolean mIsShareSupported;
118
119
120 /**
121 * Creates a {@link FileSyncAdapter}
122 *
123 * {@inheritDoc}
124 */
125 public FileSyncAdapter(Context context, boolean autoInitialize) {
126 super(context, autoInitialize);
127 }
128
129
130 /**
131 * Creates a {@link FileSyncAdapter}
132 *
133 * {@inheritDoc}
134 */
135 public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
136 super(context, autoInitialize, allowParallelSyncs);
137 }
138
139
140 /**
141 * {@inheritDoc}
142 */
143 @Override
144 public synchronized void onPerformSync(Account account, Bundle extras,
145 String authority, ContentProviderClient providerClient,
146 SyncResult syncResult) {
147
148 mCancellation = false;
149 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
150 mFailedResultsCounter = 0;
151 mLastFailedResult = null;
152 mConflictsFound = 0;
153 mFailsInFavouritesFound = 0;
154 mForgottenLocalFiles = new HashMap<String, String>();
155 mSyncResult = syncResult;
156 mSyncResult.fullSyncRequested = false;
157 mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
158
159 this.setAccount(account);
160 this.setContentProviderClient(providerClient);
161 this.setStorageManager(new FileDataStorageManager(account, providerClient));
162
163 try {
164 this.initClientForCurrentAccount();
165 } catch (IOException e) {
166 /// the account is unknown for the Synchronization Manager, unreachable this context,
167 // or can not be authenticated; don't try this again
168 mSyncResult.tooManyRetries = true;
169 notifyFailedSynchronization();
170 return;
171 } catch (AccountsException e) {
172 /// the account is unknown for the Synchronization Manager, unreachable this context,
173 // or can not be authenticated; don't try this again
174 mSyncResult.tooManyRetries = true;
175 notifyFailedSynchronization();
176 return;
177 }
178
179 Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
180 sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
181 // of the synchronization to the UI
182
183 try {
184 updateOCVersion();
185 mCurrentSyncTime = System.currentTimeMillis();
186 if (!mCancellation) {
187 synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
188
189 } else {
190 Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " +
191 "because cancelation request");
192 }
193
194
195 } finally {
196 // it's important making this although very unexpected errors occur;
197 // that's the reason for the finally
198
199 if (mFailedResultsCounter > 0 && mIsManualSync) {
200 /// don't let the system synchronization manager retries MANUAL synchronizations
201 // (be careful: "MANUAL" currently includes the synchronization requested when
202 // a new account is created and when the user changes the current account)
203 mSyncResult.tooManyRetries = true;
204
205 /// notify the user about the failure of MANUAL synchronization
206 notifyFailedSynchronization();
207 }
208 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
209 notifyFailsInFavourites();
210 }
211 if (mForgottenLocalFiles.size() > 0) {
212 notifyForgottenLocalFiles();
213 }
214 sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
215 // the end to the UI
216 }
217
218 }
219
220 /**
221 * Called by system SyncManager when a synchronization is required to be cancelled.
222 *
223 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
224 * before a new folder is fetched. Data of the last folder synchronized will be still
225 * locally saved.
226 *
227 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
228 * and {@link #synchronizeFolder(OCFile)}.
229 */
230 @Override
231 public void onSyncCanceled() {
232 Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
233 mCancellation = true;
234 super.onSyncCanceled();
235 }
236
237
238 /**
239 * Updates the locally stored version value of the ownCloud server
240 */
241 private void updateOCVersion() {
242 UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
243 RemoteOperationResult result = update.execute(getClient());
244 if (!result.isSuccess()) {
245 mLastFailedResult = result;
246 } else {
247 mIsShareSupported = update.getOCVersion().isSharedSupported();
248 }
249 }
250
251
252 /**
253 * Synchronizes the list of files contained in a folder identified with its remote path.
254 *
255 * Fetches the list and properties of the files contained in the given folder, including their
256 * properties, and updates the local database with them.
257 *
258 * Enters in the child folders to synchronize their contents also, following a recursive
259 * depth first strategy.
260 *
261 * @param folder Folder to synchronize.
262 */
263 private void synchronizeFolder(OCFile folder) {
264
265 if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
266 return;
267
268 // folder synchronization
269 RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
270 mCurrentSyncTime,
271 true,
272 mIsShareSupported,
273 false,
274 getStorageManager(),
275 getAccount(),
276 getContext()
277 );
278 RemoteOperationResult result = synchFolderOp.execute(getClient());
279
280
281 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
282 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
283
284 // check the result of synchronizing the folder
285 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
286
287 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
288 mConflictsFound += synchFolderOp.getConflictsFound();
289 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
290 }
291 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
292 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
293 }
294 if (result.isSuccess()) {
295 // synchronize children folders
296 List<OCFile> children = synchFolderOp.getChildren();
297 // beware of the 'hidden' recursion here!
298 syncChildren(children);
299 }
300
301 } else {
302 // in failures, the statistics for the global result are updated
303 if ( result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
304 result.isIdPRedirection()
305 ) {
306 mSyncResult.stats.numAuthExceptions++;
307
308 } else if (result.getException() instanceof DavException) {
309 mSyncResult.stats.numParseExceptions++;
310
311 } else if (result.getException() instanceof IOException) {
312 mSyncResult.stats.numIoExceptions++;
313 }
314 mFailedResultsCounter++;
315 mLastFailedResult = result;
316 }
317
318 }
319
320 /**
321 * Checks if a failed result should terminate the synchronization process immediately,
322 * according to OUR OWN POLICY
323 *
324 * @param failedResult Remote operation result to check.
325 * @return 'True' if the result should immediately finish the
326 * synchronization
327 */
328 private boolean isFinisher(RemoteOperationResult failedResult) {
329 if (failedResult != null) {
330 RemoteOperationResult.ResultCode code = failedResult.getCode();
331 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
332 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
333 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
334 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
335 }
336 return false;
337 }
338
339 /**
340 * Triggers the synchronization of any folder contained in the list of received files.
341 *
342 * No consideration of etag here because it MUST walk down anyway, in case that kept-in-sync files
343 * have local changes.
344 *
345 * @param files Files to recursively synchronize.
346 */
347 private void syncChildren(List<OCFile> files) {
348 int i;
349 OCFile newFile;
350 for (i=0; i < files.size() && !mCancellation; i++) {
351 newFile = files.get(i);
352 if (newFile.isFolder()) {
353 synchronizeFolder(newFile);
354 }
355 }
356
357 if (mCancellation && i <files.size()) Log_OC.d(TAG,
358 "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
359 " due to cancelation request");
360 }
361
362
363 /**
364 * Sends a message to any application component interested in the progress of the
365 * synchronization.
366 *
367 * @param event Event in the process of synchronization to be notified.
368 * @param dirRemotePath Remote path of the folder target of the event occurred.
369 * @param result Result of an individual {@ SynchronizeFolderOperation},
370 * if completed; may be null.
371 */
372 private void sendLocalBroadcast(String event, String dirRemotePath,
373 RemoteOperationResult result) {
374 Log_OC.d(TAG, "Send broadcast " + event);
375 Intent intent = new Intent(event);
376 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
377 if (dirRemotePath != null) {
378 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
379 }
380 if (result != null) {
381 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
382 }
383 getContext().sendStickyBroadcast(intent);
384 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
385 }
386
387
388
389 /**
390 * Notifies the user about a failed synchronization through the status notification bar
391 */
392 private void notifyFailedSynchronization() {
393 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
394 boolean needsToUpdateCredentials = (
395 mLastFailedResult != null && (
396 mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
397 mLastFailedResult.isIdPRedirection()
398 )
399 );
400 if (needsToUpdateCredentials) {
401 // let the user update credentials with one click
402 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
403 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
404 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
405 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
406 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
407 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
408 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
409 notificationBuilder
410 .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
411 .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
412 .setContentIntent(PendingIntent.getActivity(
413 getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
414 PendingIntent.FLAG_ONE_SHOT
415 ))
416 .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
417 } else {
418 notificationBuilder
419 .setTicker(i18n(R.string.sync_fail_ticker))
420 .setContentTitle(i18n(R.string.sync_fail_ticker))
421 .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
422 }
423
424 showNotification(R.string.sync_fail_ticker, notificationBuilder);
425 }
426
427
428 /**
429 * Notifies the user about conflicts and strange fails when trying to synchronize the contents
430 * of kept-in-sync files.
431 *
432 * By now, we won't consider a failed synchronization.
433 */
434 private void notifyFailsInFavourites() {
435 if (mFailedResultsCounter > 0) {
436 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
437 notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
438
439 // TODO put something smart in the contentIntent below
440 notificationBuilder
441 .setContentIntent(PendingIntent.getActivity(
442 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
443 ))
444 .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
445 .setContentText(i18n(R.string.sync_fail_in_favourites_content,
446 mFailedResultsCounter + mConflictsFound, mConflictsFound));
447
448 showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
449 } else {
450 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
451 notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
452
453 // TODO put something smart in the contentIntent below
454 notificationBuilder
455 .setContentIntent(PendingIntent.getActivity(
456 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
457 ))
458 .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
459 .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
460
461 showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
462 }
463 }
464
465 /**
466 * Notifies the user about local copies of files out of the ownCloud local directory that
467 * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
468 *
469 * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
470 * It's easy to have synchronization problems if a local file is linked to more than one
471 * remote file.
472 *
473 * We won't consider a synchronization as failed when foreign files can not be copied to
474 * the ownCloud local directory.
475 */
476 private void notifyForgottenLocalFiles() {
477 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
478 notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
479
480 /// includes a pending intent in the notification showing a more detailed explanation
481 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
482 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
483 ArrayList<String> remotePaths = new ArrayList<String>();
484 ArrayList<String> localPaths = new ArrayList<String>();
485 remotePaths.addAll(mForgottenLocalFiles.keySet());
486 localPaths.addAll(mForgottenLocalFiles.values());
487 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
488 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
489 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
490
491 notificationBuilder
492 .setContentIntent(PendingIntent.getActivity(
493 getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
494 ))
495 .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
496 .setContentText(i18n(R.string.sync_foreign_files_forgotten_content,
497 mForgottenLocalFiles.size(), i18n(R.string.app_name)));
498
499 showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
500 }
501
502 /**
503 * Creates a notification builder with some commonly used settings
504 *
505 * @return
506 */
507 private NotificationCompat.Builder createNotificationBuilder() {
508 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
509 notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
510 notificationBuilder.setColor(getContext().getResources().getColor(R.color.primary));
511 return notificationBuilder;
512 }
513
514 /**
515 * Builds and shows the notification
516 *
517 * @param id
518 * @param builder
519 */
520 private void showNotification(int id, NotificationCompat.Builder builder) {
521 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
522 .notify(id, builder.build());
523 }
524 /**
525 * Shorthand translation
526 *
527 * @param key
528 * @param args
529 * @return
530 */
531 private String i18n(int key, Object... args) {
532 return getContext().getString(key, args);
533 }
534 }