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