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
.DataStorageManager
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
36 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
37 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
38 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
39 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
40 import com
.owncloud
.android
.ui
.activity
.ErrorsWhileCopyingHandlerActivity
;
41 import com
.owncloud
.android
.utils
.FileStorageUtils
;
43 import android
.accounts
.Account
;
44 import android
.accounts
.AccountsException
;
45 import android
.app
.Notification
;
46 import android
.app
.NotificationManager
;
47 import android
.app
.PendingIntent
;
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
;
56 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
57 * platform ContactOperations provider.
59 * @author Bartek Przybylski
60 * @author David A. Velasco
62 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
64 private final static String TAG
= "FileSyncAdapter";
67 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
69 private static final int MAX_FAILED_RESULTS
= 3;
71 private long mCurrentSyncTime
;
72 private boolean mCancellation
;
73 private boolean mIsManualSync
;
74 private int mFailedResultsCounter
;
75 private RemoteOperationResult mLastFailedResult
;
76 private SyncResult mSyncResult
;
77 private int mConflictsFound
;
78 private int mFailsInFavouritesFound
;
79 private Map
<String
, String
> mForgottenLocalFiles
;
82 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
83 super(context
, autoInitialize
);
90 public synchronized void onPerformSync(Account account
, Bundle extras
,
91 String authority
, ContentProviderClient provider
,
92 SyncResult syncResult
) {
94 mCancellation
= false
;
95 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
96 mFailedResultsCounter
= 0;
97 mLastFailedResult
= null
;
99 mFailsInFavouritesFound
= 0;
100 mForgottenLocalFiles
= new HashMap
<String
, String
>();
101 mSyncResult
= syncResult
;
102 mSyncResult
.fullSyncRequested
= false
;
103 mSyncResult
.delayUntil
= 60*60*24; // sync after 24h
105 this.setAccount(account
);
106 this.setContentProvider(provider
);
107 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
109 this.initClientForCurrentAccount();
110 } catch (IOException e
) {
111 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
112 mSyncResult
.tooManyRetries
= true
;
113 notifyFailedSynchronization();
115 } catch (AccountsException e
) {
116 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
117 mSyncResult
.tooManyRetries
= true
;
118 notifyFailedSynchronization();
122 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
123 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
127 mCurrentSyncTime
= System
.currentTimeMillis();
128 if (!mCancellation
) {
129 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
132 Log_OC
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
137 // it's important making this although very unexpected errors occur; that's the reason for the finally
139 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
140 /// don't let the system synchronization manager retries MANUAL synchronizations
141 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
142 mSyncResult
.tooManyRetries
= true
;
144 /// notify the user about the failure of MANUAL synchronization
145 notifyFailedSynchronization();
148 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
149 notifyFailsInFavourites();
151 if (mForgottenLocalFiles
.size() > 0) {
152 notifyForgottenLocalFiles();
155 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
161 * Called by system SyncManager when a synchronization is required to be cancelled.
163 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
164 * fetched will be still saved in the database. See onPerformSync implementation.
167 public void onSyncCanceled() {
168 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
169 mCancellation
= true
;
170 super.onSyncCanceled();
175 * Updates the locally stored version value of the ownCloud server
177 private void updateOCVersion() {
178 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
179 RemoteOperationResult result
= update
.execute(getClient());
180 if (!result
.isSuccess()) {
181 mLastFailedResult
= result
;
187 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
189 * @param remotePath Remote path to the folder to synchronize.
190 * @param parentId Database Id of the folder to synchronize.
192 private void fetchData(String remotePath
, long parentId
) {
194 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
197 // perform folder synchronization
198 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
205 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
208 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
209 sendStickyBroadcast(true
, remotePath
, null
);
211 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
213 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
214 mConflictsFound
+= synchFolderOp
.getConflictsFound();
215 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
217 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
218 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
220 // synchronize children folders
221 List
<OCFile
> children
= synchFolderOp
.getChildren();
222 fetchChildren(children
); // beware of the 'hidden' recursion here!
224 sendStickyBroadcast(true
, remotePath
, null
);
227 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
||
228 ((result
.isTemporalRedirection() || result
.isIdPRedirection()) && getClient().getSsoSessionCookie() != null
)) {
229 mSyncResult
.stats
.numAuthExceptions
++;
231 } else if (result
.getException() instanceof DavException
) {
232 mSyncResult
.stats
.numParseExceptions
++;
234 } else if (result
.getException() instanceof IOException
) {
235 mSyncResult
.stats
.numIoExceptions
++;
237 mFailedResultsCounter
++;
238 mLastFailedResult
= result
;
244 * Checks if a failed result should terminate the synchronization process immediately, according to
247 * @param failedResult Remote operation result to check.
248 * @return 'True' if the result should immediately finish the synchronization
250 private boolean isFinisher(RemoteOperationResult failedResult
) {
251 if (failedResult
!= null
) {
252 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
253 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
254 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
255 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
256 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
262 * Synchronize data of folders in the list of received files
264 * @param files Files to recursively fetch
266 private void fetchChildren(List
<OCFile
> files
) {
268 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
269 OCFile newFile
= files
.get(i
);
270 if (newFile
.isDirectory()) {
271 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
273 // Update folder size on DB
274 getStorageManager().calculateFolderSize(newFile
.getFileId());
278 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
283 * Sends a message to any application component interested in the progress of the synchronization.
285 * @param inProgress 'True' when the synchronization progress is not finished.
286 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
288 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
289 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
290 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
291 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
292 if (dirRemotePath
!= null
) {
293 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
295 if (result
!= null
) {
296 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
298 getContext().sendStickyBroadcast(i
);
304 * Notifies the user about a failed synchronization through the status notification bar
306 private void notifyFailedSynchronization() {
307 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
308 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
309 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&&
310 ( mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
311 ((mLastFailedResult
.isTemporalRedirection() || mLastFailedResult
.isIdPRedirection())
312 && AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(getClient().getAuthTokenType()))
315 // TODO put something smart in the contentIntent below for all the possible errors
316 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
317 if (needsToUpdateCredentials
) {
318 // let the user update credentials with one click
319 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
320 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
321 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
322 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
323 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
324 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
325 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
326 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
327 notification
.setLatestEventInfo(getContext().getApplicationContext(),
328 getContext().getString(R
.string
.sync_fail_ticker
),
329 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
330 notification
.contentIntent
);
332 notification
.setLatestEventInfo(getContext().getApplicationContext(),
333 getContext().getString(R
.string
.sync_fail_ticker
),
334 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
335 notification
.contentIntent
);
337 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
342 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
344 * By now, we won't consider a failed synchronization.
346 private void notifyFailsInFavourites() {
347 if (mFailedResultsCounter
> 0) {
348 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
349 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
350 // TODO put something smart in the contentIntent below
351 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
352 notification
.setLatestEventInfo(getContext().getApplicationContext(),
353 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
354 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
355 notification
.contentIntent
);
356 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
359 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
360 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
361 // TODO put something smart in the contentIntent below
362 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
363 notification
.setLatestEventInfo(getContext().getApplicationContext(),
364 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
365 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
366 notification
.contentIntent
);
367 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
372 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
373 * copying them inside the ownCloud local directory was not possible.
375 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
376 * synchronization problems if a local file is linked to more than one remote file.
378 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
380 private void notifyForgottenLocalFiles() {
381 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
382 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
384 /// includes a pending intent in the notification showing a more detailed explanation
385 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
386 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
387 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
388 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
389 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
390 localPaths
.addAll(mForgottenLocalFiles
.values());
391 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
392 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
393 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
395 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
396 notification
.setLatestEventInfo(getContext().getApplicationContext(),
397 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
398 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
399 notification
.contentIntent
);
400 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);