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