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
;
92 mSyncResult
.fullSyncRequested
= false
;
93 mSyncResult
.delayUntil
= 60*60*24; // sync after 24h
95 this.setAccount(account
);
96 this.setContentProvider(provider
);
97 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
99 this.initClientForCurrentAccount();
100 } catch (UnknownHostException e
) {
101 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
102 mSyncResult
.tooManyRetries
= true
;
103 notifyFailedSynchronization();
107 Log
.d(TAG
, "Synchronization of ownCloud account " + account
.name
+ " starting");
108 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
112 mCurrentSyncTime
= System
.currentTimeMillis();
113 if (!mCancellation
) {
114 fetchData(OCFile
.PATH_SEPARATOR
, DataStorageManager
.ROOT_PARENT_ID
);
117 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
122 // it's important making this although very unexpected errors occur; that's the reason for the finally
124 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
125 /// don't let the system synchronization manager retries MANUAL synchronizations
126 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
127 mSyncResult
.tooManyRetries
= true
;
129 /// notify the user about the failure of MANUAL synchronization
130 notifyFailedSynchronization();
132 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
140 * Called by system SyncManager when a synchronization is required to be cancelled.
142 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
143 * fetched will be still saved in the database. See onPerformSync implementation.
146 public void onSyncCanceled() {
147 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
148 mCancellation
= true
;
149 super.onSyncCanceled();
154 * Updates the locally stored version value of the ownCloud server
156 private void updateOCVersion() {
157 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(getAccount(), getContext());
158 RemoteOperationResult result
= update
.execute(getClient());
159 if (!result
.isSuccess()) {
160 mLastFailedResult
= result
;
167 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
169 * @param remotePath Remote path to the folder to synchronize.
170 * @param parentId Database Id of the folder to synchronize.
172 private void fetchData(String remotePath
, long parentId
) {
174 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
|| isFinisher(mLastFailedResult
))
177 // perform folder synchronization
178 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
185 RemoteOperationResult result
= synchFolderOp
.execute(getClient());
188 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
189 sendStickyBroadcast(true
, remotePath
, null
);
191 if (result
.isSuccess()) {
192 // synchronize children folders
193 List
<OCFile
> children
= synchFolderOp
.getChildren();
194 fetchChildren(children
); // beware of the 'hidden' recursion here!
198 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
199 mSyncResult
.stats
.numAuthExceptions
++;
201 } else if (result
.getException() instanceof DavException
) {
202 mSyncResult
.stats
.numParseExceptions
++;
204 } else if (result
.getException() instanceof IOException
) {
205 mSyncResult
.stats
.numIoExceptions
++;
207 // insertion or update of files
208 List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
209 for (int i = 1; i < resp.getResponses().length; ++i) {
210 WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());
211 OCFile file = fillOCFile(we);
212 file.setParentId(parentId);
213 if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&
214 getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&
215 file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())
216 .getModificationTimestamp()) {
217 // first disable observer so we won't get file upload right after download
218 Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
219 Intent intent = new Intent(getContext(), FileObserverService.class);
220 intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
221 intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());
222 getContext().startService(intent);
223 intent = new Intent(this.getContext(), FileDownloader.class);
224 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
225 intent.putExtra(FileDownloader.EXTRA_FILE, file);
226 file.setKeepInSync(true);
227 getContext().startService(intent);
229 if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
230 file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
231 >>>>>>> origin/master*/
234 mFailedResultsCounter
++;
235 mLastFailedResult
= result
;
241 * Checks if a failed result should terminate the synchronization process immediately, according to
244 * @param failedResult Remote operation result to check.
245 * @return 'True' if the result should immediately finish the synchronization
247 private boolean isFinisher(RemoteOperationResult failedResult
) {
248 if (failedResult
!= null
) {
249 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
250 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
251 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
252 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
253 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
259 * Synchronize data of folders in the list of received files
261 * @param files Files to recursively fetch
263 private void fetchChildren(List
<OCFile
> files
) {
265 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
266 OCFile newFile
= files
.get(i
);
267 if (newFile
.isDirectory()) {
268 fetchData(newFile
.getRemotePath(), newFile
.getFileId());
271 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
276 * Sends a message to any application component interested in the progress of the synchronization.
278 * @param inProgress 'True' when the synchronization progress is not finished.
279 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
281 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
282 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
283 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
284 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
285 if (dirRemotePath
!= null
) {
286 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
288 if (result
!= null
) {
289 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
291 getContext().sendStickyBroadcast(i
);
297 * Notifies the user about a failed synchronization through the status notification bar
299 private void notifyFailedSynchronization() {
300 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
301 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
302 // TODO put something smart in the contentIntent below
303 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
304 notification
.setLatestEventInfo(getContext().getApplicationContext(),
305 getContext().getString(R
.string
.sync_fail_ticker
),
306 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
307 notification
.contentIntent
);
308 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);