1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
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.
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.
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/>.
19 package com
.owncloud
.android
.syncadapter
;
21 import java
.io
.IOException
;
22 import java
.util
.ArrayList
;
23 import java
.util
.HashMap
;
24 import java
.util
.List
;
27 import org
.apache
.jackrabbit
.webdav
.DavException
;
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
;
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
;
57 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
60 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
62 * @author Bartek Przybylski
63 * @author David A. Velasco
65 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
67 private final static String TAG
= FileSyncAdapter
.class.getSimpleName();
69 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
70 private static final int MAX_FAILED_RESULTS
= 3;
73 /** Time stamp for the current synchronization process, used to distinguish fresh data */
74 private long mCurrentSyncTime
;
76 /** Flag made 'true' when a request to cancel the synchronization is received */
77 private boolean mCancellation
;
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
;
82 /** Counter for failed operations in the synchronization process */
83 private int mFailedResultsCounter
;
85 /** Result of the last failed operation */
86 private RemoteOperationResult mLastFailedResult
;
88 /** Counter of conflicts found between local and remote files */
89 private int mConflictsFound
;
91 /** Counter of failed operations in synchronization of kept-in-sync files */
92 private int mFailsInFavouritesFound
;
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
;
97 /** {@link SyncResult} instance to return to the system when the synchronization finish */
98 private SyncResult mSyncResult
;
102 * Creates a {@link FileSyncAdapter}
106 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
107 super(context
, autoInitialize
);
112 * Creates a {@link FileSyncAdapter}
116 public FileSyncAdapter(Context context
, boolean autoInitialize
, boolean allowParallelSyncs
) {
117 super(context
, autoInitialize
, allowParallelSyncs
);
125 public synchronized void onPerformSync(Account account
, Bundle extras
,
126 String authority
, ContentProviderClient providerClient
,
127 SyncResult syncResult
) {
129 mCancellation
= false
;
130 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
131 mFailedResultsCounter
= 0;
132 mLastFailedResult
= null
;
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
140 this.setAccount(account
);
141 this.setContentProviderClient(providerClient
);
142 this.setStorageManager(new FileDataStorageManager(account
, providerClient
));
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();
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();
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
162 mCurrentSyncTime
= System
.currentTimeMillis();
163 if (!mCancellation
) {
164 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
167 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
172 // it's important making this although very unexpected errors occur; that's the reason for the finally
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
;
179 /// notify the user about the failure of MANUAL synchronization
180 notifyFailedSynchronization();
182 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
183 notifyFailsInFavourites();
185 if (mForgottenLocalFiles
.size() > 0) {
186 notifyForgottenLocalFiles();
188 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
194 * Called by system SyncManager when a synchronization is required to be cancelled.
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
200 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
201 * and {@link #synchronizeFolder(String, long)}.
204 public void onSyncCanceled() {
205 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
206 mCancellation
= true
;
207 super.onSyncCanceled();
212 * Updates the locally stored version value of the ownCloud server
214 private void updateOCVersion() {
215 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
216 RemoteOperationResult result
= update
.execute(getClient());
217 if (!result
.isSuccess()) {
218 mLastFailedResult
= result
;
224 * Synchronizes the list of files contained in a folder identified with its remote path.
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.
229 * Enters in the child folders to synchronize their contents also, following a recursive
230 * depth first strategy.
232 * @param folder Folder to synchronize.
234 private void synchronizeFolder(OCFile folder
) {
236 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
241 long currentSyncTime,
242 boolean updateFolderProperties,
243 boolean syncFullAccount,
244 DataStorageManager dataStorageManager,
250 // folder synchronization
251 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
258 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
261 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
262 sendStickyBroadcast(true
, folder
.getRemotePath(), null
);
264 // check the result of synchronizing the folder
265 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
267 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
268 mConflictsFound
+= synchFolderOp
.getConflictsFound();
269 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
271 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
272 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
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!
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
++;
288 } else if (result
.getException() instanceof DavException
) {
289 mSyncResult
.stats
.numParseExceptions
++;
291 } else if (result
.getException() instanceof IOException
) {
292 mSyncResult
.stats
.numIoExceptions
++;
294 mFailedResultsCounter
++;
295 mLastFailedResult
= result
;
301 * Checks if a failed result should terminate the synchronization process immediately, according to
304 * @param failedResult Remote operation result to check.
305 * @return 'True' if the result should immediately finish the synchronization
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
));
319 * Triggers the synchronization of any folder contained in the list of received files.
321 * @param files Files to recursively synchronize.
323 private void fetchChildren(OCFile parent
, List
<OCFile
> files
, boolean parentEtagChanged
) {
325 OCFile newFile
= null
;
327 boolean syncDown
= false
;
328 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
329 newFile
= files
.get(i
);
330 if (newFile
.isFolder()) {
332 etag = newFile.getEtag();
333 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
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
343 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
348 * Sends a message to any application component interested in the progress of the synchronization.
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)
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
);
360 if (result
!= null
) {
361 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
363 getContext().sendStickyBroadcast(i
);
369 * Notifies the user about a failed synchronization through the status notification bar
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()))
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
);
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
);
403 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
408 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
410 * By now, we won't consider a failed synchronization.
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
);
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
);
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.
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.
444 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
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
;
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
);
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
);