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
95 Log
.d(TAG
, "syncing owncloud account " + account
.name
);
97 sendStickyBroadcast(true
, null
); // message to signal the start to the UI
99 String uri
= getUri().toString();
100 PropFindMethod query
= null
;
102 mCurrentSyncTime
= System
.currentTimeMillis();
103 query
= new PropFindMethod(uri
+ "/");
104 int status
= getClient().executeMethod(query
);
105 if (status
!= HttpStatus
.SC_UNAUTHORIZED
) {
106 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
108 if (resp
.getResponses().length
> 0) {
109 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], getUri().getPath());
110 OCFile file
= fillOCFile(we
);
112 getStorageManager().saveFile(file
);
113 if (!mCancellation
) {
114 fetchData(uri
, syncResult
, file
.getFileId());
119 syncResult
.stats
.numAuthExceptions
++;
121 } catch (IOException e
) {
122 syncResult
.stats
.numIoExceptions
++;
123 logException(e
, uri
+ "/");
125 } catch (DavException e
) {
126 syncResult
.stats
.numParseExceptions
++;
127 logException(e
, uri
+ "/");
129 } catch (Exception e
) {
130 // TODO something smart with syncresult
131 logException(e
, uri
+ "/");
136 query
.releaseConnection(); // let the connection available for other methods
137 mRightSync
&= (syncResult
.stats
.numIoExceptions
== 0 && syncResult
.stats
.numAuthExceptions
== 0 && syncResult
.stats
.numParseExceptions
== 0);
138 if (!mRightSync
&& mIsManualSync
) {
139 /// don't let the system synchronization manager retries MANUAL synchronizations
140 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
141 syncResult
.tooManyRetries
= true
;
143 /// notify the user about the failure of MANUAL synchronization
144 Notification notification
= new Notification(R
.drawable
.icon
, getContext().getString(R
.string
.sync_fail_ticker
), System
.currentTimeMillis());
145 notification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
146 // TODO put something smart in the contentIntent below
147 notification
.contentIntent
= PendingIntent
.getActivity(getContext().getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
148 notification
.setLatestEventInfo(getContext().getApplicationContext(),
149 getContext().getString(R
.string
.sync_fail_ticker
),
150 String
.format(getContext().getString(R
.string
.sync_fail_content
), account
.name
),
151 notification
.contentIntent
);
152 ((NotificationManager
) getContext().getSystemService(Context
.NOTIFICATION_SERVICE
)).notify(R
.string
.sync_fail_ticker
, notification
);
154 sendStickyBroadcast(false
, null
); // message to signal the end to the UI
157 /* Commented code for ugly performance tests
158 long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;
159 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
160 sum += mResponseDelays[i];
161 max = Math.max(max, mResponseDelays[i]);
162 min = Math.min(min, mResponseDelays[i]);
164 mean = sum / mDelaysCount;
165 Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
167 sum = 0; max = 0; min = Long.MAX_VALUE;
168 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
169 sum += mSaveDelays[i];
170 max = Math.max(max, mSaveDelays[i]);
171 min = Math.min(min, mSaveDelays[i]);
173 mean = sum / mDelaysCount;
174 Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
175 Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);
180 private void fetchData(String uri
, SyncResult syncResult
, long parentId
) {
181 PropFindMethod query
= null
;
183 Log
.d(TAG
, "fetching " + uri
);
186 query
= new PropFindMethod(uri
);
187 /* Commented code for ugly performance tests
188 long responseDelay = System.currentTimeMillis();
190 int status
= getClient().executeMethod(query
);
191 /* Commented code for ugly performance tests
192 responseDelay = System.currentTimeMillis() - responseDelay;
193 Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");
195 if (status
!= HttpStatus
.SC_UNAUTHORIZED
) {
196 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
198 // insertion or update of files
199 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
200 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
201 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], getUri().getPath());
202 OCFile file
= fillOCFile(we
);
203 file
.setParentId(parentId
);
204 if (getStorageManager().getFileByPath(file
.getRemotePath()) != null
&&
205 getStorageManager().getFileByPath(file
.getRemotePath()).keepInSync() &&
206 file
.getModificationTimestamp() > getStorageManager().getFileByPath(file
.getRemotePath())
207 .getModificationTimestamp()) {
208 Intent intent
= new Intent(this.getContext(), FileDownloader
.class);
209 intent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, getAccount());
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
);