Redirect app to login screen when operations in file details view fail due to bad...
[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.net.UnknownHostException;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.apache.jackrabbit.webdav.DavException;
29
30 import com.owncloud.android.R;
31 import com.owncloud.android.datamodel.DataStorageManager;
32 import com.owncloud.android.datamodel.FileDataStorageManager;
33 import com.owncloud.android.datamodel.OCFile;
34 import com.owncloud.android.operations.RemoteOperationResult;
35 import com.owncloud.android.operations.SynchronizeFolderOperation;
36 import com.owncloud.android.operations.UpdateOCVersionOperation;
37 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
38 import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
39 import android.accounts.Account;
40 import android.accounts.AccountsException;
41 import android.accounts.AuthenticatorException;
42 import android.accounts.OperationCanceledException;
43 import android.app.Notification;
44 import android.app.NotificationManager;
45 import android.app.PendingIntent;
46 import android.content.ContentProviderClient;
47 import android.content.ContentResolver;
48 import android.content.Context;
49 import android.content.Intent;
50 import android.content.SyncResult;
51 import android.os.Bundle;
52 import android.util.Log;
53
54 /**
55 * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
56 * platform ContactOperations provider.
57 *
58 * @author Bartek Przybylski
59 */
60 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
61
62 private final static String TAG = "FileSyncAdapter";
63
64 /**
65 * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation
66 */
67 private static final int MAX_FAILED_RESULTS = 3;
68
69 private long mCurrentSyncTime;
70 private boolean mCancellation;
71 private boolean mIsManualSync;
72 private int mFailedResultsCounter;
73 private RemoteOperationResult mLastFailedResult;
74 private SyncResult mSyncResult;
75 private int mConflictsFound;
76 private int mFailsInFavouritesFound;
77 private Map<String, String> mForgottenLocalFiles;
78
79
80 public FileSyncAdapter(Context context, boolean autoInitialize) {
81 super(context, autoInitialize);
82 }
83
84 /**
85 * {@inheritDoc}
86 */
87 @Override
88 public synchronized void onPerformSync(Account account, Bundle extras,
89 String authority, ContentProviderClient provider,
90 SyncResult syncResult) {
91
92 mCancellation = false;
93 mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
94 mFailedResultsCounter = 0;
95 mLastFailedResult = null;
96 mConflictsFound = 0;
97 mFailsInFavouritesFound = 0;
98 mForgottenLocalFiles = new HashMap<String, String>();
99 mSyncResult = syncResult;
100 mSyncResult.fullSyncRequested = false;
101 mSyncResult.delayUntil = 60*60*24; // sync after 24h
102
103 this.setAccount(account);
104 this.setContentProvider(provider);
105 this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));
106 try {
107 this.initClientForCurrentAccount();
108 } catch (IOException e) {
109 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
110 mSyncResult.tooManyRetries = true;
111 notifyFailedSynchronization();
112 return;
113 } catch (AccountsException e) {
114 /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again
115 mSyncResult.tooManyRetries = true;
116 notifyFailedSynchronization();
117 return;
118 }
119
120 Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
121 sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
122
123 try {
124 updateOCVersion();
125 mCurrentSyncTime = System.currentTimeMillis();
126 if (!mCancellation) {
127 fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);
128
129 } else {
130 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
131 }
132
133
134 } finally {
135 // it's important making this although very unexpected errors occur; that's the reason for the finally
136
137 if (mFailedResultsCounter > 0 && mIsManualSync) {
138 /// don't let the system synchronization manager retries MANUAL synchronizations
139 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
140 mSyncResult.tooManyRetries = true;
141
142 /// notify the user about the failure of MANUAL synchronization
143 notifyFailedSynchronization();
144
145 }
146 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
147 notifyFailsInFavourites();
148 }
149 if (mForgottenLocalFiles.size() > 0) {
150 notifyForgottenLocalFiles();
151
152 }
153 sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
154 }
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.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 /**
187 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
188 *
189 * @param remotePath Remote path to the folder to synchronize.
190 * @param parentId Database Id of the folder to synchronize.
191 */
192 private void fetchData(String remotePath, long parentId) {
193
194 if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
195 return;
196
197 // perform folder synchronization
198 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
199 mCurrentSyncTime,
200 parentId,
201 getStorageManager(),
202 getAccount(),
203 getContext()
204 );
205 RemoteOperationResult result = synchFolderOp.execute(getClient());
206
207
208 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
209 sendStickyBroadcast(true, remotePath, null);
210
211 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
212
213 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
214 mConflictsFound += synchFolderOp.getConflictsFound();
215 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
216 }
217 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
218 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
219 }
220 // synchronize children folders
221 List<OCFile> children = synchFolderOp.getChildren();
222 fetchChildren(children); // beware of the 'hidden' recursion here!
223
224 } else {
225 if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
226 mSyncResult.stats.numAuthExceptions++;
227
228 } else if (result.getException() instanceof DavException) {
229 mSyncResult.stats.numParseExceptions++;
230
231 } else if (result.getException() instanceof IOException) {
232 mSyncResult.stats.numIoExceptions++;
233 }
234 mFailedResultsCounter++;
235 mLastFailedResult = result;
236 }
237
238 }
239
240 /**
241 * Checks if a failed result should terminate the synchronization process immediately, according to
242 * OUR OWN POLICY
243 *
244 * @param failedResult Remote operation result to check.
245 * @return 'True' if the result should immediately finish the synchronization
246 */
247 private boolean isFinisher(RemoteOperationResult failedResult) {
248 if (failedResult != null) {
249 RemoteOperationResult.ResultCode code = failedResult.getCode();
250 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
251 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
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 // TODO put something smart in the contentIntent below
303 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
304 notification.setLatestEventInfo(getContext().getApplicationContext(),
305 getContext().getString(R.string.sync_fail_ticker),
306 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
307 notification.contentIntent);
308 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
309 }
310
311
312 /**
313 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
314 *
315 * By now, we won't consider a failed synchronization.
316 */
317 private void notifyFailsInFavourites() {
318 if (mFailedResultsCounter > 0) {
319 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
320 notification.flags |= Notification.FLAG_AUTO_CANCEL;
321 // TODO put something smart in the contentIntent below
322 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
323 notification.setLatestEventInfo(getContext().getApplicationContext(),
324 getContext().getString(R.string.sync_fail_in_favourites_ticker),
325 String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
326 notification.contentIntent);
327 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
328
329 } else {
330 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
331 notification.flags |= Notification.FLAG_AUTO_CANCEL;
332 // TODO put something smart in the contentIntent below
333 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
334 notification.setLatestEventInfo(getContext().getApplicationContext(),
335 getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
336 String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
337 notification.contentIntent);
338 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
339 }
340 }
341
342
343 /**
344 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
345 * copying them inside the ownCloud local directory was not possible.
346 *
347 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
348 * synchronization problems if a local file is linked to more than one remote file.
349 *
350 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
351 */
352 private void notifyForgottenLocalFiles() {
353 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
354 notification.flags |= Notification.FLAG_AUTO_CANCEL;
355
356 /// includes a pending intent in the notification showing a more detailed explanation
357 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
358 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
359 ArrayList<String> remotePaths = new ArrayList<String>();
360 ArrayList<String> localPaths = new ArrayList<String>();
361 remotePaths.addAll(mForgottenLocalFiles.keySet());
362 localPaths.addAll(mForgottenLocalFiles.values());
363 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
364 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
365 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
366
367 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
368 notification.setLatestEventInfo(getContext().getApplicationContext(),
369 getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
370 String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size()),
371 notification.contentIntent);
372 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
373
374 }
375
376
377 }