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
.util
.List
;
24 import org
.apache
.jackrabbit
.webdav
.DavException
;
25 import org
.json
.JSONObject
;
27 import com
.owncloud
.android
.AccountUtils
;
28 import com
.owncloud
.android
.R
;
29 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
30 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
31 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
32 import com
.owncloud
.android
.datamodel
.OCFile
;
33 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
34 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
35 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
37 import android
.accounts
.Account
;
38 import android
.app
.Notification
;
39 import android
.app
.NotificationManager
;
40 import android
.app
.PendingIntent
;
41 import android
.content
.ContentProviderClient
;
42 import android
.content
.ContentResolver
;
43 import android
.content
.Context
;
44 import android
.content
.Intent
;
45 import android
.content
.SyncResult
;
46 import android
.os
.Bundle
;
47 import android
.util
.Log
;
48 import eu
.alefzero
.webdav
.WebdavClient
;
51 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
52 * platform ContactOperations provider.
54 * @author Bartek Przybylski
56 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
58 private final static String TAG
= "FileSyncAdapter";
61 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
63 private static final int MAX_FAILED_RESULTS
= 3;
65 private long mCurrentSyncTime
;
66 private boolean mCancellation
;
67 private boolean mIsManualSync
;
68 private int mFailedResultsCounter
;
69 private RemoteOperationResult mLastFailedResult
;
71 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
72 super(context
, autoInitialize
);
76 public synchronized void onPerformSync(Account account
, Bundle extras
,
77 String authority
, ContentProviderClient provider
,
78 SyncResult syncResult
) {
80 mCancellation
= false
;
81 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
82 mFailedResultsCounter
= 0;
83 mLastFailedResult
= null
;
85 this.setAccount(account
);
86 this.setContentProvider(provider
);
87 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
89 Log
.d(TAG
, "syncing owncloud account " + account
.name
);
91 sendStickyBroadcast(true
, null
, null
); // message to signal the start of the synchronization to the UI
95 mCurrentSyncTime
= System
.currentTimeMillis();
97 fetchData(OCFile
.PATH_SEPARATOR
, syncResult
, DataStorageManager
.ROOT_PARENT_ID
);
100 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
104 // it's important making this although very unexpected errors occur; that's the reason for the finally
106 if (mFailedResultsCounter
> 0 && mIsManualSync
) {
107 /// don't let the system synchronization manager retries MANUAL synchronizations
108 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
109 syncResult
.tooManyRetries
= true
;
111 /// notify the user about the failure of MANUAL synchronization
112 notifyFailedSynchronization();
114 sendStickyBroadcast(false
, null
, mLastFailedResult
); // message to signal the end to the UI
122 * Called by system SyncManager when a synchronization is required to be cancelled.
124 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
125 * fetched will be still saved in the database. See onPerformSync implementation.
128 public void onSyncCanceled() {
129 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
130 mCancellation
= true
;
131 super.onSyncCanceled();
136 * Updates the locally stored version value of the ownCloud server
138 private void updateOCVersion() {
139 String statUrl
= getAccountManager().getUserData(getAccount(), AccountAuthenticator
.KEY_OC_BASE_URL
);
140 statUrl
+= AccountUtils
.STATUS_PATH
;
143 String result
= getClient().getResultAsString(statUrl
);
144 if (result
!= null
) {
146 JSONObject json
= new JSONObject(result
);
147 if (json
!= null
&& json
.getString("version") != null
) {
148 OwnCloudVersion ocver
= new OwnCloudVersion(json
.getString("version"));
149 if (ocver
.isVersionValid()) {
150 getAccountManager().setUserData(getAccount(), AccountAuthenticator
.KEY_OC_VERSION
, ocver
.toString());
151 Log
.d(TAG
, "Got new OC version " + ocver
.toString());
153 Log
.w(TAG
, "Invalid version number received from server: " + json
.getString("version"));
156 } catch (Throwable e
) {
157 Log
.w(TAG
, "Couldn't parse version response", e
);
160 Log
.w(TAG
, "Problem while getting ocversion from server");
162 } catch (Exception e
) {
163 Log
.e(TAG
, "Problem getting response from server", e
);
170 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
172 * @param remotePath Remote path to the folder to synchronize.
173 * @param parentId Database Id of the folder to synchronize.
174 * @param syncResult Object to update for communicate results to the system's synchronization manager.
176 private void fetchData(String remotePath
, SyncResult syncResult
, long parentId
) {
178 if (mFailedResultsCounter
> MAX_FAILED_RESULTS
&& isFinisher(mLastFailedResult
))
181 // get client object to connect to the remote ownCloud server
182 WebdavClient client
= null
;
184 client
= getClient();
185 } catch (IOException e
) {
186 syncResult
.stats
.numIoExceptions
++;
187 Log
.d(TAG
, "Could not get client object while trying to synchronize - impossible to continue");
191 // perform folder synchronization
192 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
199 RemoteOperationResult result
= synchFolderOp
.execute(client
);
202 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
203 sendStickyBroadcast(true
, remotePath
, null
);
205 if (result
.isSuccess()) {
206 // synchronize children folders
207 List
<OCFile
> children
= synchFolderOp
.getChildren();
208 fetchChildren(children
, syncResult
); // beware of the 'hidden' recursion here!
211 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
212 syncResult
.stats
.numAuthExceptions
++;
214 } else if (result
.getException() instanceof DavException
) {
215 syncResult
.stats
.numParseExceptions
++;
217 } else if (result
.getException() instanceof IOException
) {
218 syncResult
.stats
.numIoExceptions
++;
221 mFailedResultsCounter
++;
222 mLastFailedResult
= result
;
228 * Checks if a failed result should terminate the synchronization process immediately, according to
231 * @param failedResult Remote operation result to check.
232 * @return 'True' if the result should immediately finish the synchronization
234 private boolean isFinisher(RemoteOperationResult failedResult
) {
235 if (failedResult
!= null
) {
236 RemoteOperationResult
.ResultCode code
= failedResult
.getCode();
237 return (code
.equals(RemoteOperationResult
.ResultCode
.SSL_ERROR
) ||
238 code
.equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) ||
239 code
.equals(RemoteOperationResult
.ResultCode
.BAD_OC_VERSION
) ||
240 code
.equals(RemoteOperationResult
.ResultCode
.INSTANCE_NOT_CONFIGURED
));
246 * Synchronize data of folders in the list of received files
248 * @param files Files to recursively fetch
249 * @param syncResult Updated object to provide results to the Synchronization Manager
251 private void fetchChildren(List
<OCFile
> files
, SyncResult syncResult
) {
253 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
254 OCFile newFile
= files
.get(i
);
255 if (newFile
.isDirectory()) {
256 fetchData(newFile
.getRemotePath(), syncResult
, newFile
.getFileId());
259 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
264 * Sends a message to any application component interested in the progress of the synchronization.
266 * @param inProgress 'True' when the synchronization progress is not finished.
267 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
269 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
270 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
271 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
272 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
273 if (dirRemotePath
!= null
) {
274 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
276 if (result
!= null
) {
277 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
279 getContext().sendStickyBroadcast(i
);
285 * Notifies the user about a failed synchronization through the status notification bar
287 private void notifyFailedSynchronization() {
288 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
289 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
290 // TODO put something smart in the contentIntent below
291 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
292 notification
.setLatestEventInfo(getContext().getApplicationContext(),
293 getContext().getString(R
.string
.sync_fail_ticker
),
294 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
295 notification
.contentIntent
);
296 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);