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
.Log_OC
;
30 import com
.owncloud
.android
.R
;
31 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
32 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
33 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
34 import com
.owncloud
.android
.datamodel
.OCFile
;
35 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
36 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
37 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
38 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
39 import com
.owncloud
.android
.ui
.activity
.ErrorsWhileCopyingHandlerActivity
;
41 import android
.accounts
.Account
;
42 import android
.accounts
.AccountsException
;
43 import android
.app
.Notification
;
44 import android
.app
.NotificationManager
;
45 import android
.app
.PendingIntent
;
46 import android
.content
.AbstractThreadedSyncAdapter
;
47 import android
.content
.ContentProviderClient
;
48 import android
.content
.ContentResolver
;
49 import android
.content
.Context
;
50 import android
.content
.Intent
;
51 import android
.content
.SyncResult
;
52 import android
.os
.Bundle
;
55 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
58 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
60 * @author Bartek Przybylski
61 * @author David A. Velasco
63 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
65 private final static String TAG
= FileSyncAdapter
.class.getSimpleName();
67 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
68 private static final int MAX_FAILED_RESULTS
= 3;
71 /** Time stamp for the current synchronization process, used to distinguish fresh data */
72 private long mCurrentSyncTime
;
74 /** Flag made 'true' when a request to cancel the synchronization is received */
75 private boolean mCancellation
;
77 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
78 private boolean mIsManualSync
;
80 /** Counter for failed operations in the synchronization process */
81 private int mFailedResultsCounter
;
83 /** Result of the last failed operation */
84 private RemoteOperationResult mLastFailedResult
;
86 /** Counter of conflicts found between local and remote files */
87 private int mConflictsFound
;
89 /** Counter of failed operations in synchronization of kept-in-sync files */
90 private int mFailsInFavouritesFound
;
92 /** 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 */
93 private Map
<String
, String
> mForgottenLocalFiles
;
95 /** {@link SyncResult} instance to return to the system when the synchronization finish */
96 private SyncResult mSyncResult
;
100 * Creates an {@link FileSyncAdapter}
104 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
105 super(context
, autoInitialize
);
113 public synchronized void onPerformSync(Account account
, Bundle extras
,
114 String authority
, ContentProviderClient provider
,
115 SyncResult syncResult
) {
117 mCancellation
= false
;
118 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
119 mFailedResultsCounter
= 0;
120 mLastFailedResult
= null
;
122 mFailsInFavouritesFound
= 0;
123 mForgottenLocalFiles
= new HashMap
<String
, String
>();
124 mSyncResult
= syncResult
;
125 mSyncResult
.fullSyncRequested
= false
;
126 mSyncResult
.delayUntil
= 60*60*24; // avoid too many automatic synchronizations
128 this.setAccount(account
);
129 this.setContentProvider(provider
);
130 this.setStorageManager(new FileDataStorageManager(account
, provider
));
132 this.initClientForCurrentAccount();
133 } catch (IOException e
) {
134 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
135 mSyncResult
.tooManyRetries
= true
;
136 notifyFailedSynchronization();
138 } catch (AccountsException e
) {
139 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
140 mSyncResult
.tooManyRetries
= true
;
141 notifyFailedSynchronization();
145 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
146 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
150 mCurrentSyncTime
= System
.currentTimeMillis();
151 if (!mCancellation
) {
152 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
), true
);
155 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
160 // it's important making this although very unexpected errors occur; that's the reason for the finally
162 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
163 /// don't let the system synchronization manager retries MANUAL synchronizations
164 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
165 mSyncResult
.tooManyRetries
= true
;
167 /// notify the user about the failure of MANUAL synchronization
168 notifyFailedSynchronization();
170 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
171 notifyFailsInFavourites();
173 if (mForgottenLocalFiles
.size() > 0) {
174 notifyForgottenLocalFiles();
176 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
182 * Called by system SyncManager when a synchronization is required to be cancelled.
184 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
185 * before a new folder is fetched. Data of the last folder synchronized will be still
188 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
189 * and {@link #synchronizeFolder(String, long)}.
192 public void onSyncCanceled() {
193 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
194 mCancellation
= true
;
195 super.onSyncCanceled();
200 * Updates the locally stored version value of the ownCloud server
202 private void updateOCVersion() {
203 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
204 RemoteOperationResult result
= update
.execute(getClient());
205 if (!result
.isSuccess()) {
206 mLastFailedResult
= result
;
212 * Synchronizes the list of files contained in a folder identified with its remote path.
214 * Fetches the list and properties of the files contained in the given folder, including their
215 * properties, and updates the local database with them.
217 * Enters in the child folders to synchronize their contents also, following a recursive
218 * depth first strategy.
220 * @param folder Folder to synchronize.
221 * @param updateFolderProperties When 'true', updates also the properties of the of the target folder.
223 private void synchronizeFolder(OCFile folder
, boolean updateFolderProperties
) {
225 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
230 long currentSyncTime,
231 boolean updateFolderProperties,
232 boolean syncFullAccount,
233 DataStorageManager dataStorageManager,
239 // folder synchronization
240 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
242 updateFolderProperties
,
248 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
251 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
252 sendStickyBroadcast(true
, folder
.getRemotePath(), null
);
254 // check the result of synchronizing the folder
255 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
257 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
258 mConflictsFound
+= synchFolderOp
.getConflictsFound();
259 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
261 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
262 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
264 // synchronize children folders
265 List
<OCFile
> children
= synchFolderOp
.getChildren();
266 fetchChildren(children
); // beware of the 'hidden' recursion here!
268 // update folder size again after recursive synchronization
269 getStorageManager().calculateFolderSize(folder
.getFileId());
270 sendStickyBroadcast(true
, folder
.getRemotePath(), null
); // notify again
273 // in failures, the statistics for the global result are updated
274 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
275 ( result
.isIdPRedirection() &&
276 AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(getClient().getAuthTokenType()))) {
277 mSyncResult
.stats
.numAuthExceptions
++;
279 } else if (result
.getException() instanceof DavException
) {
280 mSyncResult
.stats
.numParseExceptions
++;
282 } else if (result
.getException() instanceof IOException
) {
283 mSyncResult
.stats
.numIoExceptions
++;
285 mFailedResultsCounter
++;
286 mLastFailedResult
= result
;
292 * Checks if a failed result should terminate the synchronization process immediately, according to
295 * @param failedResult Remote operation result to check.
296 * @return 'True' if the result should immediately finish the synchronization
298 private boolean isFinisher(RemoteOperationResult failedResult
) {
299 if (failedResult
!= null
) {
300 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
301 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
302 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
303 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
304 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
310 * Triggers the synchronization of any folder contained in the list of received files.
312 * @param files Files to recursively synchronize.
314 private void fetchChildren(List
<OCFile
> files
) {
316 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
317 OCFile newFile
= files
.get(i
);
318 if (newFile
.isFolder()) {
319 synchronizeFolder(newFile
, false
);
323 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
328 * Sends a message to any application component interested in the progress of the synchronization.
330 * @param inProgress 'True' when the synchronization progress is not finished.
331 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
333 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
334 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
335 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
336 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
337 if (dirRemotePath
!= null
) {
338 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
340 if (result
!= null
) {
341 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
343 getContext().sendStickyBroadcast(i
);
349 * Notifies the user about a failed synchronization through the status notification bar
351 private void notifyFailedSynchronization() {
352 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
353 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
354 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&&
355 ( mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
356 // (mLastFailedResult.isTemporalRedirection() && mLastFailedResult.isIdPRedirection() &&
357 ( mLastFailedResult
.isIdPRedirection() &&
358 AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(getClient().getAuthTokenType()))
361 // TODO put something smart in the contentIntent below for all the possible errors
362 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
363 if (needsToUpdateCredentials
) {
364 // let the user update credentials with one click
365 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
366 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
367 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
368 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
369 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
370 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
371 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
372 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
373 notification
.setLatestEventInfo(getContext().getApplicationContext(),
374 getContext().getString(R
.string
.sync_fail_ticker
),
375 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
376 notification
.contentIntent
);
378 notification
.setLatestEventInfo(getContext().getApplicationContext(),
379 getContext().getString(R
.string
.sync_fail_ticker
),
380 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
381 notification
.contentIntent
);
383 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
388 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
390 * By now, we won't consider a failed synchronization.
392 private void notifyFailsInFavourites() {
393 if (mFailedResultsCounter
> 0) {
394 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
395 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
396 // TODO put something smart in the contentIntent below
397 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
398 notification
.setLatestEventInfo(getContext().getApplicationContext(),
399 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
400 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
401 notification
.contentIntent
);
402 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
405 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
406 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
407 // TODO put something smart in the contentIntent below
408 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
409 notification
.setLatestEventInfo(getContext().getApplicationContext(),
410 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
411 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
412 notification
.contentIntent
);
413 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
418 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
419 * copying them inside the ownCloud local directory was not possible.
421 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
422 * synchronization problems if a local file is linked to more than one remote file.
424 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
426 private void notifyForgottenLocalFiles() {
427 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
428 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
430 /// includes a pending intent in the notification showing a more detailed explanation
431 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
432 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
433 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
434 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
435 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
436 localPaths
.addAll(mForgottenLocalFiles
.values());
437 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
438 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
439 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
441 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
442 notification
.setLatestEventInfo(getContext().getApplicationContext(),
443 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
444 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
445 notification
.contentIntent
);
446 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);