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
);
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
;
321 * Checks if a failed result should terminate the synchronization process immediately,
322 * according to OUR OWN POLICY
324 * @param failedResult Remote operation result to check.
325 * @return 'True' if the result should immediately finish the
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
));
340 * Triggers the synchronization of any folder contained in the list of received files.
342 * No consideration of etag here because it MUST walk down anyway, in case that kept-in-sync files
343 * have local changes.
345 * @param files Files to recursively synchronize.
347 private void syncChildren(List
<OCFile
> files
) {
350 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
351 newFile
= files
.get(i
);
352 if (newFile
.isFolder()) {
353 synchronizeFolder(newFile
);
357 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
,
358 "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() +
359 " due to cancelation request");
364 * Sends a message to any application component interested in the progress of the
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.
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
);
380 if (result
!= null
) {
381 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
383 getContext().sendStickyBroadcast(intent
);
384 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
390 * Notifies the user about a failed synchronization through the status notification bar
392 private void notifyFailedSynchronization() {
393 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
394 boolean needsToUpdateCredentials
= (
395 mLastFailedResult
!= null
&& (
396 mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
397 mLastFailedResult
.isIdPRedirection()
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
);
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
416 .setContentText(i18n(R
.string
.sync_fail_content_unauthorized
, getAccount().name
));
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
));
424 showNotification(R
.string
.sync_fail_ticker
, notificationBuilder
);
429 * Notifies the user about conflicts and strange fails when trying to synchronize the contents
430 * of kept-in-sync files.
432 * By now, we won't consider a failed synchronization.
434 private void notifyFailsInFavourites() {
435 if (mFailedResultsCounter
> 0) {
436 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
437 notificationBuilder
.setTicker(i18n(R
.string
.sync_fail_in_favourites_ticker
));
439 // TODO put something smart in the contentIntent below
441 .setContentIntent(PendingIntent
.getActivity(
442 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
444 .setContentTitle(i18n(R
.string
.sync_fail_in_favourites_ticker
))
445 .setContentText(i18n(R
.string
.sync_fail_in_favourites_content
,
446 mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
));
448 showNotification(R
.string
.sync_fail_in_favourites_ticker
, notificationBuilder
);
450 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
451 notificationBuilder
.setTicker(i18n(R
.string
.sync_conflicts_in_favourites_ticker
));
453 // TODO put something smart in the contentIntent below
455 .setContentIntent(PendingIntent
.getActivity(
456 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
458 .setContentTitle(i18n(R
.string
.sync_conflicts_in_favourites_ticker
))
459 .setContentText(i18n(R
.string
.sync_conflicts_in_favourites_ticker
, mConflictsFound
));
461 showNotification(R
.string
.sync_conflicts_in_favourites_ticker
, notificationBuilder
);
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.
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
473 * We won't consider a synchronization as failed when foreign files can not be copied to
474 * the ownCloud local directory.
476 private void notifyForgottenLocalFiles() {
477 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
478 notificationBuilder
.setTicker(i18n(R
.string
.sync_foreign_files_forgotten_ticker
));
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
);
492 .setContentIntent(PendingIntent
.getActivity(
493 getContext(), (int) System
.currentTimeMillis(), explanationIntent
, 0
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
)));
499 showNotification(R
.string
.sync_foreign_files_forgotten_ticker
, notificationBuilder
);
503 * Creates a notification builder with some commonly used settings
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
;
515 * Builds and shows the notification
520 private void showNotification(int id
, NotificationCompat
.Builder builder
) {
521 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
))
522 .notify(id
, builder
.build());
525 * Shorthand translation
531 private String
i18n(int key
, Object
... args
) {
532 return getContext().getString(key
, args
);