Show the details of a file when the status notification of a download in progress...
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18
19 package com.owncloud.android.syncadapter;
20
21 import java.io.IOException;
22 import java.util.List;
23 import java.util.Vector;
24
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;
29
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;
34
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;
48
49 /**
50 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
51 * platform ContactOperations provider.
52 *
53 * @author Bartek Przybylski
54 */
55 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
56
57 private final static String TAG = "FileSyncAdapter";
58
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;
65 */
66
67 private long mCurrentSyncTime;
68 private boolean mCancellation;
69 private boolean mIsManualSync;
70 private boolean mRightSync;
71
72 public FileSyncAdapter(Context context, boolean autoInitialize) {
73 super(context, autoInitialize);
74 }
75
76 @Override
77 public synchronized void onPerformSync(Account account, Bundle extras,
78 String authority, ContentProviderClient provider,
79 SyncResult syncResult) {
80
81 mCancellation = false;
82 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
83 mRightSync = true;
84
85 this.setAccount(account);
86 this.setContentProvider(provider);
87 this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
88
89 /* Commented code for ugly performance tests
90 mDelaysIndex = 0;
91 mDelaysCount = 0;
92 */
93
94
95 Log.d(TAG, "syncing owncloud account " + account.name);
96
97 sendStickyBroadcast(true, null); // message to signal the start to the UI
98
99 String uri = getUri().toString();
100 PropFindMethod query = null;
101 try {
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();
107
108 if (resp.getResponses().length > 0) {
109 WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());
110 OCFile file = fillOCFile(we);
111 file.setParentId(0);
112 getStorageManager().saveFile(file);
113 if (!mCancellation) {
114 fetchData(uri, syncResult, file.getFileId());
115 }
116 }
117
118 } else {
119 syncResult.stats.numAuthExceptions++;
120 }
121 } catch (IOException e) {
122 syncResult.stats.numIoExceptions++;
123 logException(e, uri + "/");
124
125 } catch (DavException e) {
126 syncResult.stats.numParseExceptions++;
127 logException(e, uri + "/");
128
129 } catch (Exception e) {
130 // TODO something smart with syncresult
131 logException(e, uri + "/");
132 mRightSync = false;
133
134 } finally {
135 if (query != null)
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;
142
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);
153 }
154 sendStickyBroadcast(false, null); // message to signal the end to the UI
155 }
156
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]);
163 }
164 mean = sum / mDelaysCount;
165 Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);
166
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]);
172 }
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);
176 */
177
178 }
179
180 private void fetchData(String uri, SyncResult syncResult, long parentId) {
181 PropFindMethod query = null;
182 try {
183 Log.d(TAG, "fetching " + uri);
184
185 // remote request
186 query = new PropFindMethod(uri);
187 /* Commented code for ugly performance tests
188 long responseDelay = System.currentTimeMillis();
189 */
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");
194 */
195 if (status != HttpStatus.SC_UNAUTHORIZED) {
196 MultiStatus resp = query.getResponseBodyAsMultiStatus();
197
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, file);
211 /*intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath());
212 intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath());
213 intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength());*/
214 file.setKeepInSync(true);
215 getContext().startService(intent);
216 }
217 if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
218 file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
219
220 // Log.v(TAG, "adding file: " + file);
221 updatedFiles.add(file);
222 if (parentId == 0)
223 parentId = file.getFileId();
224 }
225 /* Commented code for ugly performance tests
226 long saveDelay = System.currentTimeMillis();
227 */
228 getStorageManager().saveFiles(updatedFiles); // all "at once" ; trying to get a best performance in database update
229 /* Commented code for ugly performance tests
230 saveDelay = System.currentTimeMillis() - saveDelay;
231 Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");
232 */
233
234 // removal of obsolete files
235 Vector<OCFile> files = getStorageManager().getDirectoryContent(
236 getStorageManager().getFileById(parentId));
237 OCFile file;
238 String currentSavePath = FileDownloader.getSavePath(getAccount().name);
239 for (int i=0; i < files.size(); ) {
240 file = files.get(i);
241 if (file.getLastSyncDate() != mCurrentSyncTime) {
242 Log.v(TAG, "removing file: " + file);
243 getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
244 files.remove(i);
245 } else {
246 i++;
247 }
248 }
249
250 // recursive fetch
251 for (int i=0; i < files.size() && !mCancellation; i++) {
252 OCFile newFile = files.get(i);
253 if (newFile.getMimetype().equals("DIR")) {
254 fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());
255 }
256 }
257 if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");
258
259 /* Commented code for ugly performance tests
260 mResponseDelays[mDelaysIndex] = responseDelay;
261 mSaveDelays[mDelaysIndex] = saveDelay;
262 mDelaysCount++;
263 mDelaysIndex++;
264 if (mDelaysIndex >= MAX_DELAYS)
265 mDelaysIndex = 0;
266 */
267
268 } else {
269 syncResult.stats.numAuthExceptions++;
270 }
271 } catch (IOException e) {
272 syncResult.stats.numIoExceptions++;
273 logException(e, uri);
274
275 } catch (DavException e) {
276 syncResult.stats.numParseExceptions++;
277 logException(e, uri);
278
279 } catch (Exception e) {
280 // TODO something smart with syncresult
281 mRightSync = false;
282 logException(e, uri);
283
284 } finally {
285 if (query != null)
286 query.releaseConnection(); // let the connection available for other methods
287
288 // synchronized folder -> notice to UI
289 sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());
290 }
291 }
292
293 private OCFile fillOCFile(WebdavEntry we) {
294 OCFile file = new OCFile(we.decodedPath());
295 file.setCreationTimestamp(we.createTimestamp());
296 file.setFileLength(we.contentLength());
297 file.setMimetype(we.contentType());
298 file.setModificationTimestamp(we.modifiedTimesamp());
299 file.setLastSyncDate(mCurrentSyncTime);
300 return file;
301 }
302
303
304 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {
305 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
306 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
307 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
308 if (dirRemotePath != null) {
309 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
310 }
311 getContext().sendStickyBroadcast(i);
312 }
313
314 /**
315 * Called by system SyncManager when a synchronization is required to be cancelled.
316 *
317 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
318 * fetched will be still saved in the database. See onPerformSync implementation.
319 */
320 @Override
321 public void onSyncCanceled() {
322 Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
323 mCancellation = true;
324 super.onSyncCanceled();
325 }
326
327
328 /**
329 * Logs an exception triggered in a synchronization request.
330 *
331 * @param e Caught exception.
332 * @param uri Uri to the remote directory that was fetched when the synchronization failed
333 */
334 private void logException(Exception e, String uri) {
335 if (e instanceof IOException) {
336 Log.e(TAG, "Unrecovered transport exception while synchronizing " + uri + " at " + getAccount().name, e);
337
338 } else if (e instanceof DavException) {
339 Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);
340
341 } else {
342 Log.e(TAG, "Unexpected exception while synchronizing " + uri + " at " + getAccount().name, e);
343 }
344 }
345
346
347 }