1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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
.net
.UnknownHostException
;
23 import java
.util
.List
;
25 import org
.apache
.jackrabbit
.webdav
.DavException
;
27 import com
.owncloud
.android
.R
;
28 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
29 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
30 import com
.owncloud
.android
.datamodel
.OCFile
;
31 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
32 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
33 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
35 import android
.accounts
.Account
;
36 import android
.app
.Notification
;
37 import android
.app
.NotificationManager
;
38 import android
.app
.PendingIntent
;
39 import android
.content
.ContentProviderClient
;
40 import android
.content
.ContentResolver
;
41 import android
.content
.Context
;
42 import android
.content
.Intent
;
43 import android
.content
.SyncResult
;
44 import android
.os
.Bundle
;
45 import android
.util
.Log
;
48 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
49 * platform ContactOperations provider.
51 * @author Bartek Przybylski
53 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
55 private final static String TAG
= "FileSyncAdapter";
58 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
60 private static final int MAX_FAILED_RESULTS
= 3;
62 private long mCurrentSyncTime
;
63 private boolean mCancellation
;
64 private boolean mIsManualSync
;
65 private int mFailedResultsCounter
;
66 private RemoteOperationResult mLastFailedResult
;
67 private SyncResult mSyncResult
;
69 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
70 super(context
, autoInitialize
);
77 public synchronized void onPerformSync(Account account
, Bundle extras
,
78 String authority
, ContentProviderClient provider
,
79 SyncResult syncResult
) {
81 mCancellation
= false
;
82 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
83 mFailedResultsCounter
= 0;
84 mLastFailedResult
= null
;
85 mSyncResult
= syncResult
;
87 this.setAccount(account
);
88 this.setContentProvider(provider
);
89 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
91 this.initClientForCurrentAccount();
92 } catch (UnknownHostException e
) {
93 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
94 mSyncResult
.tooManyRetries
= true
;
95 notifyFailedSynchronization();
99 Log
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
100 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
104 mCurrentSyncTime
= System
.currentTimeMillis();
105 if (!mCancellation
) {
106 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
109 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
114 // it's important making this although very unexpected errors occur; that's the reason for the finally
116 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
117 /// don't let the system synchronization manager retries MANUAL synchronizations
118 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
119 mSyncResult
.tooManyRetries
= true
;
121 /// notify the user about the failure of MANUAL synchronization
122 notifyFailedSynchronization();
124 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
132 * Called by system SyncManager when a synchronization is required to be cancelled.
134 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
135 * fetched will be still saved in the database. See onPerformSync implementation.
138 public void onSyncCanceled() {
139 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
140 mCancellation
= true
;
141 super.onSyncCanceled();
146 * Updates the locally stored version value of the ownCloud server
148 private void updateOCVersion() {
149 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
150 RemoteOperationResult result
= update
.execute(getClient());
151 if (!result
.isSuccess()) {
152 mLastFailedResult
= result
;
159 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
161 * @param remotePath Remote path to the folder to synchronize.
162 * @param parentId Database Id of the folder to synchronize.
164 private void fetchData(String remotePath
, long parentId
) {
166 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
169 // perform folder synchronization
170 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
177 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
180 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
181 sendStickyBroadcast(true
, remotePath
, null
);
183 if (result
.isSuccess()) {
184 // synchronize children folders
185 List
<OCFile
> children
= synchFolderOp
.getChildren();
186 fetchChildren(children
); // beware of the 'hidden' recursion here!
189 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
190 mSyncResult
.stats
.numAuthExceptions
++;
192 } else if (result
.getException() instanceof DavException
) {
193 mSyncResult
.stats
.numParseExceptions
++;
195 } else if (result
.getException() instanceof IOException
) {
196 mSyncResult
.stats
.numIoExceptions
++;
199 mFailedResultsCounter
++;
200 mLastFailedResult
= result
;
206 * Checks if a failed result should terminate the synchronization process immediately, according to
209 * @param failedResult Remote operation result to check.
210 * @return 'True' if the result should immediately finish the synchronization
212 private boolean isFinisher(RemoteOperationResult failedResult
) {
213 if (failedResult
!= null
) {
214 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
215 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
216 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
217 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
218 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
224 * Synchronize data of folders in the list of received files
226 * @param files Files to recursively fetch
228 private void fetchChildren(List
<OCFile
> files
) {
230 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
231 OCFile newFile
= files
.get(i
);
232 if (newFile
.isDirectory()) {
233 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
236 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
241 * Sends a message to any application component interested in the progress of the synchronization.
243 * @param inProgress 'True' when the synchronization progress is not finished.
244 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
246 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
247 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
248 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
249 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
250 if (dirRemotePath
!= null
) {
251 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
253 if (result
!= null
) {
254 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
256 getContext().sendStickyBroadcast(i
);
262 * Notifies the user about a failed synchronization through the status notification bar
264 private void notifyFailedSynchronization() {
265 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
266 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
267 // TODO put something smart in the contentIntent below
268 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
269 notification
.setLatestEventInfo(getContext().getApplicationContext(),
270 getContext().getString(R
.string
.sync_fail_ticker
),
271 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
272 notification
.contentIntent
);
273 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);