Add author's line in license
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
1 /* ownCloud Android client application
2 *
3 * @author Bartek Przybylski
4 * @author David A. Velasco
5 * Copyright (C) 2011 Bartek Przybylski
6 * Copyright (C) 2012-2013 ownCloud Inc.
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22 package com.owncloud.android.syncadapter;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.apache.jackrabbit.webdav.DavException;
31
32 import com.owncloud.android.R;
33 import com.owncloud.android.authentication.AuthenticatorActivity;
34 import com.owncloud.android.datamodel.FileDataStorageManager;
35 import com.owncloud.android.datamodel.OCFile;
36 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
37 import com.owncloud.android.operations.RefreshFolderOperation;
38 import com.owncloud.android.operations.UpdateOCVersionOperation;
39 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
40 import com.owncloud.android.lib.common.utils.Log_OC;
41 import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
42
43 import android.accounts.Account;
44 import android.accounts.AccountsException;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.content.AbstractThreadedSyncAdapter;
48 import android.content.ContentProviderClient;
49 import android.content.ContentResolver;
50 import android.content.Context;
51 import android.content.Intent;
52 import android.content.SyncResult;
53 import android.os.Bundle;
54 import android.support.v4.app.NotificationCompat;
55
56 /**
57 * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
58 * ownCloud files.
59 *
60 * Performs a full synchronization of the account recieved in {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}.
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 RefreshFolderOperation synchFolderOp = new RefreshFolderOperation( folder,
264 mCurrentSyncTime,
265 true,
266 mIsShareSupported,
267 false,
268 getStorageManager(),
269 getAccount(),
270 getContext()
271 );
272 RemoteOperationResult result = synchFolderOp.execute(getClient());
273
274
275 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
276 sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
277
278 // check the result of synchronizing the folder
279 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
280
281 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
282 mConflictsFound += synchFolderOp.getConflictsFound();
283 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
284 }
285 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
286 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
287 }
288 if (result.isSuccess()) {
289 // synchronize children folders
290 List<OCFile> children = synchFolderOp.getChildren();
291 fetchChildren(folder, children, synchFolderOp.getRemoteFolderChanged()); // beware of the 'hidden' recursion here!
292 }
293
294 } else {
295 // in failures, the statistics for the global result are updated
296 if ( result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
297 result.isIdPRedirection()
298 ) {
299 mSyncResult.stats.numAuthExceptions++;
300
301 } else if (result.getException() instanceof DavException) {
302 mSyncResult.stats.numParseExceptions++;
303
304 } else if (result.getException() instanceof IOException) {
305 mSyncResult.stats.numIoExceptions++;
306 }
307 mFailedResultsCounter++;
308 mLastFailedResult = result;
309 }
310
311 }
312
313 /**
314 * Checks if a failed result should terminate the synchronization process immediately, according to
315 * OUR OWN POLICY
316 *
317 * @param failedResult Remote operation result to check.
318 * @return 'True' if the result should immediately finish the synchronization
319 */
320 private boolean isFinisher(RemoteOperationResult failedResult) {
321 if (failedResult != null) {
322 RemoteOperationResult.ResultCode code = failedResult.getCode();
323 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
324 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
325 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
326 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
327 }
328 return false;
329 }
330
331 /**
332 * Triggers the synchronization of any folder contained in the list of received files.
333 *
334 * @param files Files to recursively synchronize.
335 */
336 private void fetchChildren(OCFile parent, List<OCFile> files, boolean parentEtagChanged) {
337 int i;
338 OCFile newFile = null;
339 //String etag = null;
340 //boolean syncDown = false;
341 for (i=0; i < files.size() && !mCancellation; i++) {
342 newFile = files.get(i);
343 if (newFile.isFolder()) {
344 /*
345 etag = newFile.getEtag();
346 syncDown = (parentEtagChanged || etag == null || etag.length() == 0);
347 if(syncDown) { */
348 synchronizeFolder(newFile);
349 //sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED, parent.getRemotePath(), null);
350 //}
351 }
352 }
353
354 if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " due to cancelation request");
355 }
356
357
358 /**
359 * Sends a message to any application component interested in the progress of the synchronization.
360 *
361 * @param event Event in the process of synchronization to be notified.
362 * @param dirRemotePath Remote path of the folder target of the event occurred.
363 * @param result Result of an individual {@ SynchronizeFolderOperation}, if completed; may be null.
364 */
365 private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
366 Log_OC.d(TAG, "Send broadcast " + event);
367 Intent intent = new Intent(event);
368 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
369 if (dirRemotePath != null) {
370 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
371 }
372 if (result != null) {
373 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
374 }
375 getContext().sendStickyBroadcast(intent);
376 //LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
377 }
378
379
380
381 /**
382 * Notifies the user about a failed synchronization through the status notification bar
383 */
384 private void notifyFailedSynchronization() {
385 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
386 boolean needsToUpdateCredentials = (
387 mLastFailedResult != null && (
388 mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
389 mLastFailedResult.isIdPRedirection()
390 )
391 );
392 if (needsToUpdateCredentials) {
393 // let the user update credentials with one click
394 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
395 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
396 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
397 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
398 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
399 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
400 notificationBuilder
401 .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
402 .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
403 .setContentIntent(PendingIntent.getActivity(
404 getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT
405 ))
406 .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
407 } else {
408 notificationBuilder
409 .setTicker(i18n(R.string.sync_fail_ticker))
410 .setContentTitle(i18n(R.string.sync_fail_ticker))
411 .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
412 }
413
414 showNotification(R.string.sync_fail_ticker, notificationBuilder);
415 }
416
417
418 /**
419 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
420 *
421 * By now, we won't consider a failed synchronization.
422 */
423 private void notifyFailsInFavourites() {
424 if (mFailedResultsCounter > 0) {
425 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
426 notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
427
428 // TODO put something smart in the contentIntent below
429 notificationBuilder
430 .setContentIntent(PendingIntent.getActivity(
431 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
432 ))
433 .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
434 .setContentText(i18n(R.string.sync_fail_in_favourites_content, mFailedResultsCounter + mConflictsFound, mConflictsFound));
435
436 showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
437 } else {
438 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
439 notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
440
441 // TODO put something smart in the contentIntent below
442 notificationBuilder
443 .setContentIntent(PendingIntent.getActivity(
444 getContext(), (int) System.currentTimeMillis(), new Intent(), 0
445 ))
446 .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
447 .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
448
449 showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
450 }
451 }
452
453 /**
454 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
455 * copying them inside the ownCloud local directory was not possible.
456 *
457 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
458 * synchronization problems if a local file is linked to more than one remote file.
459 *
460 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
461 */
462 private void notifyForgottenLocalFiles() {
463 NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
464 notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
465
466 /// includes a pending intent in the notification showing a more detailed explanation
467 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
468 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
469 ArrayList<String> remotePaths = new ArrayList<String>();
470 ArrayList<String> localPaths = new ArrayList<String>();
471 remotePaths.addAll(mForgottenLocalFiles.keySet());
472 localPaths.addAll(mForgottenLocalFiles.values());
473 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
474 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
475 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
476
477 notificationBuilder
478 .setContentIntent(PendingIntent.getActivity(
479 getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
480 ))
481 .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
482 .setContentText(i18n(R.string.sync_foreign_files_forgotten_content, mForgottenLocalFiles.size(), i18n(R.string.app_name)));
483
484 showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
485 }
486
487 /**
488 * Creates a notification builder with some commonly used settings
489 *
490 * @return
491 */
492 private NotificationCompat.Builder createNotificationBuilder() {
493 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
494 notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
495 return notificationBuilder;
496 }
497
498 /**
499 * Builds and shows the notification
500 *
501 * @param id
502 * @param builder
503 */
504 private void showNotification(int id, NotificationCompat.Builder builder) {
505 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE))
506 .notify(id, builder.build());
507 }
508 /**
509 * Shorthand translation
510 *
511 * @param key
512 * @param args
513 * @return
514 */
515 private String i18n(int key, Object... args) {
516 return getContext().getString(key, args);
517 }
518 }