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