Changes after CR
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.apache.jackrabbit.webdav.DavException;
28
29 import com.owncloud.android.R;
30 import com.owncloud.android.authentication.AuthenticatorActivity;
31 import com.owncloud.android.datamodel.FileDataStorageManager;
32 import com.owncloud.android.datamodel.OCFile;
33 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
34 import com.owncloud.android.operations.SynchronizeFolderOperation;
35 import com.owncloud.android.operations.UpdateOCVersionOperation;
36 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
37 import com.owncloud.android.lib.common.utils.Log_OC;
38 import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
39
40 import android.accounts.Account;
41 import android.accounts.AccountsException;
42 import android.app.NotificationManager;
43 import android.app.PendingIntent;
44 import android.content.AbstractThreadedSyncAdapter;
45 import android.content.ContentProviderClient;
46 import android.content.ContentResolver;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.content.SyncResult;
50 import android.os.Bundle;
51 import android.support.v4.app.NotificationCompat;
52
53 /**
54 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
55 * ownCloud files.
56 *
57 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
58 *
59 * @author Bartek Przybylski
60 * @author David A. Velasco
61 */
62 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
63
64 private final static String TAG = FileSyncAdapter.class.getSimpleName();
65
66 /** Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation */
67 private static final int MAX_FAILED_RESULTS = 3;
68
69
70 public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_START";
71 public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_END";
72 public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
73 //public static final String EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED = FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED";
74
75 public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() + ".EXTRA_ACCOUNT_NAME";
76 public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() + ".EXTRA_FOLDER_PATH";
77 public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
78
79
80 /** Time stamp for the current synchronization process, used to distinguish fresh data */
81 private long mCurrentSyncTime;
82
83 /** Flag made 'true' when a request to cancel the synchronization is received */
84 private boolean mCancellation;
85
86 /** When 'true' the process was requested by the user through the user interface; when 'false', it was requested automatically by the system */
87 private boolean mIsManualSync;
88
89 /** Counter for failed operations in the synchronization process */
90 private int mFailedResultsCounter;
91
92 /** Result of the last failed operation */
93 private RemoteOperationResult mLastFailedResult;
94
95 /** Counter of conflicts found between local and remote files */
96 private int mConflictsFound;
97
98 /** Counter of failed operations in synchronization of kept-in-sync files */
99 private int mFailsInFavouritesFound;
100
101 /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
102 private Map<String, String> mForgottenLocalFiles;
103
104 /** {@link SyncResult} instance to return to the system when the synchronization finish */
105 private SyncResult mSyncResult;
106
107 /** 'True' means that the server supports the share API */
108 private boolean mIsShareSupported;
109
110
111 /**
112 * Creates a {@link FileSyncAdapter}
113 *
114 * {@inheritDoc}
115 */
116 public FileSyncAdapter(Context context, boolean autoInitialize) {
117 super(context, autoInitialize);
118 }
119
120
121 /**
122 * Creates a {@link FileSyncAdapter}
123 *
124 * {@inheritDoc}
125 */
126 public FileSyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
127 super(context, autoInitialize, allowParallelSyncs);
128 }
129
130
131 /**
132 * {@inheritDoc}
133 */
134 @Override
135 public synchronized void onPerformSync(Account account, Bundle extras,
136 String authority, ContentProviderClient providerClient,
137 SyncResult syncResult) {
138
139 mCancellation = false;
140 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
141 mFailedResultsCounter = 0;
142 mLastFailedResult = null;
143 mConflictsFound = 0;
144 mFailsInFavouritesFound = 0;
145 mForgottenLocalFiles = new HashMap<String, String>();
146 mSyncResult = syncResult;
147 mSyncResult.fullSyncRequested = false;
148 mSyncResult.delayUntil = 60*60*24; // avoid too many automatic synchronizations
149
150 this.setAccount(account);
151 this.setContentProviderClient(providerClient);
152 this.setStorageManager(new FileDataStorageManager(account, providerClient));
153
154 try {
155 this.initClientForCurrentAccount();
156 } catch (IOException e) {
157 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
158 mSyncResult.tooManyRetries = true;
159 notifyFailedSynchronization();
160 return;
161 } catch (AccountsException e) {
162 /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
163 mSyncResult.tooManyRetries = true;
164 notifyFailedSynchronization();
165 return;
166 }
167
168 Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
169 sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start of the synchronization to the UI
170
171 try {
172 updateOCVersion();
173 mCurrentSyncTime = System.currentTimeMillis();
174 if (!mCancellation) {
175 synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
176
177 } else {
178 Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder because cancelation request");
179 }
180
181
182 } finally {
183 // it's important making this although very unexpected errors occur; that's the reason for the finally
184
185 if (mFailedResultsCounter > 0 && mIsManualSync) {
186 /// don't let the system synchronization manager retries MANUAL synchronizations
187 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
188 mSyncResult.tooManyRetries = true;
189
190 /// notify the user about the failure of MANUAL synchronization
191 notifyFailedSynchronization();
192 }
193 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
194 notifyFailsInFavourites();
195 }
196 if (mForgottenLocalFiles.size() > 0) {
197 notifyForgottenLocalFiles();
198 }
199 sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal the end to the UI
200 }
201
202 }
203
204 /**
205 * Called by system SyncManager when a synchronization is required to be cancelled.
206 *
207 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
208 * before a new folder is fetched. Data of the last folder synchronized will be still
209 * locally saved.
210 *
211 * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
212 * and {@link #synchronizeFolder(String, long)}.
213 */
214 @Override
215 public void onSyncCanceled() {
216 Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
217 mCancellation = true;
218 super.onSyncCanceled();
219 }
220
221
222 /**
223 * Updates the locally stored version value of the ownCloud server
224 */
225 private void updateOCVersion() {
226 UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
227 RemoteOperationResult result = update.execute(getClient());
228 if (!result.isSuccess()) {
229 mLastFailedResult = result;
230 } else {
231 mIsShareSupported = update.getOCVersion().isSharedSupported();
232 }
233 }
234
235
236 /**
237 * Synchronizes the list of files contained in a folder identified with its remote path.
238 *
239 * Fetches the list and properties of the files contained in the given folder, including their
240 * properties, and updates the local database with them.
241 *
242 * Enters in the child folders to synchronize their contents also, following a recursive
243 * depth first strategy.
244 *
245 * @param folder Folder to synchronize.
246 */
247 private void synchronizeFolder(OCFile folder) {
248
249 if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
250 return;
251
252 /*
253 OCFile folder,
254 long currentSyncTime,
255 boolean updateFolderProperties,
256 boolean syncFullAccount,
257 DataStorageManager dataStorageManager,
258 Account account,
259 Context context ) {
260 }
261 */
262 // folder synchronization
263 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( folder,
264 mCurrentSyncTime,
265 true,
266 mIsShareSupported,
267 getStorageManager(),
268 getAccount(),
269 getContext()
270 );
271 RemoteOperationResult result = synchFolderOp.execute(getClient());
272
273
274 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
275 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
276
277 // check the result of synchronizing the folder
278 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
279
280 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
281 mConflictsFound += synchFolderOp.getConflictsFound();
282 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
283 }
284 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
285 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
286 }
287 if (result.isSuccess()) {
288 // synchronize children folders
289 List<OCFile> children = synchFolderOp.getChildren();
290 fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
291 }
292
293 } else {
294 // in failures, the statistics for the global result are updated
295 if ( result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
296 result.isIdPRedirection()
297 ) {
298 mSyncResult.stats.numAuthExceptions++;
299
300 } else if (result.getException() instanceof DavException) {
301 mSyncResult.stats.numParseExceptions++;
302
303 } else if (result.getException() instanceof IOException) {
304 mSyncResult.stats.numIoExceptions++;
305 }
306 mFailedResultsCounter++;
307 mLastFailedResult = result;
308 }
309
310 }
311
312 /**
313 * Checks if a failed result should terminate the synchronization process immediately, according to
314 * OUR OWN POLICY
315 *
316 * @param failedResult Remote operation result to check.
317 * @return 'True' if the result should immediately finish the synchronization
318 */
319 private boolean isFinisher(RemoteOperationResult failedResult) {
320 if (failedResult != null) {
321 RemoteOperationResult.ResultCode code = failedResult.getCode();
322 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
323 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
324 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
325 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
326 }
327 return false;
328 }
329
330 /**
331 * Triggers the synchronization of any folder contained in the list of received files.
332 *
333 * @param files Files to recursively synchronize.
334 */
335 private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
336 int i;
337 OCFile newFile = null;
338 //String etag = null;
339 //boolean syncDown = false;
340 for (i=0; i < files.size() && !mCancellation; i++) {
341 newFile = files.get(i);
342 if (newFile.isFolder()) {
343 /*
344 etag = newFile.getEtag();
345 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
346 if(syncDown) { */
347 synchronizeFolder(newFile);
348 //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null);
349 //}
350 }
351 }
352
353 if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " due to cancelation request");
354 }
355
356
357 /**
358 * Sends a message to any application component interested in the progress of the synchronization.
359 *
360 * @param event Event in the process of synchronization to be notified.
361 * @param dirRemotePath Remote path of the folder target of the event occurred.
362 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
363 */
364 private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
365 Log_OC.d(TAG, "Send broadcast " + event);
366 Intent intent = new Intent(event);
367 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
368 if (dirRemotePath != null) {
369 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
370 }
371 if (result != null) {
372 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
373 }
374 getContext().sendStickyBroadcast(intent);
375 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
376 }
377
378
379
380 /**
381 * Notifies the user about a failed synchronization through the status notification bar
382 */
383 private void notifyFailedSynchronization() {
384 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
385 boolean needsToUpdateCredentials = (
386 mLastFailedResult != null && (
387 mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
388 mLastFailedResult.isIdPRedirection()
389 )
390 );
391 if (needsToUpdateCredentials) {
392 // let the user update credentials with one click
393 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
394 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
395 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
396 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
397 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
398 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
399 notificationBuilder
400 .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
401 .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
402 .setContentIntent(PendingIntent.getActivity(
403 getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT
404 ))
405 .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
406 } else {
407 notificationBuilder
408 .setTicker(i18n(R.string.sync_fail_ticker))
409 .setContentTitle(i18n(R.string.sync_fail_ticker))
410 .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
411 }
412
413 showNotification(R.string.sync_fail_ticker, notificationBuilder);
414 }
415
416
417 /**
418 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
419 *
420 * By now, we won't consider a failed synchronization.
421 */
422 private void notifyFailsInFavourites() {
423 if (mFailedResultsCounter > 0) {
424 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
425 notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
426
427 // TODO put something smart in the contentIntent below
428 notificationBuilder
429 .setContentIntent(PendingIntent.getActivity(
430 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
431 ))
432 .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
433 .setContentText(i18n(R.string.sync_fail_in_favourites_content, mFailedResultsCounter + mConflictsFound, mConflictsFound));
434
435 showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
436 } else {
437 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
438 notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
439
440 // TODO put something smart in the contentIntent below
441 notificationBuilder
442 .setContentIntent(PendingIntent.getActivity(
443 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
444 ))
445 .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
446 .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
447
448 showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
449 }
450 }
451
452 /**
453 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
454 * copying them inside the ownCloud local directory was not possible.
455 *
456 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
457 * synchronization problems if a local file is linked to more than one remote file.
458 *
459 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
460 */
461 private void notifyForgottenLocalFiles() {
462 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
463 notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
464
465 /// includes a pending intent in the notification showing a more detailed explanation
466 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
467 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
468 ArrayList<String> remotePaths = new ArrayList<String>();
469 ArrayList<String> localPaths = new ArrayList<String>();
470 remotePaths.addAll(mForgottenLocalFiles.keySet());
471 localPaths.addAll(mForgottenLocalFiles.values());
472 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
473 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
474 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
475
476 notificationBuilder
477 .setContentIntent(PendingIntent.getActivity(
478 getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
479 ))
480 .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
481 .setContentText(i18n(R.string.sync_foreign_files_forgotten_content, mForgottenLocalFiles.size(), i18n(R.string.app_name)));
482
483 showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
484 }
485
486 /**
487 * Creates a notification builder with some commonly used settings
488 *
489 * @return
490 */
491 private NotificationCompat.Builder createNotificationBuilder() {
492 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
493 notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
494 return notificationBuilder;
495 }
496
497 /**
498 * Builds and shows the notification
499 *
500 * @param id
501 * @param builder
502 */
503 private void showNotification(int id, NotificationCompat.Builder builder) {
504 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
505 .notify(id, builder.build());
506 }
507 /**
508 * Shorthand translation
509 *
510 * @param key
511 * @param args
512 * @return
513 */
514 private String i18n(int key, Object... args) {
515 return getContext().getString(key, args);
516 }
517 }