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";
60 private long mCurrentSyncTime
;
61 private boolean mCancellation
;
62 private boolean mIsManualSync
;
63 private boolean mRightSync
;
65 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
66 super(context
, autoInitialize
);
70 public synchronized void onPerformSync(Account account
, Bundle extras
,
71 String authority
, ContentProviderClient provider
,
72 SyncResult syncResult
) {
74 mCancellation
= false
;
75 mIsManualSync
= extras
.getBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, false
);
78 this.setAccount(account
);
79 this.setContentProvider(provider
);
80 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
82 Log
.d(TAG
, "syncing owncloud account " + account
.name
);
84 sendStickyBroadcast(true
, null
); // message to signal the start to the UI
88 mCurrentSyncTime
= System
.currentTimeMillis();
90 fetchData(OCFile
.PATH_SEPARATOR
, syncResult
, DataStorageManager
.ROOT_PARENT_ID
);
93 Log
.d(TAG
, "Leaving synchronization before any remote request due to cancellation was requested");
97 // it's important making this although very unexpected errors occur; that's the reason for the finally
99 mRightSync
&= (syncResult
.stats
.numIoExceptions
== 0 && syncResult
.stats
.numAuthExceptions
== 0 && syncResult
.stats
.numParseExceptions
== 0);
100 if (!mRightSync
&& mIsManualSync
) {
101 /// don't let the system synchronization manager retries MANUAL synchronizations
102 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
103 syncResult
.tooManyRetries
= true
;
105 /// notify the user about the failure of MANUAL synchronization
106 notifyFailedSynchronization();
108 sendStickyBroadcast(false
, null
); // message to signal the end to the UI
116 * Called by system SyncManager when a synchronization is required to be cancelled.
118 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
119 * fetched will be still saved in the database. See onPerformSync implementation.
122 public void onSyncCanceled() {
123 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
124 mCancellation
= true
;
125 super.onSyncCanceled();
130 * Updates the locally stored version value of the ownCloud server
132 private void updateOCVersion() {
133 String statUrl
= getAccountManager().getUserData(getAccount(), AccountAuthenticator
.KEY_OC_BASE_URL
);
134 statUrl
+= AccountUtils
.STATUS_PATH
;
137 String result
= getClient().getResultAsString(statUrl
);
138 if (result
!= null
) {
140 JSONObject json
= new JSONObject(result
);
141 if (json
!= null
&& json
.getString("version") != null
) {
142 OwnCloudVersion ocver
= new OwnCloudVersion(json
.getString("version"));
143 if (ocver
.isVersionValid()) {
144 getAccountManager().setUserData(getAccount(), AccountAuthenticator
.KEY_OC_VERSION
, ocver
.toString());
145 Log
.d(TAG
, "Got new OC version " + ocver
.toString());
147 Log
.w(TAG
, "Invalid version number received from server: " + json
.getString("version"));
150 } catch (Throwable e
) {
151 Log
.w(TAG
, "Couldn't parse version response", e
);
154 Log
.w(TAG
, "Problem while getting ocversion from server");
156 } catch (Exception e
) {
157 Log
.e(TAG
, "Problem getting response from server", e
);
164 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
166 * @param remotePath Remote path to the folder to synchronize.
167 * @param parentId Database Id of the folder to synchronize.
168 * @param syncResult Object to update for communicate results to the system's synchronization manager.
170 private void fetchData(String remotePath
, SyncResult syncResult
, long parentId
) {
172 // get client object to connect to the remote ownCloud server
173 WebdavClient client
= null
;
175 client
= getClient();
176 } catch (IOException e
) {
177 syncResult
.stats
.numIoExceptions
++;
178 Log
.d(TAG
, "Could not get client object while trying to synchronize - impossible to continue");
182 // perform folder synchronization
183 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation( remotePath
,
190 RemoteOperationResult result
= synchFolderOp
.execute(client
);
193 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
194 sendStickyBroadcast(true
, remotePath
);
196 if (result
.isSuccess()) {
197 // synchronize children folders
198 List
<OCFile
> children
= synchFolderOp
.getChildren();
199 fetchChildren(children
, syncResult
); // beware of the 'hidden' recursion here!
202 if (result
.getCode() == RemoteOperationResult
.ResultCode
.UNAUTHORIZED
) {
203 syncResult
.stats
.numAuthExceptions
++;
205 } else if (result
.getException() instanceof DavException
) {
206 syncResult
.stats
.numParseExceptions
++;
208 } else if (result
.getException() instanceof IOException
) {
209 syncResult
.stats
.numIoExceptions
++;
211 } else if (result
.getException() != null
) {
212 // TODO maybe something smarter with syncResult
220 * Synchronize data of folders in the list of received files
222 * @param files Files to recursively fetch
223 * @param syncResult Updated object to provide results to the Synchronization Manager
225 private void fetchChildren(List
<OCFile
> files
, SyncResult syncResult
) {
227 for (i
=0; i
< files
.size() && !mCancellation
; i
++) {
228 OCFile newFile
= files
.get(i
);
229 if (newFile
.isDirectory()) {
230 fetchData(newFile
.getRemotePath(), syncResult
, newFile
.getFileId());
233 if (mCancellation
&& i
<files
.size()) Log
.d(TAG
, "Leaving synchronization before synchronizing " + files
.get(i
).getRemotePath() + " because cancelation request");
238 * Sends a message to any app component interested in the progress of the synchronization.
240 * @param inProgress 'True' when the synchronization progress is not finished.
241 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
243 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
/*, RemoteOperationResult result*/) {
244 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
245 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
246 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
247 if (dirRemotePath
!= null
) {
248 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
250 /*if (result != null) {
251 i.putExtra(FileSyncService.SYNC_RESULT, result);
253 getContext().sendStickyBroadcast(i
);
259 * Notifies the user about a failed synchronization through the status notification bar
261 private void notifyFailedSynchronization() {
262 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
263 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
264 // TODO put something smart in the contentIntent below
265 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), (int)System
.currentTimeMillis(), new Intent(), 0);
266 notification
.setLatestEventInfo(getContext().getApplicationContext(),
267 getContext().getString(R
.string
.sync_fail_ticker
),
268 String
.format(getContext().getString(R
.string
.sync_fail_content
), getAccount().name
),
269 notification
.contentIntent
);
270 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);