1 /* ownCloud Android client application
3 * @author Bartek Przybylski
4 * @author David A. Velasco
5 * Copyright (C) 2011 Bartek Przybylski
6 * Copyright (C) 2012-2013 ownCloud Inc.
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 package com
.owncloud
.android
.syncadapter
;
24 import java
.io
.IOException
;
25 import java
.util
.ArrayList
;
26 import java
.util
.HashMap
;
27 import java
.util
.List
;
30 import org
.apache
.jackrabbit
.webdav
.DavException
;
32 import com
.owncloud
.android
.R
;
33 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
37 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
38 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
39 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
40 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
41 import com
.owncloud
.android
.ui
.activity
.ErrorsWhileCopyingHandlerActivity
;
43 import android
.accounts
.Account
;
44 import android
.accounts
.AccountsException
;
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
.app
.NotificationCompat
;
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 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
64 private final static String TAG
= FileSyncAdapter
.class.getSimpleName();
66 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
67 private static final int MAX_FAILED_RESULTS
= 3;
70 public static final String EVENT_FULL_SYNC_START
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_START";
71 public static final String EVENT_FULL_SYNC_END
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_END";
72 public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
73 //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
75 public static final String EXTRA_ACCOUNT_NAME
= FileSyncAdapter
.class.getName() + ".EXTRA_ACCOUNT_NAME";
76 public static final String EXTRA_FOLDER_PATH
= FileSyncAdapter
.class.getName() + ".EXTRA_FOLDER_PATH";
77 public static final String EXTRA_RESULT
= FileSyncAdapter
.class.getName() + ".EXTRA_RESULT";
80 /** Time stamp for the current synchronization process, used to distinguish fresh data */
81 private long mCurrentSyncTime
;
83 /** Flag made 'true' when a request to cancel the synchronization is received */
84 private boolean mCancellation
;
86 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
87 private boolean mIsManualSync
;
89 /** Counter for failed operations in the synchronization process */
90 private int mFailedResultsCounter
;
92 /** Result of the last failed operation */
93 private RemoteOperationResult mLastFailedResult
;
95 /** Counter of conflicts found between local and remote files */
96 private int mConflictsFound
;
98 /** Counter of failed operations in synchronization of kept-in-sync files */
99 private int mFailsInFavouritesFound
;
101 /** 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 */
102 private Map
<String
, String
> mForgottenLocalFiles
;
104 /** {@link SyncResult} instance to return to the system when the synchronization finish */
105 private SyncResult mSyncResult
;
107 /** 'True' means that the server supports the share API */
108 private boolean mIsShareSupported
;
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
));
155 this.initClientForCurrentAccount();
156 } catch (IOException e
) {
157 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
158 mSyncResult
.tooManyRetries
= true
;
159 notifyFailedSynchronization();
161 } catch (AccountsException 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();
168 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
169 sendLocalBroadcast(EVENT_FULL_SYNC_START
, null
, null
); // message to signal the start of the synchronization to the UI
173 mCurrentSyncTime
= System
.currentTimeMillis();
174 if (!mCancellation
) {
175 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
178 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
183 // it's important making this although very unexpected errors occur; that's the reason for the finally
185 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
186 /// don't let the system synchronization manager retries MANUAL synchronizations
187 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
188 mSyncResult
.tooManyRetries
= true
;
190 /// notify the user about the failure of MANUAL synchronization
191 notifyFailedSynchronization();
193 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
194 notifyFailsInFavourites();
196 if (mForgottenLocalFiles
.size() > 0) {
197 notifyForgottenLocalFiles();
199 sendLocalBroadcast(EVENT_FULL_SYNC_END
, null
, mLastFailedResult
); // message to signal the end to the UI
205 * Called by system SyncManager when a synchronization is required to be cancelled.
207 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
208 * before a new folder is fetched. Data of the last folder synchronized will be still
211 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
212 * and {@link #synchronizeFolder(String, long)}.
215 public void onSyncCanceled() {
216 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
217 mCancellation
= true
;
218 super.onSyncCanceled();
223 * Updates the locally stored version value of the ownCloud server
225 private void updateOCVersion() {
226 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
227 RemoteOperationResult result
= update
.execute(getClient());
228 if (!result
.isSuccess()) {
229 mLastFailedResult
= result
;
231 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
237 * Synchronizes the list of files contained in a folder identified with its remote path.
239 * Fetches the list and properties of the files contained in the given folder, including their
240 * properties, and updates the local database with them.
242 * Enters in the child folders to synchronize their contents also, following a recursive
243 * depth first strategy.
245 * @param folder Folder to synchronize.
247 private void synchronizeFolder(OCFile folder
) {
249 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
254 long currentSyncTime,
255 boolean updateFolderProperties,
256 boolean syncFullAccount,
257 DataStorageManager dataStorageManager,
262 // folder synchronization
263 RefreshFolderOperation synchFolderOp
= new RefreshFolderOperation( folder
,
272 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
275 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
276 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
, folder
.getRemotePath(), result
);
278 // check the result of synchronizing the folder
279 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
281 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
282 mConflictsFound
+= synchFolderOp
.getConflictsFound();
283 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
285 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
286 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
288 if (result
.isSuccess()) {
289 // synchronize children folders
290 List
<OCFile
> children
= synchFolderOp
.getChildren();
291 fetchChildren(folder
, children
, synchFolderOp
.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
295 // in failures, the statistics for the global result are updated
296 if ( result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
297 result
.isIdPRedirection()
299 mSyncResult
.stats
.numAuthExceptions
++;
301 } else if (result
.getException() instanceof DavException
) {
302 mSyncResult
.stats
.numParseExceptions
++;
304 } else if (result
.getException() instanceof IOException
) {
305 mSyncResult
.stats
.numIoExceptions
++;
307 mFailedResultsCounter
++;
308 mLastFailedResult
= result
;
314 * Checks if a failed result should terminate the synchronization process immediately, according to
317 * @param failedResult Remote operation result to check.
318 * @return 'True' if the result should immediately finish the synchronization
320 private boolean isFinisher(RemoteOperationResult failedResult
) {
321 if (failedResult
!= null
) {
322 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
323 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
324 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
325 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
326 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
332 * Triggers the synchronization of any folder contained in the list of received files.
334 * @param files Files to recursively synchronize.
336 private void fetchChildren(OCFile parent
, List
<OCFile
> files
, boolean parentEtagChanged
) {
338 OCFile newFile
= null
;
339 //String etag = null;
340 //boolean syncDown = false;
341 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
342 newFile
= files
.get(i
);
343 if (newFile
.isFolder()) {
345 etag = newFile.getEtag();
346 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
348 synchronizeFolder(newFile
);
349 //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null);
354 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
359 * Sends a message to any application component interested in the progress of the synchronization.
361 * @param event Event in the process of synchronization to be notified.
362 * @param dirRemotePath Remote path of the folder target of the event occurred.
363 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
365 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
366 Log_OC
.d(TAG
, "Send broadcast " + event
);
367 Intent intent
= new Intent(event
);
368 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, getAccount().name
);
369 if (dirRemotePath
!= null
) {
370 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
372 if (result
!= null
) {
373 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
375 getContext().sendStickyBroadcast(intent
);
376 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
382 * Notifies the user about a failed synchronization through the status notification bar
384 private void notifyFailedSynchronization() {
385 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
386 boolean needsToUpdateCredentials
= (
387 mLastFailedResult
!= null
&& (
388 mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
389 mLastFailedResult
.isIdPRedirection()
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_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
);
397 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
398 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
399 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
401 .setTicker(i18n(R
.string
.sync_fail_ticker_unauthorized
))
402 .setContentTitle(i18n(R
.string
.sync_fail_ticker_unauthorized
))
403 .setContentIntent(PendingIntent
.getActivity(
404 getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
406 .setContentText(i18n(R
.string
.sync_fail_content_unauthorized
, getAccount().name
));
409 .setTicker(i18n(R
.string
.sync_fail_ticker
))
410 .setContentTitle(i18n(R
.string
.sync_fail_ticker
))
411 .setContentText(i18n(R
.string
.sync_fail_content
, getAccount().name
));
414 showNotification(R
.string
.sync_fail_ticker
, notificationBuilder
);
419 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
421 * By now, we won't consider a failed synchronization.
423 private void notifyFailsInFavourites() {
424 if (mFailedResultsCounter
> 0) {
425 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
426 notificationBuilder
.setTicker(i18n(R
.string
.sync_fail_in_favourites_ticker
));
428 // TODO put something smart in the contentIntent below
430 .setContentIntent(PendingIntent
.getActivity(
431 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
433 .setContentTitle(i18n(R
.string
.sync_fail_in_favourites_ticker
))
434 .setContentText(i18n(R
.string
.sync_fail_in_favourites_content
, mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
));
436 showNotification(R
.string
.sync_fail_in_favourites_ticker
, notificationBuilder
);
438 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
439 notificationBuilder
.setTicker(i18n(R
.string
.sync_conflicts_in_favourites_ticker
));
441 // TODO put something smart in the contentIntent below
443 .setContentIntent(PendingIntent
.getActivity(
444 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
446 .setContentTitle(i18n(R
.string
.sync_conflicts_in_favourites_ticker
))
447 .setContentText(i18n(R
.string
.sync_conflicts_in_favourites_ticker
, mConflictsFound
));
449 showNotification(R
.string
.sync_conflicts_in_favourites_ticker
, notificationBuilder
);
454 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
455 * copying them inside the ownCloud local directory was not possible.
457 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
458 * synchronization problems if a local file is linked to more than one remote file.
460 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
462 private void notifyForgottenLocalFiles() {
463 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
464 notificationBuilder
.setTicker(i18n(R
.string
.sync_foreign_files_forgotten_ticker
));
466 /// includes a pending intent in the notification showing a more detailed explanation
467 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
468 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
469 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
470 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
471 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
472 localPaths
.addAll(mForgottenLocalFiles
.values());
473 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
474 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
475 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
478 .setContentIntent(PendingIntent
.getActivity(
479 getContext(), (int) System
.currentTimeMillis(), explanationIntent
, 0
481 .setContentTitle(i18n(R
.string
.sync_foreign_files_forgotten_ticker
))
482 .setContentText(i18n(R
.string
.sync_foreign_files_forgotten_content
, mForgottenLocalFiles
.size(), i18n(R
.string
.app_name
)));
484 showNotification(R
.string
.sync_foreign_files_forgotten_ticker
, notificationBuilder
);
488 * Creates a notification builder with some commonly used settings
492 private NotificationCompat
.Builder
createNotificationBuilder() {
493 NotificationCompat
.Builder notificationBuilder
= new NotificationCompat
.Builder(getContext());
494 notificationBuilder
.setSmallIcon(R
.drawable
.notification_icon
).setAutoCancel(true
);
495 return notificationBuilder
;
499 * Builds and shows the notification
504 private void showNotification(int id
, NotificationCompat
.Builder builder
) {
505 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
))
506 .notify(id
, builder
.build());
509 * Shorthand translation
515 private String
i18n(int key
, Object
... args
) {
516 return getContext().getString(key
, args
);