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