2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.syncadapter
;
25 import java
.io
.IOException
;
26 import java
.util
.ArrayList
;
27 import java
.util
.HashMap
;
28 import java
.util
.List
;
31 import org
.apache
.jackrabbit
.webdav
.DavException
;
33 import com
.owncloud
.android
.R
;
34 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
35 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
36 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
38 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
39 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
40 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
41 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
42 import com
.owncloud
.android
.ui
.activity
.ErrorsWhileCopyingHandlerActivity
;
44 import android
.accounts
.Account
;
45 import android
.accounts
.AccountsException
;
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
;
55 import android
.support
.v4
.app
.NotificationCompat
;
58 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
61 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
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 public static final String EVENT_FULL_SYNC_START
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_START";
72 public static final String EVENT_FULL_SYNC_END
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_END";
73 public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
= FileSyncAdapter
.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
74 //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
76 public static final String EXTRA_ACCOUNT_NAME
= FileSyncAdapter
.class.getName() + ".EXTRA_ACCOUNT_NAME";
77 public static final String EXTRA_FOLDER_PATH
= FileSyncAdapter
.class.getName() + ".EXTRA_FOLDER_PATH";
78 public static final String EXTRA_RESULT
= FileSyncAdapter
.class.getName() + ".EXTRA_RESULT";
81 /** Time stamp for the current synchronization process, used to distinguish fresh data */
82 private long mCurrentSyncTime
;
84 /** Flag made 'true' when a request to cancel the synchronization is received */
85 private boolean mCancellation
;
87 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
88 private boolean mIsManualSync
;
90 /** Counter for failed operations in the synchronization process */
91 private int mFailedResultsCounter
;
93 /** Result of the last failed operation */
94 private RemoteOperationResult mLastFailedResult
;
96 /** Counter of conflicts found between local and remote files */
97 private int mConflictsFound
;
99 /** Counter of failed operations in synchronization of kept-in-sync files */
100 private int mFailsInFavouritesFound
;
102 /** 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 */
103 private Map
<String
, String
> mForgottenLocalFiles
;
105 /** {@link SyncResult} instance to return to the system when the synchronization finish */
106 private SyncResult mSyncResult
;
108 /** 'True' means that the server supports the share API */
109 private boolean mIsShareSupported
;
113 * Creates a {@link FileSyncAdapter}
117 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
118 super(context
, autoInitialize
);
123 * Creates a {@link FileSyncAdapter}
127 public FileSyncAdapter(Context context
, boolean autoInitialize
, boolean allowParallelSyncs
) {
128 super(context
, autoInitialize
, allowParallelSyncs
);
136 public synchronized void onPerformSync(Account account
, Bundle extras
,
137 String authority
, ContentProviderClient providerClient
,
138 SyncResult syncResult
) {
140 mCancellation
= false
;
141 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
142 mFailedResultsCounter
= 0;
143 mLastFailedResult
= null
;
145 mFailsInFavouritesFound
= 0;
146 mForgottenLocalFiles
= new HashMap
<String
, String
>();
147 mSyncResult
= syncResult
;
148 mSyncResult
.fullSyncRequested
= false
;
149 mSyncResult
.delayUntil
= 60*60*24; // avoid too many automatic synchronizations
151 this.setAccount(account
);
152 this.setContentProviderClient(providerClient
);
153 this.setStorageManager(new FileDataStorageManager(account
, providerClient
));
156 this.initClientForCurrentAccount();
157 } catch (IOException e
) {
158 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
159 mSyncResult
.tooManyRetries
= true
;
160 notifyFailedSynchronization();
162 } catch (AccountsException e
) {
163 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
164 mSyncResult
.tooManyRetries
= true
;
165 notifyFailedSynchronization();
169 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
170 sendLocalBroadcast(EVENT_FULL_SYNC_START
, null
, null
); // message to signal the start of the synchronization to the UI
174 mCurrentSyncTime
= System
.currentTimeMillis();
175 if (!mCancellation
) {
176 synchronizeFolder(getStorageManager().getFileByPath(OCFile
.ROOT_PATH
));
179 Log_OC
.d(TAG
, "Leaving synchronization before synchronizing the root folder because cancelation request");
184 // it's important making this although very unexpected errors occur; that's the reason for the finally
186 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
187 /// don't let the system synchronization manager retries MANUAL synchronizations
188 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
189 mSyncResult
.tooManyRetries
= true
;
191 /// notify the user about the failure of MANUAL synchronization
192 notifyFailedSynchronization();
194 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
195 notifyFailsInFavourites();
197 if (mForgottenLocalFiles
.size() > 0) {
198 notifyForgottenLocalFiles();
200 sendLocalBroadcast(EVENT_FULL_SYNC_END
, null
, mLastFailedResult
); // message to signal the end to the UI
206 * Called by system SyncManager when a synchronization is required to be cancelled.
208 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
209 * before a new folder is fetched. Data of the last folder synchronized will be still
212 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
213 * and {@link #synchronizeFolder(String, long)}.
216 public void onSyncCanceled() {
217 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
218 mCancellation
= true
;
219 super.onSyncCanceled();
224 * Updates the locally stored version value of the ownCloud server
226 private void updateOCVersion() {
227 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
228 RemoteOperationResult result
= update
.execute(getClient());
229 if (!result
.isSuccess()) {
230 mLastFailedResult
= result
;
232 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
238 * Synchronizes the list of files contained in a folder identified with its remote path.
240 * Fetches the list and properties of the files contained in the given folder, including their
241 * properties, and updates the local database with them.
243 * Enters in the child folders to synchronize their contents also, following a recursive
244 * depth first strategy.
246 * @param folder Folder to synchronize.
248 private void synchronizeFolder(OCFile folder
) {
250 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
255 long currentSyncTime,
256 boolean updateFolderProperties,
257 boolean syncFullAccount,
258 DataStorageManager dataStorageManager,
263 // folder synchronization
264 RefreshFolderOperation synchFolderOp
= new RefreshFolderOperation( folder
,
273 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
276 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
277 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
, folder
.getRemotePath(), result
);
279 // check the result of synchronizing the folder
280 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
282 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
283 mConflictsFound
+= synchFolderOp
.getConflictsFound();
284 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
286 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
287 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
289 if (result
.isSuccess()) {
290 // synchronize children folders
291 List
<OCFile
> children
= synchFolderOp
.getChildren();
292 fetchChildren(folder
, children
, synchFolderOp
.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
296 // in failures, the statistics for the global result are updated
297 if ( result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
298 result
.isIdPRedirection()
300 mSyncResult
.stats
.numAuthExceptions
++;
302 } else if (result
.getException() instanceof DavException
) {
303 mSyncResult
.stats
.numParseExceptions
++;
305 } else if (result
.getException() instanceof IOException
) {
306 mSyncResult
.stats
.numIoExceptions
++;
308 mFailedResultsCounter
++;
309 mLastFailedResult
= result
;
315 * Checks if a failed result should terminate the synchronization process immediately, according to
318 * @param failedResult Remote operation result to check.
319 * @return 'True' if the result should immediately finish the synchronization
321 private boolean isFinisher(RemoteOperationResult failedResult
) {
322 if (failedResult
!= null
) {
323 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
324 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
325 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
326 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
327 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
333 * Triggers the synchronization of any folder contained in the list of received files.
335 * @param files Files to recursively synchronize.
337 private void fetchChildren(OCFile parent
, List
<OCFile
> files
, boolean parentEtagChanged
) {
339 OCFile newFile
= null
;
340 //String etag = null;
341 //boolean syncDown = false;
342 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
343 newFile
= files
.get(i
);
344 if (newFile
.isFolder()) {
346 etag = newFile.getEtag();
347 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
349 synchronizeFolder(newFile
);
350 //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null);
355 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " due to cancelation request");
360 * Sends a message to any application component interested in the progress of the synchronization.
362 * @param event Event in the process of synchronization to be notified.
363 * @param dirRemotePath Remote path of the folder target of the event occurred.
364 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
366 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
367 Log_OC
.d(TAG
, "Send broadcast " + event
);
368 Intent intent
= new Intent(event
);
369 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, getAccount().name
);
370 if (dirRemotePath
!= null
) {
371 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
373 if (result
!= null
) {
374 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
376 getContext().sendStickyBroadcast(intent
);
377 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
383 * Notifies the user about a failed synchronization through the status notification bar
385 private void notifyFailedSynchronization() {
386 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
387 boolean needsToUpdateCredentials
= (
388 mLastFailedResult
!= null
&& (
389 mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
390 mLastFailedResult
.isIdPRedirection()
393 if (needsToUpdateCredentials
) {
394 // let the user update credentials with one click
395 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
396 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
397 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_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
);
402 .setTicker(i18n(R
.string
.sync_fail_ticker_unauthorized
))
403 .setContentTitle(i18n(R
.string
.sync_fail_ticker_unauthorized
))
404 .setContentIntent(PendingIntent
.getActivity(
405 getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
407 .setContentText(i18n(R
.string
.sync_fail_content_unauthorized
, getAccount().name
));
410 .setTicker(i18n(R
.string
.sync_fail_ticker
))
411 .setContentTitle(i18n(R
.string
.sync_fail_ticker
))
412 .setContentText(i18n(R
.string
.sync_fail_content
, getAccount().name
));
415 showNotification(R
.string
.sync_fail_ticker
, notificationBuilder
);
420 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
422 * By now, we won't consider a failed synchronization.
424 private void notifyFailsInFavourites() {
425 if (mFailedResultsCounter
> 0) {
426 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
427 notificationBuilder
.setTicker(i18n(R
.string
.sync_fail_in_favourites_ticker
));
429 // TODO put something smart in the contentIntent below
431 .setContentIntent(PendingIntent
.getActivity(
432 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
434 .setContentTitle(i18n(R
.string
.sync_fail_in_favourites_ticker
))
435 .setContentText(i18n(R
.string
.sync_fail_in_favourites_content
, mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
));
437 showNotification(R
.string
.sync_fail_in_favourites_ticker
, notificationBuilder
);
439 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
440 notificationBuilder
.setTicker(i18n(R
.string
.sync_conflicts_in_favourites_ticker
));
442 // TODO put something smart in the contentIntent below
444 .setContentIntent(PendingIntent
.getActivity(
445 getContext(), (int) System
.currentTimeMillis(), new Intent(), 0
447 .setContentTitle(i18n(R
.string
.sync_conflicts_in_favourites_ticker
))
448 .setContentText(i18n(R
.string
.sync_conflicts_in_favourites_ticker
, mConflictsFound
));
450 showNotification(R
.string
.sync_conflicts_in_favourites_ticker
, notificationBuilder
);
455 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
456 * copying them inside the ownCloud local directory was not possible.
458 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
459 * synchronization problems if a local file is linked to more than one remote file.
461 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
463 private void notifyForgottenLocalFiles() {
464 NotificationCompat
.Builder notificationBuilder
= createNotificationBuilder();
465 notificationBuilder
.setTicker(i18n(R
.string
.sync_foreign_files_forgotten_ticker
));
467 /// includes a pending intent in the notification showing a more detailed explanation
468 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
469 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
470 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
471 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
472 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
473 localPaths
.addAll(mForgottenLocalFiles
.values());
474 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
475 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
476 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
479 .setContentIntent(PendingIntent
.getActivity(
480 getContext(), (int) System
.currentTimeMillis(), explanationIntent
, 0
482 .setContentTitle(i18n(R
.string
.sync_foreign_files_forgotten_ticker
))
483 .setContentText(i18n(R
.string
.sync_foreign_files_forgotten_content
, mForgottenLocalFiles
.size(), i18n(R
.string
.app_name
)));
485 showNotification(R
.string
.sync_foreign_files_forgotten_ticker
, notificationBuilder
);
489 * Creates a notification builder with some commonly used settings
493 private NotificationCompat
.Builder
createNotificationBuilder() {
494 NotificationCompat
.Builder notificationBuilder
= new NotificationCompat
.Builder(getContext());
495 notificationBuilder
.setSmallIcon(R
.drawable
.notification_icon
).setAutoCancel(true
);
496 return notificationBuilder
;
500 * Builds and shows the notification
505 private void showNotification(int id
, NotificationCompat
.Builder builder
) {
506 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
))
507 .notify(id
, builder
.build());
510 * Shorthand translation
516 private String
i18n(int key
, Object
... args
) {
517 return getContext().getString(key
, args
);