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