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() &&
229 AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(getClient().getAuthTokenType()))) {
230 mSyncResult
.stats
.numAuthExceptions
++;
232 } else if (result
.getException() instanceof DavException
) {
233 mSyncResult
.stats
.numParseExceptions
++;
235 } else if (result
.getException() instanceof IOException
) {
236 mSyncResult
.stats
.numIoExceptions
++;
238 mFailedResultsCounter
++;
239 mLastFailedResult
= result
;
245 * Checks if a failed result should terminate the synchronization process immediately, according to
248 * @param failedResult Remote operation result to check.
249 * @return 'True' if the result should immediately finish the synchronization
251 private boolean isFinisher(RemoteOperationResult failedResult
) {
252 if (failedResult
!= null
) {
253 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
254 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
255 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
256 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
257 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
263 * Synchronize data of folders in the list of received files
265 * @param files Files to recursively fetch
267 private void fetchChildren(List
<OCFile
> files
) {
269 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
270 OCFile newFile
= files
.get(i
);
271 if (newFile
.isDirectory()) {
272 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
274 // Update folder size on DB
275 getStorageManager().calculateFolderSize(newFile
.getFileId());
279 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
284 * Sends a message to any application component interested in the progress of the synchronization.
286 * @param inProgress 'True' when the synchronization progress is not finished.
287 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
289 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
290 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
291 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
292 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
293 if (dirRemotePath
!= null
) {
294 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
296 if (result
!= null
) {
297 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
299 getContext().sendStickyBroadcast(i
);
305 * Notifies the user about a failed synchronization through the status notification bar
307 private void notifyFailedSynchronization() {
308 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
309 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
310 boolean needsToUpdateCredentials
= (mLastFailedResult
!= null
&&
311 ( mLastFailedResult
.getCode() == ResultCode
.UNAUTHORIZED
||
312 (mLastFailedResult
.isTemporalRedirection() && mLastFailedResult
.isIdPRedirection() &&
313 AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(getClient().getAuthTokenType()))
316 // TODO put something smart in the contentIntent below for all the possible errors
317 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
318 if (needsToUpdateCredentials
) {
319 // let the user update credentials with one click
320 Intent updateAccountCredentials
= new Intent(getContext(), AuthenticatorActivity
.class);
321 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, getAccount());
322 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ENFORCED_UPDATE
, true
);
323 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_TOKEN
);
324 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
325 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
326 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
327 notification
.contentIntent
= PendingIntent
.getActivity(getContext(), (int)System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
);
328 notification
.setLatestEventInfo(getContext().getApplicationContext(),
329 getContext().getString(R
.string
.sync_fail_ticker
),
330 String
.format(getContext().getString(R
.string
.sync_fail_content_unauthorized
), getAccount().name
),
331 notification
.contentIntent
);
333 notification
.setLatestEventInfo(getContext().getApplicationContext(),
334 getContext().getString(R
.string
.sync_fail_ticker
),
335 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
336 notification
.contentIntent
);
338 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
343 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
345 * By now, we won't consider a failed synchronization.
347 private void notifyFailsInFavourites() {
348 if (mFailedResultsCounter
> 0) {
349 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
350 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
351 // TODO put something smart in the contentIntent below
352 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
353 notification
.setLatestEventInfo(getContext().getApplicationContext(),
354 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
355 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
356 notification
.contentIntent
);
357 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
360 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
361 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
362 // TODO put something smart in the contentIntent below
363 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
364 notification
.setLatestEventInfo(getContext().getApplicationContext(),
365 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
366 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
367 notification
.contentIntent
);
368 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
373 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
374 * copying them inside the ownCloud local directory was not possible.
376 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
377 * synchronization problems if a local file is linked to more than one remote file.
379 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
381 private void notifyForgottenLocalFiles() {
382 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
383 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
385 /// includes a pending intent in the notification showing a more detailed explanation
386 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
387 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
388 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
389 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
390 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
391 localPaths
.addAll(mForgottenLocalFiles
.values());
392 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
393 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
394 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
396 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
397 notification
.setLatestEventInfo(getContext().getApplicationContext(),
398 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
399 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
400 notification
.contentIntent
);
401 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);