Fixed crash when the device is turned while the warning dialog about server certifica...
[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_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);
215 }
216 if (getStorageManager().getFileByPath(file.getRemotePath()) != null)
217 file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());
218
219 // Log.v(TAG, "adding file: " + file);
220 updatedFiles.add(file);
221 if (parentId == 0)
222 parentId = file.getFileId();
223 }
224 /* Commented code for ugly performance tests
225 long saveDelay = System.currentTimeMillis();
226 */
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");
231 */
232
233 // removal of obsolete files
234 Vector<OCFile> files = getStorageManager().getDirectoryContent(
235 getStorageManager().getFileById(parentId));
236 OCFile file;
237 String currentSavePath = FileDownloader.getSavePath(getAccount().name);
238 for (int i=0; i < files.size(); ) {
239 file = files.get(i);
240 if (file.getLastSyncDate() != mCurrentSyncTime) {
241 Log.v(TAG, "removing file: " + file);
242 getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
243 files.remove(i);
244 } else {
245 i++;
246 }
247 }
248
249 // recursive fetch
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());
254 }
255 }
256 if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");
257
258 /* Commented code for ugly performance tests
259 mResponseDelays[mDelaysIndex] = responseDelay;
260 mSaveDelays[mDelaysIndex] = saveDelay;
261 mDelaysCount++;
262 mDelaysIndex++;
263 if (mDelaysIndex >= MAX_DELAYS)
264 mDelaysIndex = 0;
265 */
266
267 } else {
268 syncResult.stats.numAuthExceptions++;
269 }
270 } catch (IOException e) {
271 syncResult.stats.numIoExceptions++;
272 logException(e, uri);
273
274 } catch (DavException e) {
275 syncResult.stats.numParseExceptions++;
276 logException(e, uri);
277
278 } catch (Exception e) {
279 // TODO something smart with syncresult
280 mRightSync = false;
281 logException(e, uri);
282
283 } finally {
284 if (query != null)
285 query.releaseConnection(); // let the connection available for other methods
286
287 // synchronized folder -> notice to UI
288 sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());
289 }
290 }
291
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);
299 return file;
300 }
301
302
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);
309 }
310 getContext().sendStickyBroadcast(i);
311 }
312
313 /**
314 * Called by system SyncManager when a synchronization is required to be cancelled.
315 *
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.
318 */
319 @Override
320 public void onSyncCanceled() {
321 Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
322 mCancellation = true;
323 super.onSyncCanceled();
324 }
325
326
327 /**
328 * Logs an exception triggered in a synchronization request.
329 *
330 * @param e Caught exception.
331 * @param uri Uri to the remote directory that was fetched when the synchronization failed
332 */
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);
336
337 } else if (e instanceof DavException) {
338 Log.e(TAG, "Unexpected WebDAV exception while synchronizing " + uri + " at " + getAccount().name, e);
339
340 } else {
341 Log.e(TAG, "Unexpected exception while synchronizing " + uri + " at " + getAccount().name, e);
342 }
343 }
344
345
346 }