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