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
.AuthenticatorActivity
;
32 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
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
;
40 import android
.accounts
.Account
;
41 import android
.accounts
.AccountsException
;
42 import android
.app
.Notification
;
43 import android
.app
.NotificationManager
;
44 import android
.app
.PendingIntent
;
45 import android
.content
.ContentProviderClient
;
46 import android
.content
.ContentResolver
;
47 import android
.content
.Context
;
48 import android
.content
.Intent
;
49 import android
.content
.SyncResult
;
50 import android
.os
.Bundle
;
53 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
54 * platform ContactOperations provider.
56 * @author Bartek Przybylski
57 * @author David A. Velasco
59 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
61 private final static String TAG
= "FileSyncAdapter";
64 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
66 private static final int MAX_FAILED_RESULTS
= 3;
68 private long mCurrentSyncTime
;
69 private boolean mCancellation
;
70 private boolean mIsManualSync
;
71 private int mFailedResultsCounter
;
72 private RemoteOperationResult mLastFailedResult
;
73 private SyncResult mSyncResult
;
74 private int mConflictsFound
;
75 private int mFailsInFavouritesFound
;
76 private Map
<String
, String
> mForgottenLocalFiles
;
79 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
80 super(context
, autoInitialize
);
87 public synchronized void onPerformSync(Account account
, Bundle extras
,
88 String authority
, ContentProviderClient provider
,
89 SyncResult syncResult
) {
91 mCancellation
= false
;
92 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
93 mFailedResultsCounter
= 0;
94 mLastFailedResult
= null
;
96 mFailsInFavouritesFound
= 0;
97 mForgottenLocalFiles
= new HashMap
<String
, String
>();
98 mSyncResult
= syncResult
;
99 mSyncResult
.fullSyncRequested
= false
;
100 mSyncResult
.delayUntil
= 60*60*24; // sync after 24h
102 this.setAccount(account
);
103 this.setContentProvider(provider
);
104 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
106 this.initClientForCurrentAccount();
107 } catch (IOException e
) {
108 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
109 mSyncResult
.tooManyRetries
= true
;
110 notifyFailedSynchronization();
112 } catch (AccountsException e
) {
113 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
114 mSyncResult
.tooManyRetries
= true
;
115 notifyFailedSynchronization();
119 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
120 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
124 mCurrentSyncTime
= System
.currentTimeMillis();
125 if (!mCancellation
) {
126 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
129 Log_OC
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
134 // it's important making this although very unexpected errors occur; that's the reason for the finally
136 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
137 /// don't let the system synchronization manager retries MANUAL synchronizations
138 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
139 mSyncResult
.tooManyRetries
= true
;
141 /// notify the user about the failure of MANUAL synchronization
142 notifyFailedSynchronization();
145 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
146 notifyFailsInFavourites();
148 if (mForgottenLocalFiles
.size() > 0) {
149 notifyForgottenLocalFiles();
152 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
158 * Called by system SyncManager when a synchronization is required to be cancelled.
160 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
161 * fetched will be still saved in the database. See onPerformSync implementation.
164 public void onSyncCanceled() {
165 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
166 mCancellation
= true
;
167 super.onSyncCanceled();
172 * Updates the locally stored version value of the ownCloud server
174 private void updateOCVersion() {
175 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
176 RemoteOperationResult result
= update
.execute(getClient());
177 if (!result
.isSuccess()) {
178 mLastFailedResult
= result
;
184 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
186 * @param remotePath Remote path to the folder to synchronize.
187 * @param parentId Database Id of the folder to synchronize.
189 private void fetchData(String remotePath
, long parentId
) {
191 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
194 // perform folder synchronization
195 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
202 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
205 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
206 sendStickyBroadcast(true
, remotePath
, null
);
208 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
210 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
211 mConflictsFound
+= synchFolderOp
.getConflictsFound();
212 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
214 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
215 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
217 // synchronize children folders
218 List
<OCFile
> children
= synchFolderOp
.getChildren();
219 fetchChildren(children
); // beware of the 'hidden' recursion here!
222 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
223 mSyncResult
.stats
.numAuthExceptions
++;
225 } else if (result
.getException() instanceof DavException
) {
226 mSyncResult
.stats
.numParseExceptions
++;
228 } else if (result
.getException() instanceof IOException
) {
229 mSyncResult
.stats
.numIoExceptions
++;
231 mFailedResultsCounter
++;
232 mLastFailedResult
= result
;
238 * Checks if a failed result should terminate the synchronization process immediately, according to
241 * @param failedResult Remote operation result to check.
242 * @return 'True' if the result should immediately finish the synchronization
244 private boolean isFinisher(RemoteOperationResult failedResult
) {
245 if (failedResult
!= null
) {
246 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
247 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
248 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
249 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
250 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
256 * Synchronize data of folders in the list of received files
258 * @param files Files to recursively fetch
260 private void fetchChildren(List
<OCFile
> files
) {
262 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
263 OCFile newFile
= files
.get(i
);
264 if (newFile
.isDirectory()) {
265 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
268 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
273 * Sends a message to any application component interested in the progress of the synchronization.
275 * @param inProgress 'True' when the synchronization progress is not finished.
276 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
278 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
279 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
280 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
281 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
282 if (dirRemotePath
!= null
) {
283 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
285 if (result
!= null
) {
286 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
288 getContext().sendStickyBroadcast(i
);
294 * Notifies the user about a failed synchronization through the status notification bar
296 private void notifyFailedSynchronization() {
297 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
298 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
299 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&& mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
);
300 // TODO put something smart in the contentIntent below for all the possible errors
301 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
302 if (needsToUpdateCredentials
) {
303 // let the user update credentials with one click
304 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
305 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
306 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
307 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
308 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
309 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
310 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
311 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
312 notification
.setLatestEventInfo(getContext().getApplicationContext(),
313 getContext().getString(R
.string
.sync_fail_ticker
),
314 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
315 notification
.contentIntent
);
317 notification
.setLatestEventInfo(getContext().getApplicationContext(),
318 getContext().getString(R
.string
.sync_fail_ticker
),
319 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
320 notification
.contentIntent
);
322 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
327 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
329 * By now, we won't consider a failed synchronization.
331 private void notifyFailsInFavourites() {
332 if (mFailedResultsCounter
> 0) {
333 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
334 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
335 // TODO put something smart in the contentIntent below
336 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
337 notification
.setLatestEventInfo(getContext().getApplicationContext(),
338 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
339 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
340 notification
.contentIntent
);
341 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
344 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
345 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
346 // TODO put something smart in the contentIntent below
347 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
348 notification
.setLatestEventInfo(getContext().getApplicationContext(),
349 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
350 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
351 notification
.contentIntent
);
352 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
357 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
358 * copying them inside the ownCloud local directory was not possible.
360 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
361 * synchronization problems if a local file is linked to more than one remote file.
363 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
365 private void notifyForgottenLocalFiles() {
366 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
367 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
369 /// includes a pending intent in the notification showing a more detailed explanation
370 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
371 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
372 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
373 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
374 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
375 localPaths
.addAll(mForgottenLocalFiles
.values());
376 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
377 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
378 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
380 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
381 notification
.setLatestEventInfo(getContext().getApplicationContext(),
382 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
383 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
384 notification
.contentIntent
);
385 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);