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 as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 package com
.owncloud
.android
.syncadapter
;
22 import java
.io
.IOException
;
23 import java
.net
.UnknownHostException
;
24 import java
.util
.ArrayList
;
25 import java
.util
.HashMap
;
26 import java
.util
.List
;
29 import org
.apache
.jackrabbit
.webdav
.DavException
;
31 import com
.owncloud
.android
.R
;
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
.app
.Notification
;
42 import android
.app
.NotificationManager
;
43 import android
.app
.PendingIntent
;
44 import android
.content
.ContentProviderClient
;
45 import android
.content
.ContentResolver
;
46 import android
.content
.Context
;
47 import android
.content
.Intent
;
48 import android
.content
.SyncResult
;
49 import android
.os
.Bundle
;
50 import android
.util
.Log
;
53 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
54 * platform ContactOperations provider.
56 * @author Bartek Przybylski
58 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
60 private final static String TAG
= "FileSyncAdapter";
63 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
65 private static final int MAX_FAILED_RESULTS
= 3;
67 private long mCurrentSyncTime
;
68 private boolean mCancellation
;
69 private boolean mIsManualSync
;
70 private int mFailedResultsCounter
;
71 private RemoteOperationResult mLastFailedResult
;
72 private SyncResult mSyncResult
;
73 private int mConflictsFound
;
74 private int mFailsInFavouritesFound
;
75 private Map
<String
, String
> mForgottenLocalFiles
;
78 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
79 super(context
, autoInitialize
);
86 public synchronized void onPerformSync(Account account
, Bundle extras
,
87 String authority
, ContentProviderClient provider
,
88 SyncResult syncResult
) {
90 mCancellation
= false
;
91 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
92 mFailedResultsCounter
= 0;
93 mLastFailedResult
= null
;
95 mFailsInFavouritesFound
= 0;
96 mForgottenLocalFiles
= new HashMap
<String
, String
>();
97 mSyncResult
= syncResult
;
98 mSyncResult
.fullSyncRequested
= false
;
99 mSyncResult
.delayUntil
= 60*60*24; // sync after 24h
101 this.setAccount(account
);
102 this.setContentProvider(provider
);
103 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
105 this.initClientForCurrentAccount();
106 } catch (UnknownHostException e
) {
107 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
108 mSyncResult
.tooManyRetries
= true
;
109 notifyFailedSynchronization();
113 Log
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
114 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
118 mCurrentSyncTime
= System
.currentTimeMillis();
119 if (!mCancellation
) {
120 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
123 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
128 // it's important making this although very unexpected errors occur; that's the reason for the finally
130 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
131 /// don't let the system synchronization manager retries MANUAL synchronizations
132 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
133 mSyncResult
.tooManyRetries
= true
;
135 /// notify the user about the failure of MANUAL synchronization
136 notifyFailedSynchronization();
139 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
140 notifyFailsInFavourites();
142 if (mForgottenLocalFiles
.size() > 0) {
143 notifyForgottenLocalFiles();
146 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
153 * Called by system SyncManager when a synchronization is required to be cancelled.
155 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
156 * fetched will be still saved in the database. See onPerformSync implementation.
159 public void onSyncCanceled() {
160 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
161 mCancellation
= true
;
162 super.onSyncCanceled();
167 * Updates the locally stored version value of the ownCloud server
169 private void updateOCVersion() {
170 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
171 RemoteOperationResult result
= update
.execute(getClient());
172 if (!result
.isSuccess()) {
173 mLastFailedResult
= result
;
180 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
182 * @param remotePath Remote path to the folder to synchronize.
183 * @param parentId Database Id of the folder to synchronize.
185 private void fetchData(String remotePath
, long parentId
) {
187 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
190 // perform folder synchronization
191 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
198 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
201 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
202 sendStickyBroadcast(true
, remotePath
, null
);
204 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
206 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
207 mConflictsFound
+= synchFolderOp
.getConflictsFound();
208 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
210 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
211 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
213 // synchronize children folders
214 List
<OCFile
> children
= synchFolderOp
.getChildren();
215 fetchChildren(children
); // beware of the 'hidden' recursion here!
218 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
219 mSyncResult
.stats
.numAuthExceptions
++;
221 } else if (result
.getException() instanceof DavException
) {
222 mSyncResult
.stats
.numParseExceptions
++;
224 } else if (result
.getException() instanceof IOException
) {
225 mSyncResult
.stats
.numIoExceptions
++;
227 mFailedResultsCounter
++;
228 mLastFailedResult
= result
;
234 * Checks if a failed result should terminate the synchronization process immediately, according to
237 * @param failedResult Remote operation result to check.
238 * @return 'True' if the result should immediately finish the synchronization
240 private boolean isFinisher(RemoteOperationResult failedResult
) {
241 if (failedResult
!= null
) {
242 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
243 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
244 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
245 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
246 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
252 * Synchronize data of folders in the list of received files
254 * @param files Files to recursively fetch
256 private void fetchChildren(List
<OCFile
> files
) {
258 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
259 OCFile newFile
= files
.get(i
);
260 if (newFile
.isDirectory()) {
261 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
264 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
269 * Sends a message to any application component interested in the progress of the synchronization.
271 * @param inProgress 'True' when the synchronization progress is not finished.
272 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
274 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
275 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
276 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
277 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
278 if (dirRemotePath
!= null
) {
279 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
281 if (result
!= null
) {
282 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
284 getContext().sendStickyBroadcast(i
);
290 * Notifies the user about a failed synchronization through the status notification bar
292 private void notifyFailedSynchronization() {
293 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
294 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
295 // TODO put something smart in the contentIntent below
296 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
297 notification
.setLatestEventInfo(getContext().getApplicationContext(),
298 getContext().getString(R
.string
.sync_fail_ticker
),
299 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
300 notification
.contentIntent
);
301 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
306 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
308 * By now, we won't consider a failed synchronization.
310 private void notifyFailsInFavourites() {
311 if (mFailedResultsCounter
> 0) {
312 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
313 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
314 // TODO put something smart in the contentIntent below
315 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
316 notification
.setLatestEventInfo(getContext().getApplicationContext(),
317 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
318 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
319 notification
.contentIntent
);
320 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
323 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
324 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
325 // TODO put something smart in the contentIntent below
326 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
327 notification
.setLatestEventInfo(getContext().getApplicationContext(),
328 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
329 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
330 notification
.contentIntent
);
331 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
337 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
338 * copying them inside the ownCloud local directory was not possible.
340 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
341 * synchronization problems if a local file is linked to more than one remote file.
343 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
345 private void notifyForgottenLocalFiles() {
346 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
347 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
349 /// includes a pending intent in the notification showing a more detailed explanation
350 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
351 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
352 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
353 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
354 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
355 localPaths
.addAll(mForgottenLocalFiles
.values());
356 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
357 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
358 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
360 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
361 notification
.setLatestEventInfo(getContext().getApplicationContext(),
362 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
363 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
364 notification
.contentIntent
);
365 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);