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