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
.Log_OC
;
32 import com
.owncloud
.android
.R
;
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 android
.accounts
.Account
;
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
;
51 import android
.util
.Log
;
54 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
55 * platform ContactOperations provider.
57 * @author Bartek Przybylski
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 (UnknownHostException 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();
114 Log_OC
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
115 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
119 mCurrentSyncTime
= System
.currentTimeMillis();
120 if (!mCancellation
) {
121 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
124 Log_OC
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
129 // it's important making this although very unexpected errors occur; that's the reason for the finally
131 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
132 /// don't let the system synchronization manager retries MANUAL synchronizations
133 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
134 mSyncResult
.tooManyRetries
= true
;
136 /// notify the user about the failure of MANUAL synchronization
137 notifyFailedSynchronization();
140 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
141 notifyFailsInFavourites();
143 if (mForgottenLocalFiles
.size() > 0) {
144 notifyForgottenLocalFiles();
147 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
154 * Called by system SyncManager when a synchronization is required to be cancelled.
156 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
157 * fetched will be still saved in the database. See onPerformSync implementation.
160 public void onSyncCanceled() {
161 Log_OC
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
162 mCancellation
= true
;
163 super.onSyncCanceled();
168 * Updates the locally stored version value of the ownCloud server
170 private void updateOCVersion() {
171 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
172 RemoteOperationResult result
= update
.execute(getClient());
173 if (!result
.isSuccess()) {
174 mLastFailedResult
= result
;
181 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
183 * @param remotePath Remote path to the folder to synchronize.
184 * @param parentId Database Id of the folder to synchronize.
186 private void fetchData(String remotePath
, long parentId
) {
188 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
191 // perform folder synchronization
192 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
199 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
202 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
203 sendStickyBroadcast(true
, remotePath
, null
);
205 if (result
.isSuccess() || result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
207 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
208 mConflictsFound
+= synchFolderOp
.getConflictsFound();
209 mFailsInFavouritesFound
+= synchFolderOp
.getFailsInFavouritesFound();
211 if (synchFolderOp
.getForgottenLocalFiles().size() > 0) {
212 mForgottenLocalFiles
.putAll(synchFolderOp
.getForgottenLocalFiles());
214 // synchronize children folders
215 List
<OCFile
> children
= synchFolderOp
.getChildren();
216 fetchChildren(children
); // beware of the 'hidden' recursion here!
219 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
220 mSyncResult
.stats
.numAuthExceptions
++;
222 } else if (result
.getException() instanceof DavException
) {
223 mSyncResult
.stats
.numParseExceptions
++;
225 } else if (result
.getException() instanceof IOException
) {
226 mSyncResult
.stats
.numIoExceptions
++;
228 mFailedResultsCounter
++;
229 mLastFailedResult
= result
;
235 * Checks if a failed result should terminate the synchronization process immediately, according to
238 * @param failedResult Remote operation result to check.
239 * @return 'True' if the result should immediately finish the synchronization
241 private boolean isFinisher(RemoteOperationResult failedResult
) {
242 if (failedResult
!= null
) {
243 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
244 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
245 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
246 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
247 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
253 * Synchronize data of folders in the list of received files
255 * @param files Files to recursively fetch
257 private void fetchChildren(List
<OCFile
> files
) {
259 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
260 OCFile newFile
= files
.get(i
);
261 if (newFile
.isDirectory()) {
262 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
265 if (mCancellation
&& i
<files
.size()) Log_OC
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
270 * Sends a message to any application component interested in the progress of the synchronization.
272 * @param inProgress 'True' when the synchronization progress is not finished.
273 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
275 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
276 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
277 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
278 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
279 if (dirRemotePath
!= null
) {
280 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
282 if (result
!= null
) {
283 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
285 getContext().sendStickyBroadcast(i
);
291 * Notifies the user about a failed synchronization through the status notification bar
293 private void notifyFailedSynchronization() {
294 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
295 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
296 // TODO put something smart in the contentIntent below
297 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
298 notification
.setLatestEventInfo(getContext().getApplicationContext(),
299 getContext().getString(R
.string
.sync_fail_ticker
),
300 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
301 notification
.contentIntent
);
302 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
307 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
309 * By now, we won't consider a failed synchronization.
311 private void notifyFailsInFavourites() {
312 if (mFailedResultsCounter
> 0) {
313 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_in_favourites_ticker
), System
.currentTimeMillis());
314 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
315 // TODO put something smart in the contentIntent below
316 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
317 notification
.setLatestEventInfo(getContext().getApplicationContext(),
318 getContext().getString(R
.string
.sync_fail_in_favourites_ticker
),
319 String
.format(getContext().getString(R
.string
.sync_fail_in_favourites_content
), mFailedResultsCounter
+ mConflictsFound
, mConflictsFound
),
320 notification
.contentIntent
);
321 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_in_favourites_ticker
, notification
);
324 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
), System
.currentTimeMillis());
325 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
326 // TODO put something smart in the contentIntent below
327 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
328 notification
.setLatestEventInfo(getContext().getApplicationContext(),
329 getContext().getString(R
.string
.sync_conflicts_in_favourites_ticker
),
330 String
.format(getContext().getString(R
.string
.sync_conflicts_in_favourites_content
), mConflictsFound
),
331 notification
.contentIntent
);
332 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_conflicts_in_favourites_ticker
, notification
);
338 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
339 * copying them inside the ownCloud local directory was not possible.
341 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
342 * synchronization problems if a local file is linked to more than one remote file.
344 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
346 private void notifyForgottenLocalFiles() {
347 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
), System
.currentTimeMillis());
348 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
350 /// includes a pending intent in the notification showing a more detailed explanation
351 Intent explanationIntent
= new Intent(getContext(), ErrorsWhileCopyingHandlerActivity
.class);
352 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_ACCOUNT
, getAccount());
353 ArrayList
<String
> remotePaths
= new ArrayList
<String
>();
354 ArrayList
<String
> localPaths
= new ArrayList
<String
>();
355 remotePaths
.addAll(mForgottenLocalFiles
.keySet());
356 localPaths
.addAll(mForgottenLocalFiles
.values());
357 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_LOCAL_PATHS
, localPaths
);
358 explanationIntent
.putExtra(ErrorsWhileCopyingHandlerActivity
.EXTRA_REMOTE_PATHS
, remotePaths
);
359 explanationIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
361 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), explanationIntent
, 0);
362 notification
.setLatestEventInfo(getContext().getApplicationContext(),
363 getContext().getString(R
.string
.sync_foreign_files_forgotten_ticker
),
364 String
.format(getContext().getString(R
.string
.sync_foreign_files_forgotten_content
), mForgottenLocalFiles
.size(), getContext().getString(R
.string
.app_name
)),
365 notification
.contentIntent
);
366 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_foreign_files_forgotten_ticker
, notification
);