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
;
23 import java
.util
.Vector
;
25 import org
.apache
.http
.HttpStatus
;
26 import org
.apache
.jackrabbit
.webdav
.DavException
;
27 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
28 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
30 import com
.owncloud
.android
.R
;
31 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
32 import com
.owncloud
.android
.datamodel
.OCFile
;
33 import com
.owncloud
.android
.files
.services
.FileDownloader
;
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
;
46 import eu
.alefzero
.webdav
.WebdavEntry
;
47 import eu
.alefzero
.webdav
.WebdavUtils
;
50 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
51 * platform ContactOperations provider.
53 * @author Bartek Przybylski
55 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
57 private final static String TAG
= "FileSyncAdapter";
59 /* Commented code for ugly performance tests
60 private final static int MAX_DELAYS = 100;
61 private static long[] mResponseDelays = new long[MAX_DELAYS];
62 private static long[] mSaveDelays = new long[MAX_DELAYS];
63 private int mDelaysIndex = 0;
64 private int mDelaysCount = 0;
67 private long mCurrentSyncTime
;
68 private boolean mCancellation
;
69 private boolean mIsManualSync
;
70 private boolean mRightSync
;
72 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
73 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
);
85 this.setAccount(account
);
86 this.setContentProvider(provider
);
87 this.setStorageManager(new FileDataStorageManager(account
, getContentProvider()));
89 /* Commented code for ugly performance tests
94 Log
.d(TAG
, "syncing owncloud account " + account
.name
);
96 sendStickyBroadcast(true
, null
); // message to signal the start to the UI
98 String uri
= getUri().toString();
99 PropFindMethod query
= null
;
101 mCurrentSyncTime
= System
.currentTimeMillis();
102 query
= new PropFindMethod(uri
+ "/");
103 int status
= getClient().executeMethod(query
);
104 if (status
!= HttpStatus
.SC_UNAUTHORIZED
) {
105 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
107 if (resp
.getResponses().length
> 0) {
108 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], getUri().getPath());
109 OCFile file
= fillOCFile(we
);
111 getStorageManager().saveFile(file
);
112 if (!mCancellation
) {
113 fetchData(uri
, syncResult
, file
.getFileId());
118 syncResult
.stats
.numAuthExceptions
++;
120 } catch (IOException e
) {
121 syncResult
.stats
.numIoExceptions
++;
122 logException(e
, uri
+ "/");
124 } catch (DavException e
) {
125 syncResult
.stats
.numParseExceptions
++;
126 logException(e
, uri
+ "/");
128 } catch (Exception e
) {
129 // TODO something smart with syncresult
130 logException(e
, uri
+ "/");
135 query
.releaseConnection(); // let the connection available for other methods
136 mRightSync
&= (syncResult
.stats
.numIoExceptions
== 0 && syncResult
.stats
.numAuthExceptions
== 0 && syncResult
.stats
.numParseExceptions
== 0);
137 if (!mRightSync
&& mIsManualSync
) {
138 /// don't let the system synchronization manager retries MANUAL synchronizations
139 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
140 syncResult
.tooManyRetries
= true
;
142 /// notify the user about the failure of MANUAL synchronization
143 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
144 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
145 // TODO put something smart in the contentIntent below
146 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
147 notification
.setLatestEventInfo(getContext().getApplicationContext(),
148 getContext().getString(R
.string
.sync_fail_ticker
),
149 String
.format(getContext().getString(R
.string
.sync_fail_content
), account
.name
),
150 notification
.contentIntent
);
151 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
153 sendStickyBroadcast(false
, null
); // message to signal the end to the UI
156 /* Commented code for ugly performance tests
157 long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;
158 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
159 sum += mResponseDelays[i];
160 max = Math.max(max, mResponseDelays[i]);
161 min = Math.min(min, mResponseDelays[i]);
163 mean = sum / mDelaysCount;
164 Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
166 sum = 0; max = 0; min = Long.MAX_VALUE;
167 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
168 sum += mSaveDelays[i];
169 max = Math.max(max, mSaveDelays[i]);
170 min = Math.min(min, mSaveDelays[i]);
172 mean = sum / mDelaysCount;
173 Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
174 Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);
179 private void fetchData(String uri
, SyncResult syncResult
, long parentId
) {
180 PropFindMethod query
= null
;
182 Log
.d(TAG
, "fetching " + uri
);
185 query
= new PropFindMethod(uri
);
186 /* Commented code for ugly performance tests
187 long responseDelay = System.currentTimeMillis();
189 int status
= getClient().executeMethod(query
);
190 /* Commented code for ugly performance tests
191 responseDelay = System.currentTimeMillis() - responseDelay;
192 Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");
194 if (status
!= HttpStatus
.SC_UNAUTHORIZED
) {
195 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
197 // insertion or update of files
198 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
199 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
200 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], getUri().getPath());
201 OCFile file
= fillOCFile(we
);
202 file
.setParentId(parentId
);
203 if (getStorageManager().getFileByPath(file
.getRemotePath()) != null
&&
204 getStorageManager().getFileByPath(file
.getRemotePath()).keepInSync() &&
205 file
.getModificationTimestamp() > getStorageManager().getFileByPath(file
.getRemotePath())
206 .getModificationTimestamp()) {
207 Intent intent
= new Intent(this.getContext(), FileDownloader
.class);
208 intent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, getAccount());
209 intent
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
210 /*intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath());
211 intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath());
212 intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength());*/
213 file
.setKeepInSync(true
);
214 getContext().startService(intent
);
216 if (getStorageManager().getFileByPath(file
.getRemotePath()) != null
)
217 file
.setKeepInSync(getStorageManager().getFileByPath(file
.getRemotePath()).keepInSync());
219 // Log.v(TAG, "adding file: " + file);
220 updatedFiles
.add(file
);
222 parentId
= file
.getFileId();
224 /* Commented code for ugly performance tests
225 long saveDelay = System.currentTimeMillis();
227 getStorageManager().saveFiles(updatedFiles
); // all "at once" ; trying to get a best performance in database update
228 /* Commented code for ugly performance tests
229 saveDelay = System.currentTimeMillis() - saveDelay;
230 Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");
233 // removal of obsolete files
234 Vector
<OCFile
> files
= getStorageManager().getDirectoryContent(
235 getStorageManager().getFileById(parentId
));
237 String currentSavePath
= FileDownloader
.getSavePath(getAccount().name
);
238 for (int i
=0; i
< files
.size(); ) {
240 if (file
.getLastSyncDate() != mCurrentSyncTime
) {
241 Log
.v(TAG
, "removing file: " + file
);
242 getStorageManager().removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
250 for (int i
=0; i
< files
.size() && !mCancellation
; i
++) {
251 OCFile newFile
= files
.get(i
);
252 if (newFile
.getMimetype().equals("DIR")) {
253 fetchData(getUri().toString() + WebdavUtils
.encodePath(newFile
.getRemotePath()), syncResult
, newFile
.getFileId());
256 if (mCancellation
) Log
.d(TAG
, "Leaving " + uri
+ " because cancelation request");
258 /* Commented code for ugly performance tests
259 mResponseDelays[mDelaysIndex] = responseDelay;
260 mSaveDelays[mDelaysIndex] = saveDelay;
263 if (mDelaysIndex >= MAX_DELAYS)
268 syncResult
.stats
.numAuthExceptions
++;
270 } catch (IOException e
) {
271 syncResult
.stats
.numIoExceptions
++;
272 logException(e
, uri
);
274 } catch (DavException e
) {
275 syncResult
.stats
.numParseExceptions
++;
276 logException(e
, uri
);
278 } catch (Exception e
) {
279 // TODO something smart with syncresult
281 logException(e
, uri
);
285 query
.releaseConnection(); // let the connection available for other methods
287 // synchronized folder -> notice to UI
288 sendStickyBroadcast(true
, getStorageManager().getFileById(parentId
).getRemotePath());
292 private OCFile
fillOCFile(WebdavEntry we
) {
293 OCFile file
= new OCFile(we
.decodedPath());
294 file
.setCreationTimestamp(we
.createTimestamp());
295 file
.setFileLength(we
.contentLength());
296 file
.setMimetype(we
.contentType());
297 file
.setModificationTimestamp(we
.modifiedTimesamp());
298 file
.setLastSyncDate(mCurrentSyncTime
);
303 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
) {
304 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
305 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
306 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
307 if (dirRemotePath
!= null
) {
308 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
310 getContext().sendStickyBroadcast(i
);
314 * Called by system SyncManager when a synchronization is required to be cancelled.
316 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
317 * fetched will be still saved in the database. See onPerformSync implementation.
320 public void onSyncCanceled() {
321 Log
.d(TAG
, "Synchronization of " + getAccount().name
+ " has been requested to cancel");
322 mCancellation
= true
;
323 super.onSyncCanceled();
328 * Logs an exception triggered in a synchronization request.
330 * @param e Caught exception.
331 * @param uri Uri to the remote directory that was fetched when the synchronization failed
333 private void logException(Exception e
, String uri
) {
334 if (e
instanceof IOException
) {
335 Log
.e(TAG
, "Unrecovered transport exception while synchronizing " + uri
+ " at " + getAccount().name
, e
);
337 } else if (e
instanceof DavException
) {
338 Log
.e(TAG
, "Unexpected WebDAV exception while synchronizing " + uri
+ " at " + getAccount().name
, e
);
341 Log
.e(TAG
, "Unexpected exception while synchronizing " + uri
+ " at " + getAccount().name
, e
);