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
;
32 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
33 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
34 import com
.owncloud
.android
.operations
.UpdateOCVersionOperation
;
36 import com.owncloud.android.files.services.FileDownloader;
37 import com.owncloud.android.files.services.FileObserverService;
38 import com.owncloud.android.utils.OwnCloudVersion;
39 >>>>>>> origin/master*/
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
;
75 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
76 super(context
, autoInitialize
);
83 public synchronized void onPerformSync(Account account
, Bundle extras
,
84 String authority
, ContentProviderClient provider
,
85 SyncResult syncResult
) {
87 mCancellation
= false
;
88 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
89 mFailedResultsCounter
= 0;
90 mLastFailedResult
= null
;
91 mSyncResult
= syncResult
;
93 this.setAccount(account
);
94 this.setContentProvider(provider
);
95 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
97 this.initClientForCurrentAccount();
98 } catch (UnknownHostException e
) {
99 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
100 mSyncResult
.tooManyRetries
= true
;
101 notifyFailedSynchronization();
105 Log
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
106 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
110 mCurrentSyncTime
= System
.currentTimeMillis();
111 if (!mCancellation
) {
112 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
115 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
120 // it's important making this although very unexpected errors occur; that's the reason for the finally
122 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
123 /// don't let the system synchronization manager retries MANUAL synchronizations
124 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
125 mSyncResult
.tooManyRetries
= true
;
127 /// notify the user about the failure of MANUAL synchronization
128 notifyFailedSynchronization();
130 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
138 * Called by system SyncManager when a synchronization is required to be cancelled.
140 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
141 * fetched will be still saved in the database. See onPerformSync implementation.
144 public void onSyncCanceled() {
145 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
146 mCancellation
= true
;
147 super.onSyncCanceled();
152 * Updates the locally stored version value of the ownCloud server
154 private void updateOCVersion() {
155 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
156 RemoteOperationResult result
= update
.execute(getClient());
157 if (!result
.isSuccess()) {
158 mLastFailedResult
= result
;
165 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
167 * @param remotePath Remote path to the folder to synchronize.
168 * @param parentId Database Id of the folder to synchronize.
170 private void fetchData(String remotePath
, long parentId
) {
172 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
175 // perform folder synchronization
176 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
183 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
186 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
187 sendStickyBroadcast(true
, remotePath
, null
);
189 if (result
.isSuccess()) {
190 // synchronize children folders
191 List
<OCFile
> children
= synchFolderOp
.getChildren();
192 fetchChildren(children
); // beware of the 'hidden' recursion here!
196 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
197 mSyncResult
.stats
.numAuthExceptions
++;
199 } else if (result
.getException() instanceof DavException
) {
200 mSyncResult
.stats
.numParseExceptions
++;
202 } else if (result
.getException() instanceof IOException
) {
203 mSyncResult
.stats
.numIoExceptions
++;
205 // insertion or update of files
206 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
207 for (int i = 1; i < resp.getResponses().length; ++i) {
208 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());
209 OCFile file = fillOCFile(we);
210 file.setParentId(parentId);
211 if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&
212 getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&
213 file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())
214 .getModificationTimestamp()) {
215 // first disable observer so we won't get file upload right after download
216 Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
217 Intent intent = new Intent(getContext(), FileObserverService.class);
218 intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
219 intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());
220 getContext().startService(intent);
221 intent = new Intent(this.getContext(), FileDownloader.class);
222 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
223 intent.putExtra(FileDownloader.EXTRA_FILE, file);
224 file.setKeepInSync(true);
225 getContext().startService(intent);
227 if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
228 file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
229 >>>>>>> origin/master*/
232 mFailedResultsCounter
++;
233 mLastFailedResult
= result
;
239 * Checks if a failed result should terminate the synchronization process immediately, according to
242 * @param failedResult Remote operation result to check.
243 * @return 'True' if the result should immediately finish the synchronization
245 private boolean isFinisher(RemoteOperationResult failedResult
) {
246 if (failedResult
!= null
) {
247 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
248 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
249 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
250 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
251 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
257 * Synchronize data of folders in the list of received files
259 * @param files Files to recursively fetch
261 private void fetchChildren(List
<OCFile
> files
) {
263 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
264 OCFile newFile
= files
.get(i
);
265 if (newFile
.isDirectory()) {
266 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
269 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
274 * Sends a message to any application component interested in the progress of the synchronization.
276 * @param inProgress 'True' when the synchronization progress is not finished.
277 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
279 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
280 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
281 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
282 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
283 if (dirRemotePath
!= null
) {
284 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
286 if (result
!= null
) {
287 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
289 getContext().sendStickyBroadcast(i
);
295 * Notifies the user about a failed synchronization through the status notification bar
297 private void notifyFailedSynchronization() {
298 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
299 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
300 // TODO put something smart in the contentIntent below
301 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
302 notification
.setLatestEventInfo(getContext().getApplicationContext(),
303 getContext().getString(R
.string
.sync_fail_ticker
),
304 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
305 notification
.contentIntent
);
306 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);