2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
23 package com
.owncloud
.android
.syncadapter
;
25 import java
.io
.IOException
;
26 import java
.util
.ArrayList
;
27 import java
.util
.HashMap
;
28 import java
.util
.List
;
31 import org
.apache
.jackrabbit
.webdav
.DavException
;
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
;
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
;
58 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
61 * Performs a full synchronization of the account received in {@link #onPerformSync(Account, Bundle,
62 * String, ContentProviderClient, SyncResult)}.
64 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
66 private final static String TAG
= FileSyncAdapter
.class.getSimpleName();
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;
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";
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() +
84 public static final String EXTRA_RESULT
= FileSyncAdapter
.class.getName() + ".EXTRA_RESULT";
87 /** Time stamp for the current synchronization process, used to distinguish fresh data */
88 private long mCurrentSyncTime
;
90 /** Flag made 'true' when a request to cancel the synchronization is received */
91 private boolean mCancellation
;
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
;
97 /** Counter for failed operations in the synchronization process */
98 private int mFailedResultsCounter
;
100 /** Result of the last failed operation */
101 private RemoteOperationResult mLastFailedResult
;
103 /** Counter of conflicts found between local and remote files */
104 private int mConflictsFound
;
106 /** Counter of failed operations in synchronization of kept-in-sync files */
107 private int mFailsInFavouritesFound
;
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
;
113 /** {@link SyncResult} instance to return to the system when the synchronization finish */
114 private SyncResult mSyncResult
;
116 /** 'True' means that the server supports the share API */
117 private boolean mIsShareSupported
;
121 * Creates a {@link FileSyncAdapter}
125 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
126 super(context
, autoInitialize
);
131 * Creates a {@link FileSyncAdapter}
135 public FileSyncAdapter(Context context
, boolean autoInitialize
, boolean allowParallelSyncs
) {
136 super(context
, autoInitialize
, allowParallelSyncs
);
144 public synchronized void onPerformSync(Account account
, Bundle extras
,
145 String authority
, ContentProviderClient providerClient
,
146 SyncResult syncResult
) {
148 mCancellation
= false
;
149 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
150 mFailedResultsCounter
= 0;
151 mLastFailedResult
= null
;
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
159 this.setAccount(account
);
160 this.setContentProviderClient(providerClient
);
161 this.setStorageManager(new FileDataStorageManager(account
, providerClient
));
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();
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();
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
185 mCurrentSyncTime
= System
.currentTimeMillis();
186 if (!mCancellation
) {
187 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
190 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder " +
191 "because cancelation request");
196 // it's important making this although very unexpected errors occur;
197 // that's the reason for the finally
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
;
205 /// notify the user about the failure of MANUAL synchronization
206 notifyFailedSynchronization();
208 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
209 notifyFailsInFavourites();
211 if (mForgottenLocalFiles
.size() > 0) {
212 notifyForgottenLocalFiles();
214 sendLocalBroadcast(EVENT_FULL_SYNC_END
, null
, mLastFailedResult
); // message to signal
221 * Called by system SyncManager when a synchronization is required to be cancelled.
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
227 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
228 * and {@link #synchronizeFolder(OCFile)}.
231 public void onSyncCanceled() {
232 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
233 mCancellation
= true
;
234 super.onSyncCanceled();
239 * Updates the locally stored version value of the ownCloud server
241 private void updateOCVersion() {
242 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
243 RemoteOperationResult result
= update
.execute(getClient());
244 if (!result
.isSuccess()) {
245 mLastFailedResult
= result
;
247 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
253 * Synchronizes the list of files contained in a folder identified with its remote path.
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.
258 * Enters in the child folders to synchronize their contents also, following a recursive
259 * depth first strategy.
261 * @param folder Folder to synchronize.
263 private void synchronizeFolder(OCFile folder
) {
265 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
268 // folder synchronization
269 RefreshFolderOperation synchFolderOp
= new RefreshFolderOperation( folder
,
278 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
281 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
282 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
, folder
.getRemotePath(), result
);
284 // check the result of synchronizing the folder
285 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
287 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
288 mConflictsFound
+= synchFolderOp
.getConflictsFound();
289 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
291 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
292 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
294 if (result
.isSuccess()) {
295 // synchronize children folders
296 List
<OCFile
> children
= synchFolderOp
.getChildren();
297 // beware of the 'hidden' recursion here!
298 syncChildren(children
);
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()
306 mSyncResult
.stats
.numAuthExceptions
++;
308 } else if (result
.getException() instanceof DavException
) {
309 mSyncResult
.stats
.numParseExceptions
++;
311 } else if (result
.getException() instanceof IOException
) {
312 mSyncResult
.stats
.numIoExceptions
++;
314 mFailedResultsCounter
++;
315 mLastFailedResult
= result
;
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
324 * Checks if a failed result should terminate the synchronization process immediately,
325 * according to OUR OWN POLICY
327 * @param failedResult Remote operation result to check.
328 * @return 'True' if the result should immediately finish the
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
));
343 * Triggers the synchronization of any folder contained in the list of received files.
345 * No consideration of etag here because it MUST walk down anyway, in case that kept-in-sync files
346 * have local changes.
348 * @param files Files to recursively synchronize.
350 private void syncChildren(List
<OCFile
> files
) {
353 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
354 newFile
= files
.get(i
);
355 if (newFile
.isFolder()) {
356 synchronizeFolder(newFile
);
360 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
,
361 "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() +
362 " due to cancelation request");
367 * Sends a message to any application component interested in the progress of the
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.
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
);
383 if (result
!= null
) {
384 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
386 getContext().sendStickyBroadcast(intent
);
387 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
393 * Notifies the user about a failed synchronization through the status notification bar
395 private void notifyFailedSynchronization() {
396 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
397 boolean needsToUpdateCredentials
= (
398 mLastFailedResult
!= null
&& (
399 mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
400 mLastFailedResult
.isIdPRedirection()
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
);
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
419 .setContentText(i18n(R
.string
.sync_fail_content_unauthorized
, getAccount().name
));
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
));
427 showNotification(R
.string
.sync_fail_ticker
, notificationBuilder
);
432 * Notifies the user about conflicts and strange fails when trying to synchronize the contents
433 * of kept-in-sync files.
435 * By now, we won't consider a failed synchronization.
437 private void notifyFailsInFavourites() {
438 if (mFailedResultsCounter
> 0) {
439 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
440 notificationBuilder
.setTicker(i18n(R
.string
.sync_fail_in_favourites_ticker
));
442 // TODO put something smart in the contentIntent below
444 .setContentIntent(PendingIntent
.getActivity(
445 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
447 .setContentTitle(i18n(R
.string
.sync_fail_in_favourites_ticker
))
448 .setContentText(i18n(R
.string
.sync_fail_in_favourites_content
,
449 mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
));
451 showNotification(R
.string
.sync_fail_in_favourites_ticker
, notificationBuilder
);
453 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
454 notificationBuilder
.setTicker(i18n(R
.string
.sync_conflicts_in_favourites_ticker
));
456 // TODO put something smart in the contentIntent below
458 .setContentIntent(PendingIntent
.getActivity(
459 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
461 .setContentTitle(i18n(R
.string
.sync_conflicts_in_favourites_ticker
))
462 .setContentText(i18n(R
.string
.sync_conflicts_in_favourites_ticker
, mConflictsFound
));
464 showNotification(R
.string
.sync_conflicts_in_favourites_ticker
, notificationBuilder
);
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.
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
476 * We won't consider a synchronization as failed when foreign files can not be copied to
477 * the ownCloud local directory.
479 private void notifyForgottenLocalFiles() {
480 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
481 notificationBuilder
.setTicker(i18n(R
.string
.sync_foreign_files_forgotten_ticker
));
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
);
495 .setContentIntent(PendingIntent
.getActivity(
496 getContext(), (int) System
.currentTimeMillis(), explanationIntent
, 0
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
)));
502 showNotification(R
.string
.sync_foreign_files_forgotten_ticker
, notificationBuilder
);
506 * Creates a notification builder with some commonly used settings
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
;
518 * Builds and shows the notification
523 private void showNotification(int id
, NotificationCompat
.Builder builder
) {
524 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
))
525 .notify(id
, builder
.build());
528 * Shorthand translation
534 private String
i18n(int key
, Object
... args
) {
535 return getContext().getString(key
, args
);