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 eu
.alefzero
.owncloud
.syncadapter
;
21 import java
.io
.IOException
;
22 import java
.util
.List
;
23 import java
.util
.Vector
;
25 import org
.apache
.jackrabbit
.webdav
.DavException
;
26 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
27 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
29 import android
.accounts
.Account
;
30 import android
.accounts
.AuthenticatorException
;
31 import android
.accounts
.OperationCanceledException
;
32 import android
.content
.ContentProviderClient
;
33 import android
.content
.Context
;
34 import android
.content
.Intent
;
35 import android
.content
.SyncResult
;
36 import android
.os
.Bundle
;
37 import android
.util
.Log
;
38 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
39 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
40 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
41 import eu
.alefzero
.webdav
.WebdavEntry
;
42 import eu
.alefzero
.webdav
.WebdavUtils
;
45 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
46 * platform ContactOperations provider.
48 * @author Bartek Przybylski
50 public class FileSyncAdapter
extends AbstractOwnCloudSyncAdapter
{
52 private final static String TAG
= "FileSyncAdapter";
54 /* Commented code for ugly performance tests
55 private final static int MAX_DELAYS = 100;
56 private static long[] mResponseDelays = new long[MAX_DELAYS];
57 private static long[] mSaveDelays = new long[MAX_DELAYS];
58 private int mDelaysIndex = 0;
59 private int mDelaysCount = 0;
62 private long mCurrentSyncTime
;
63 private boolean mCancellation
;
64 private Account mAccount
;
66 public FileSyncAdapter(Context context
, boolean autoInitialize
) {
67 super(context
, autoInitialize
);
71 public synchronized void onPerformSync(Account account
, Bundle extras
,
72 String authority
, ContentProviderClient provider
,
73 SyncResult syncResult
) {
75 mCancellation
= false
;
78 this.setAccount(mAccount
);
79 this.setContentProvider(provider
);
80 this.setStorageManager(new FileDataStorageManager(mAccount
,
81 getContentProvider()));
83 /* Commented code for ugly performance tests
89 Log
.d(TAG
, "syncing owncloud account " + mAccount
.name
);
91 sendStickyBroadcast(true
, null
); // message to signal the start to the UI
95 mCurrentSyncTime
= System
.currentTimeMillis();
96 query
= new PropFindMethod(getUri().toString() + "/");
97 getClient().executeMethod(query
);
98 MultiStatus resp
= null
;
99 resp
= query
.getResponseBodyAsMultiStatus();
101 if (resp
.getResponses().length
> 0) {
102 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], getUri().getPath());
103 OCFile file
= fillOCFile(we
);
105 getStorageManager().saveFile(file
);
106 if (!mCancellation
) {
107 fetchData(getUri().toString(), syncResult
, file
.getFileId());
110 } catch (OperationCanceledException e
) {
112 } catch (AuthenticatorException e
) {
113 syncResult
.stats
.numAuthExceptions
++;
115 } catch (IOException e
) {
116 syncResult
.stats
.numIoExceptions
++;
118 } catch (DavException e
) {
119 syncResult
.stats
.numIoExceptions
++;
121 } catch (Throwable t
) {
122 // TODO update syncResult
123 Log
.e(TAG
, "problem while synchronizing owncloud account " + account
.name
, t
);
127 /* Commented code for ugly performance tests
128 long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;
129 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
130 sum += mResponseDelays[i];
131 max = Math.max(max, mResponseDelays[i]);
132 min = Math.min(min, mResponseDelays[i]);
134 mean = sum / mDelaysCount;
135 Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
137 sum = 0; max = 0; min = Long.MAX_VALUE;
138 for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {
139 sum += mSaveDelays[i];
140 max = Math.max(max, mSaveDelays[i]);
141 min = Math.min(min, mSaveDelays[i]);
143 mean = sum / mDelaysCount;
144 Log.e(TAG, "SYNC STATS - save: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
145 Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);
148 sendStickyBroadcast(false
, null
);
151 private void fetchData(String uri
, SyncResult syncResult
, long parentId
) {
153 //Log.v(TAG, "syncing: fetching " + uri);
156 PropFindMethod query
= new PropFindMethod(uri
);
157 /* Commented code for ugly performance tests
158 long responseDelay = System.currentTimeMillis();
160 getClient().executeMethod(query
);
161 /* Commented code for ugly performance tests
162 responseDelay = System.currentTimeMillis() - responseDelay;
163 Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");
165 MultiStatus resp
= null
;
166 resp
= query
.getResponseBodyAsMultiStatus();
168 // insertion or update of files
169 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
170 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
171 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], getUri().getPath());
172 OCFile file
= fillOCFile(we
);
173 file
.setParentId(parentId
);
174 if (getStorageManager().getFileByPath(file
.getRemotePath()) != null
&&
175 getStorageManager().getFileByPath(file
.getRemotePath()).keepInSync() &&
176 file
.getModificationTimestamp() > getStorageManager().getFileByPath(file
.getRemotePath())
177 .getModificationTimestamp()) {
178 Intent intent
= new Intent(this.getContext(), FileDownloader
.class);
179 intent
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, getAccount());
180 intent
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, file
.getRemotePath());
181 intent
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, file
.getRemotePath());
182 intent
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, file
.getFileLength());
183 file
.setKeepInSync(true
);
184 getContext().startService(intent
);
186 if (getStorageManager().getFileByPath(file
.getRemotePath()) != null
)
187 file
.setKeepInSync(getStorageManager().getFileByPath(file
.getRemotePath()).keepInSync());
188 //getStorageManager().saveFile(file);
189 updatedFiles
.add(file
);
191 parentId
= file
.getFileId();
193 /* Commented code for ugly performance tests
194 long saveDelay = System.currentTimeMillis();
196 getStorageManager().saveFiles(updatedFiles
); // all "at once" ; trying to get a best performance in database update
197 /* Commented code for ugly performance tests
198 saveDelay = System.currentTimeMillis() - saveDelay;
199 Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");
202 // removal of obsolete files
203 Vector
<OCFile
> files
= getStorageManager().getDirectoryContent(
204 getStorageManager().getFileById(parentId
));
206 for (int i
=0; i
< files
.size(); ) {
208 if (file
.getLastSyncDate() != mCurrentSyncTime
&& file
.getLastSyncDate() != 0) {
209 getStorageManager().removeFile(file
);
216 // synchronized folder -> notice to UI
217 sendStickyBroadcast(true
, getStorageManager().getFileById(parentId
).getRemotePath());
220 for (int i
=0; i
< files
.size() && !mCancellation
; i
++) {
221 OCFile newFile
= files
.get(i
);
222 if (newFile
.getMimetype().equals("DIR")) {
223 fetchData(getUri().toString() + WebdavUtils
.encode(newFile
.getRemotePath()), syncResult
, newFile
.getFileId());
226 if (mCancellation
) Log
.d(TAG
, "Leaving " + uri
+ " because cancellation request");
228 /* Commented code for ugly performance tests
229 mResponseDelays[mDelaysIndex] = responseDelay;
230 mSaveDelays[mDelaysIndex] = saveDelay;
233 if (mDelaysIndex >= MAX_DELAYS)
239 } catch (OperationCanceledException e
) {
241 } catch (AuthenticatorException e
) {
242 syncResult
.stats
.numAuthExceptions
++;
244 } catch (IOException e
) {
245 syncResult
.stats
.numIoExceptions
++;
247 } catch (DavException e
) {
248 syncResult
.stats
.numIoExceptions
++;
250 } catch (Throwable t
) {
251 // TODO update syncResult
252 Log
.e(TAG
, "problem while synchronizing owncloud account " + mAccount
.name
, t
);
257 private OCFile
fillOCFile(WebdavEntry we
) {
258 OCFile file
= new OCFile(we
.decodedPath());
259 file
.setCreationTimestamp(we
.createTimestamp());
260 file
.setFileLength(we
.contentLength());
261 file
.setMimetype(we
.contentType());
262 file
.setModificationTimestamp(we
.modifiedTimesamp());
263 file
.setLastSyncDate(mCurrentSyncTime
);
268 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
) {
269 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
270 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
271 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, getAccount().name
);
272 if (dirRemotePath
!= null
) {
273 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
275 getContext().sendStickyBroadcast(i
);
279 * Called by system SyncManager when a synchronization is required to be cancelled.
281 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
282 * fetched will be still saved in the database. See onPerformSync implementation.
285 public void onSyncCanceled() {
286 Log
.d(TAG
, "Synchronization of " + mAccount
.name
+ " has been requested to cancell");
287 mCancellation
= true
;
288 super.onSyncCanceled();