Merge branch 'stable'
[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 if (result.getCode() != ResultCode.FILE_NOT_FOUND) {
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 } // else, ResultCode.FILE_NOT_FOUND is ignored, remote folder was
318 // removed from other thread or other client during the synchronization,
319 // before this thread fetched its contents
320
321 }
322
323 /**
324 * Checks if a failed result should terminate the synchronization process immediately,
325 * according to OUR OWN POLICY
326 *
327 * @param failedResult Remote operation result to check.
328 * @return 'True' if the result should immediately finish the
329 * synchronization
330 */
331 private boolean isFinisher(RemoteOperationResult failedResult) {
332 if (failedResult != null) {
333 RemoteOperationResult.ResultCode code = failedResult.getCode();
334 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
335 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
336 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
337 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
338 }
339 return false;
340 }
341
342 /**
343 * Triggers the synchronization of any folder contained in the list of received files.
344 *
345 * No consideration of etag here because it MUST walk down anyway, in case that kept-in-sync files
346 * have local changes.
347 *
348 * @param files Files to recursively synchronize.
349 */
350 private void syncChildren(List<OCFile> files) {
351 int i;
352 OCFile newFile;
353 for (i=0; i < files.size() && !mCancellation; i++) {
354 newFile = files.get(i);
355 if (newFile.isFolder()) {
356 synchronizeFolder(newFile);
357 }
358 }
359
360 if (mCancellation && i <files.size()) Log_OC.d(TAG,
361 "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
362 " due to cancelation request");
363 }
364
365
366 /**
367 * Sends a message to any application component interested in the progress of the
368 * synchronization.
369 *
370 * @param event Event in the process of synchronization to be notified.
371 * @param dirRemotePath Remote path of the folder target of the event occurred.
372 * @param result Result of an individual {@ SynchronizeFolderOperation},
373 * if completed; may be null.
374 */
375 private void sendLocalBroadcast(String event, String dirRemotePath,
376 RemoteOperationResult result) {
377 Log_OC.d(TAG, "Send broadcast " + event);
378 Intent intent = new Intent(event);
379 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
380 if (dirRemotePath != null) {
381 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
382 }
383 if (result != null) {
384 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
385 }
386 getContext().sendStickyBroadcast(intent);
387 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
388 }
389
390
391
392 /**
393 * Notifies the user about a failed synchronization through the status notification bar
394 */
395 private void notifyFailedSynchronization() {
396 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
397 boolean needsToUpdateCredentials = (
398 mLastFailedResult != null && (
399 mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
400 mLastFailedResult.isIdPRedirection()
401 )
402 );
403 if (needsToUpdateCredentials) {
404 // let the user update credentials with one click
405 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
406 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
407 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
408 AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
409 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
410 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
411 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
412 notificationBuilder
413 .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
414 .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
415 .setContentIntent(PendingIntent.getActivity(
416 getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
417 PendingIntent.FLAG_ONE_SHOT
418 ))
419 .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
420 } else {
421 notificationBuilder
422 .setTicker(i18n(R.string.sync_fail_ticker))
423 .setContentTitle(i18n(R.string.sync_fail_ticker))
424 .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
425 }
426
427 showNotification(R.string.sync_fail_ticker, notificationBuilder);
428 }
429
430
431 /**
432 * Notifies the user about conflicts and strange fails when trying to synchronize the contents
433 * of kept-in-sync files.
434 *
435 * By now, we won't consider a failed synchronization.
436 */
437 private void notifyFailsInFavourites() {
438 if (mFailedResultsCounter > 0) {
439 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
440 notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
441
442 // TODO put something smart in the contentIntent below
443 notificationBuilder
444 .setContentIntent(PendingIntent.getActivity(
445 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
446 ))
447 .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
448 .setContentText(i18n(R.string.sync_fail_in_favourites_content,
449 mFailedResultsCounter + mConflictsFound, mConflictsFound));
450
451 showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
452 } else {
453 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
454 notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
455
456 // TODO put something smart in the contentIntent below
457 notificationBuilder
458 .setContentIntent(PendingIntent.getActivity(
459 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
460 ))
461 .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
462 .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
463
464 showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
465 }
466 }
467
468 /**
469 * Notifies the user about local copies of files out of the ownCloud local directory that
470 * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
471 *
472 * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
473 * It's easy to have synchronization problems if a local file is linked to more than one
474 * remote file.
475 *
476 * We won't consider a synchronization as failed when foreign files can not be copied to
477 * the ownCloud local directory.
478 */
479 private void notifyForgottenLocalFiles() {
480 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
481 notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
482
483 /// includes a pending intent in the notification showing a more detailed explanation
484 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
485 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
486 ArrayList<String> remotePaths = new ArrayList<String>();
487 ArrayList<String> localPaths = new ArrayList<String>();
488 remotePaths.addAll(mForgottenLocalFiles.keySet());
489 localPaths.addAll(mForgottenLocalFiles.values());
490 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
491 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
492 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
493
494 notificationBuilder
495 .setContentIntent(PendingIntent.getActivity(
496 getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
497 ))
498 .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
499 .setContentText(i18n(R.string.sync_foreign_files_forgotten_content,
500 mForgottenLocalFiles.size(), i18n(R.string.app_name)));
501
502 showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
503 }
504
505 /**
506 * Creates a notification builder with some commonly used settings
507 *
508 * @return
509 */
510 private NotificationCompat.Builder createNotificationBuilder() {
511 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
512 notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
513 notificationBuilder.setColor(getContext().getResources().getColor(R.color.primary));
514 return notificationBuilder;
515 }
516
517 /**
518 * Builds and shows the notification
519 *
520 * @param id
521 * @param builder
522 */
523 private void showNotification(int id, NotificationCompat.Builder builder) {
524 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
525 .notify(id, builder.build());
526 }
527 /**
528 * Shorthand translation
529 *
530 * @param key
531 * @param args
532 * @return
533 */
534 private String i18n(int key, Object... args) {
535 return getContext().getString(key, args);
536 }
537 }