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
.common
.accounts
.AccountUtils
.Constants
;
34 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
35 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
36 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
37 import com
.owncloud
.android
.lib
.common
.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
.AccountManager
;
45 import android
.accounts
.AccountsException
;
46 import android
.app
.Notification
;
47 import android
.app
.NotificationManager
;
48 import android
.app
.PendingIntent
;
49 import android
.content
.AbstractThreadedSyncAdapter
;
50 import android
.content
.ContentProviderClient
;
51 import android
.content
.ContentResolver
;
52 import android
.content
.Context
;
53 import android
.content
.Intent
;
54 import android
.content
.SyncResult
;
55 import android
.os
.Bundle
;
56 //import android.support.v4.content.LocalBroadcastManager;
59 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
62 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
64 * @author Bartek Przybylski
65 * @author David A. Velasco
67 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
69 private final static String TAG
= FileSyncAdapter
.class.getSimpleName();
71 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
72 private static final int MAX_FAILED_RESULTS
= 3;
75 public static final String EVENT_FULL_SYNC_START
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_START";
76 public static final String EVENT_FULL_SYNC_END
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_END";
77 public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
78 public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
80 public static final String EXTRA_ACCOUNT_NAME
= FileSyncAdapter
.class.getName() + ".EXTRA_ACCOUNT_NAME";
81 public static final String EXTRA_FOLDER_PATH
= FileSyncAdapter
.class.getName() + ".EXTRA_FOLDER_PATH";
82 public static final String EXTRA_RESULT
= FileSyncAdapter
.class.getName() + ".EXTRA_RESULT";
85 /** Time stamp for the current synchronization process, used to distinguish fresh data */
86 private long mCurrentSyncTime
;
88 /** Flag made 'true' when a request to cancel the synchronization is received */
89 private boolean mCancellation
;
91 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
92 private boolean mIsManualSync
;
94 /** Counter for failed operations in the synchronization process */
95 private int mFailedResultsCounter
;
97 /** Result of the last failed operation */
98 private RemoteOperationResult mLastFailedResult
;
100 /** Counter of conflicts found between local and remote files */
101 private int mConflictsFound
;
103 /** Counter of failed operations in synchronization of kept-in-sync files */
104 private int mFailsInFavouritesFound
;
106 /** 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 */
107 private Map
<String
, String
> mForgottenLocalFiles
;
109 /** {@link SyncResult} instance to return to the system when the synchronization finish */
110 private SyncResult mSyncResult
;
112 /** 'True' means that the server supports the share API */
113 private boolean mIsShareSupported
;
117 * Creates a {@link FileSyncAdapter}
121 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
122 super(context
, autoInitialize
);
127 * Creates a {@link FileSyncAdapter}
131 public FileSyncAdapter(Context context
, boolean autoInitialize
, boolean allowParallelSyncs
) {
132 super(context
, autoInitialize
, allowParallelSyncs
);
140 public synchronized void onPerformSync(Account account
, Bundle extras
,
141 String authority
, ContentProviderClient providerClient
,
142 SyncResult syncResult
) {
144 mCancellation
= false
;
145 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
146 mFailedResultsCounter
= 0;
147 mLastFailedResult
= null
;
149 mFailsInFavouritesFound
= 0;
150 mForgottenLocalFiles
= new HashMap
<String
, String
>();
151 mSyncResult
= syncResult
;
152 mSyncResult
.fullSyncRequested
= false
;
153 mSyncResult
.delayUntil
= 60*60*24; // avoid too many automatic synchronizations
155 this.setAccount(account
);
156 this.setContentProviderClient(providerClient
);
157 this.setStorageManager(new FileDataStorageManager(account
, providerClient
));
160 this.initClientForCurrentAccount();
161 } catch (IOException e
) {
162 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
163 mSyncResult
.tooManyRetries
= true
;
164 notifyFailedSynchronization();
166 } catch (AccountsException e
) {
167 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
168 mSyncResult
.tooManyRetries
= true
;
169 notifyFailedSynchronization();
173 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
174 sendLocalBroadcast(EVENT_FULL_SYNC_START
, null
, null
); // message to signal the start of the synchronization to the UI
178 mCurrentSyncTime
= System
.currentTimeMillis();
179 if (!mCancellation
) {
180 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
183 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
188 // it's important making this although very unexpected errors occur; that's the reason for the finally
190 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
191 /// don't let the system synchronization manager retries MANUAL synchronizations
192 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
193 mSyncResult
.tooManyRetries
= true
;
195 /// notify the user about the failure of MANUAL synchronization
196 notifyFailedSynchronization();
198 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
199 notifyFailsInFavourites();
201 if (mForgottenLocalFiles
.size() > 0) {
202 notifyForgottenLocalFiles();
204 sendLocalBroadcast(EVENT_FULL_SYNC_END
, null
, mLastFailedResult
); // message to signal the end to the UI
210 * Called by system SyncManager when a synchronization is required to be cancelled.
212 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
213 * before a new folder is fetched. Data of the last folder synchronized will be still
216 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
217 * and {@link #synchronizeFolder(String, long)}.
220 public void onSyncCanceled() {
221 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
222 mCancellation
= true
;
223 super.onSyncCanceled();
228 * Updates the locally stored version value of the ownCloud server
230 private void updateOCVersion() {
231 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
232 RemoteOperationResult result
= update
.execute(getClient());
233 if (!result
.isSuccess()) {
234 mLastFailedResult
= result
;
236 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
242 * Synchronizes the list of files contained in a folder identified with its remote path.
244 * Fetches the list and properties of the files contained in the given folder, including their
245 * properties, and updates the local database with them.
247 * Enters in the child folders to synchronize their contents also, following a recursive
248 * depth first strategy.
250 * @param folder Folder to synchronize.
252 private void synchronizeFolder(OCFile folder
) {
254 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
259 long currentSyncTime,
260 boolean updateFolderProperties,
261 boolean syncFullAccount,
262 DataStorageManager dataStorageManager,
267 // folder synchronization
268 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
276 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
279 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
280 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
, folder
.getRemotePath(), result
);
282 // check the result of synchronizing the folder
283 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
285 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
286 mConflictsFound
+= synchFolderOp
.getConflictsFound();
287 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
289 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
290 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
292 if (result
.isSuccess()) {
293 // synchronize children folders
294 List
<OCFile
> children
= synchFolderOp
.getChildren();
295 fetchChildren(folder
, children
, synchFolderOp
.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
299 // in failures, the statistics for the global result are updated
300 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
301 ( result
.isIdPRedirection() &&
302 getClient().getCredentials() == null
)) {
303 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))) {
304 mSyncResult
.stats
.numAuthExceptions
++;
306 } else if (result
.getException() instanceof DavException
) {
307 mSyncResult
.stats
.numParseExceptions
++;
309 } else if (result
.getException() instanceof IOException
) {
310 mSyncResult
.stats
.numIoExceptions
++;
312 mFailedResultsCounter
++;
313 mLastFailedResult
= result
;
319 * Checks if a failed result should terminate the synchronization process immediately, according to
322 * @param failedResult Remote operation result to check.
323 * @return 'True' if the result should immediately finish the synchronization
325 private boolean isFinisher(RemoteOperationResult failedResult
) {
326 if (failedResult
!= null
) {
327 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
328 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
329 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
330 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
331 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
337 * Triggers the synchronization of any folder contained in the list of received files.
339 * @param files Files to recursively synchronize.
341 private void fetchChildren(OCFile parent
, List
<OCFile
> files
, boolean parentEtagChanged
) {
343 OCFile newFile
= null
;
344 //String etag = null;
345 //boolean syncDown = false;
346 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
347 newFile
= files
.get(i
);
348 if (newFile
.isFolder()) {
350 etag = newFile.getEtag();
351 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
353 synchronizeFolder(newFile
);
354 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED
, parent
.getRemotePath(), null
);
359 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
364 * Sends a message to any application component interested in the progress of the synchronization.
366 * @param event Event in the process of synchronization to be notified.
367 * @param dirRemotePath Remote path of the folder target of the event occurred.
368 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
370 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
371 Log_OC
.d(TAG
, "Send broadcast " + event
);
372 Intent intent
= new Intent(event
);
373 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, getAccount().name
);
374 if (dirRemotePath
!= null
) {
375 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
377 if (result
!= null
) {
378 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
380 getContext().sendStickyBroadcast(intent
);
381 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
387 * Notifies the user about a failed synchronization through the status notification bar
389 private void notifyFailedSynchronization() {
390 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
391 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
392 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&&
393 ( mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
394 ( mLastFailedResult
.isIdPRedirection() &&
395 getClient().getCredentials() == null
)
396 //MainApp.getAuthTokenTypeSamlSessionCookie().equals(getClient().getAuthTokenType()))
399 // TODO put something smart in the contentIntent below for all the possible errors
400 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
401 if (needsToUpdateCredentials
) {
402 // let the user update credentials with one click
403 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
404 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
405 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
406 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
407 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
408 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
409 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
410 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
411 notification
.setLatestEventInfo(getContext().getApplicationContext(),
412 getContext().getString(R
.string
.sync_fail_ticker
),
413 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
414 notification
.contentIntent
);
416 notification
.setLatestEventInfo(getContext().getApplicationContext(),
417 getContext().getString(R
.string
.sync_fail_ticker
),
418 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
419 notification
.contentIntent
);
421 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
426 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
428 * By now, we won't consider a failed synchronization.
430 private void notifyFailsInFavourites() {
431 if (mFailedResultsCounter
> 0) {
432 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
433 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
434 // TODO put something smart in the contentIntent below
435 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
436 notification
.setLatestEventInfo(getContext().getApplicationContext(),
437 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
438 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
439 notification
.contentIntent
);
440 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
443 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
444 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
445 // TODO put something smart in the contentIntent below
446 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
447 notification
.setLatestEventInfo(getContext().getApplicationContext(),
448 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
449 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
450 notification
.contentIntent
);
451 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
456 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
457 * copying them inside the ownCloud local directory was not possible.
459 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
460 * synchronization problems if a local file is linked to more than one remote file.
462 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
464 private void notifyForgottenLocalFiles() {
465 Notification notification
= new Notification(DisplayUtils
.getSeasonalIconId(), getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
466 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
468 /// includes a pending intent in the notification showing a more detailed explanation
469 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
470 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
471 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
472 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
473 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
474 localPaths
.addAll(mForgottenLocalFiles
.values());
475 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
476 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
477 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
479 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
480 notification
.setLatestEventInfo(getContext().getApplicationContext(),
481 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
482 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
483 notification
.contentIntent
);
484 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);