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
.R
;
30 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
31 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
32 import com
.owncloud
.android
.datamodel
.OCFile
;
33 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
34 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
35 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
36 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
37 import com
.owncloud
.android
.ui
.activity
.ErrorsWhileCopyingHandlerActivity
;
38 import com
.owncloud
.android
.utils
.DisplayUtils
;
39 import com
.owncloud
.android
.utils
.Log_OC
;
42 import android
.accounts
.Account
;
43 import android
.accounts
.AccountsException
;
44 import android
.app
.Notification
;
45 import android
.app
.NotificationManager
;
46 import android
.app
.PendingIntent
;
47 import android
.content
.AbstractThreadedSyncAdapter
;
48 import android
.content
.ContentProviderClient
;
49 import android
.content
.ContentResolver
;
50 import android
.content
.Context
;
51 import android
.content
.Intent
;
52 import android
.content
.SyncResult
;
53 import android
.os
.Bundle
;
54 import android
.support
.v4
.content
.LocalBroadcastManager
;
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 public static final String EVENT_FULL_SYNC_START
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_START";
74 public static final String EVENT_FULL_SYNC_END
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_END";
75 public static final String EVENT_FOLDER_CONTENTS_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FOLDER_CONTENTS_SYNCED";
76 public static final String EVENT_FOLDER_SIZE_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FOLDER_SIZE_SYNCED";
78 public static final String EXTRA_ACCOUNT_NAME
= FileSyncAdapter
.class.getName() + ".EXTRA_ACCOUNT_NAME";
79 public static final String EXTRA_FOLDER_PATH
= FileSyncAdapter
.class.getName() + ".EXTRA_FOLDER_PATH";
80 public static final String EXTRA_RESULT
= FileSyncAdapter
.class.getName() + ".EXTRA_RESULT";
83 /** Time stamp for the current synchronization process, used to distinguish fresh data */
84 private long mCurrentSyncTime
;
86 /** Flag made 'true' when a request to cancel the synchronization is received */
87 private boolean mCancellation
;
89 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
90 private boolean mIsManualSync
;
92 /** Counter for failed operations in the synchronization process */
93 private int mFailedResultsCounter
;
95 /** Result of the last failed operation */
96 private RemoteOperationResult mLastFailedResult
;
98 /** Counter of conflicts found between local and remote files */
99 private int mConflictsFound
;
101 /** Counter of failed operations in synchronization of kept-in-sync files */
102 private int mFailsInFavouritesFound
;
104 /** 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 */
105 private Map
<String
, String
> mForgottenLocalFiles
;
107 /** {@link SyncResult} instance to return to the system when the synchronization finish */
108 private SyncResult mSyncResult
;
112 * Creates a {@link FileSyncAdapter}
116 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
117 super(context
, autoInitialize
);
122 * Creates a {@link FileSyncAdapter}
126 public FileSyncAdapter(Context context
, boolean autoInitialize
, boolean allowParallelSyncs
) {
127 super(context
, autoInitialize
, allowParallelSyncs
);
135 public synchronized void onPerformSync(Account account
, Bundle extras
,
136 String authority
, ContentProviderClient providerClient
,
137 SyncResult syncResult
) {
139 mCancellation
= false
;
140 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
141 mFailedResultsCounter
= 0;
142 mLastFailedResult
= null
;
144 mFailsInFavouritesFound
= 0;
145 mForgottenLocalFiles
= new HashMap
<String
, String
>();
146 mSyncResult
= syncResult
;
147 mSyncResult
.fullSyncRequested
= false
;
148 mSyncResult
.delayUntil
= 60*60*24; // avoid too many automatic synchronizations
150 this.setAccount(account
);
151 this.setContentProviderClient(providerClient
);
152 this.setStorageManager(new FileDataStorageManager(account
, providerClient
));
154 this.initClientForCurrentAccount();
155 } catch (IOException e
) {
156 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
157 mSyncResult
.tooManyRetries
= true
;
158 notifyFailedSynchronization();
160 } catch (AccountsException e
) {
161 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
162 mSyncResult
.tooManyRetries
= true
;
163 notifyFailedSynchronization();
167 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
168 sendLocalBroadcast(EVENT_FULL_SYNC_START
, null
, null
); // message to signal the start of the synchronization to the UI
172 mCurrentSyncTime
= System
.currentTimeMillis();
173 if (!mCancellation
) {
174 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
177 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
182 // it's important making this although very unexpected errors occur; that's the reason for the finally
184 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
185 /// don't let the system synchronization manager retries MANUAL synchronizations
186 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
187 mSyncResult
.tooManyRetries
= true
;
189 /// notify the user about the failure of MANUAL synchronization
190 notifyFailedSynchronization();
192 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
193 notifyFailsInFavourites();
195 if (mForgottenLocalFiles
.size() > 0) {
196 notifyForgottenLocalFiles();
198 sendLocalBroadcast(EVENT_FULL_SYNC_END
, null
, mLastFailedResult
); // message to signal the end to the UI
204 * Called by system SyncManager when a synchronization is required to be cancelled.
206 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
207 * before a new folder is fetched. Data of the last folder synchronized will be still
210 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
211 * and {@link #synchronizeFolder(String, long)}.
214 public void onSyncCanceled() {
215 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
216 mCancellation
= true
;
217 super.onSyncCanceled();
222 * Updates the locally stored version value of the ownCloud server
224 private void updateOCVersion() {
225 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
226 RemoteOperationResult result
= update
.execute(getClient());
227 if (!result
.isSuccess()) {
228 mLastFailedResult
= result
;
234 * Synchronizes the list of files contained in a folder identified with its remote path.
236 * Fetches the list and properties of the files contained in the given folder, including their
237 * properties, and updates the local database with them.
239 * Enters in the child folders to synchronize their contents also, following a recursive
240 * depth first strategy.
242 * @param folder Folder to synchronize.
244 private void synchronizeFolder(OCFile folder
) {
246 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
251 long currentSyncTime,
252 boolean updateFolderProperties,
253 boolean syncFullAccount,
254 DataStorageManager dataStorageManager,
260 // folder synchronization
261 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
268 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
271 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
272 sendLocalBroadcast(EVENT_FOLDER_CONTENTS_SYNCED
, folder
.getRemotePath(), result
);
274 // check the result of synchronizing the folder
275 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
277 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
278 mConflictsFound
+= synchFolderOp
.getConflictsFound();
279 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
281 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
282 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
284 if (result
.isSuccess()) {
285 // synchronize children folders
286 List
<OCFile
> children
= synchFolderOp
.getChildren();
287 fetchChildren(folder
, children
, synchFolderOp
.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
291 // in failures, the statistics for the global result are updated
292 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
293 ( result
.isIdPRedirection() &&
294 getClient().getCredentials() == null
)) {
295 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))) {
296 mSyncResult
.stats
.numAuthExceptions
++;
298 } else if (result
.getException() instanceof DavException
) {
299 mSyncResult
.stats
.numParseExceptions
++;
301 } else if (result
.getException() instanceof IOException
) {
302 mSyncResult
.stats
.numIoExceptions
++;
304 mFailedResultsCounter
++;
305 mLastFailedResult
= result
;
311 * Checks if a failed result should terminate the synchronization process immediately, according to
314 * @param failedResult Remote operation result to check.
315 * @return 'True' if the result should immediately finish the synchronization
317 private boolean isFinisher(RemoteOperationResult failedResult
) {
318 if (failedResult
!= null
) {
319 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
320 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
321 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
322 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
323 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
329 * Triggers the synchronization of any folder contained in the list of received files.
331 * @param files Files to recursively synchronize.
333 private void fetchChildren(OCFile parent
, List
<OCFile
> files
, boolean parentEtagChanged
) {
335 OCFile newFile
= null
;
336 //String etag = null;
337 //boolean syncDown = false;
338 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
339 newFile
= files
.get(i
);
340 if (newFile
.isFolder()) {
342 etag = newFile.getEtag();
343 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
345 synchronizeFolder(newFile
);
346 sendLocalBroadcast(EVENT_FOLDER_SIZE_SYNCED
, parent
.getRemotePath(), null
);
351 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
356 * Sends a message to any application component interested in the progress of the synchronization.
358 * @param event Event in the process of synchronization to be notified.
359 * @param dirRemotePath Remote path of the folder target of the event occurred.
360 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
362 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
363 Intent intent
= new Intent(event
);
364 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, getAccount().name
);
365 if (dirRemotePath
!= null
) {
366 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
368 if (result
!= null
) {
369 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
371 //getContext().sendStickyBroadcast(i);
372 LocalBroadcastManager
.getInstance(getContext()).sendBroadcast(intent
);
378 * Notifies the user about a failed synchronization through the status notification bar
380 private void notifyFailedSynchronization() {
381 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
382 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
383 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&&
384 ( mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
385 ( mLastFailedResult
.isIdPRedirection() &&
386 getClient().getCredentials() == null
)
387 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))
390 // TODO put something smart in the contentIntent below for all the possible errors
391 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
392 if (needsToUpdateCredentials
) {
393 // let the user update credentials with one click
394 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
395 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
396 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
397 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
398 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
399 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
400 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
401 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
402 notification
.setLatestEventInfo(getContext().getApplicationContext(),
403 getContext().getString(R
.string
.sync_fail_ticker
),
404 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
405 notification
.contentIntent
);
407 notification
.setLatestEventInfo(getContext().getApplicationContext(),
408 getContext().getString(R
.string
.sync_fail_ticker
),
409 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
410 notification
.contentIntent
);
412 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
417 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
419 * By now, we won't consider a failed synchronization.
421 private void notifyFailsInFavourites() {
422 if (mFailedResultsCounter
> 0) {
423 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
424 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
425 // TODO put something smart in the contentIntent below
426 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
427 notification
.setLatestEventInfo(getContext().getApplicationContext(),
428 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
429 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
430 notification
.contentIntent
);
431 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
434 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
435 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
436 // TODO put something smart in the contentIntent below
437 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
438 notification
.setLatestEventInfo(getContext().getApplicationContext(),
439 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
440 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
441 notification
.contentIntent
);
442 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
447 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
448 * copying them inside the ownCloud local directory was not possible.
450 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
451 * synchronization problems if a local file is linked to more than one remote file.
453 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
455 private void notifyForgottenLocalFiles() {
456 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
457 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
459 /// includes a pending intent in the notification showing a more detailed explanation
460 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
461 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
462 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
463 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
464 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
465 localPaths
.addAll(mForgottenLocalFiles
.values());
466 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
467 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
468 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
470 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
471 notification
.setLatestEventInfo(getContext().getApplicationContext(),
472 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
473 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
474 notification
.contentIntent
);
475 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);