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() &&
229 ( result.isIdPRedirection() &&
230 AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))) {
231 mSyncResult.stats.numAuthExceptions++;
232
233 } else if (result.getException() instanceof DavException) {
234 mSyncResult.stats.numParseExceptions++;
235
236 } else if (result.getException() instanceof IOException) {
237 mSyncResult.stats.numIoExceptions++;
238 }
239 mFailedResultsCounter++;
240 mLastFailedResult = result;
241 }
242
243 }
244
245 /**
246 * Checks if a failed result should terminate the synchronization process immediately, according to
247 * OUR OWN POLICY
248 *
249 * @param failedResult Remote operation result to check.
250 * @return 'True' if the result should immediately finish the synchronization
251 */
252 private boolean isFinisher(RemoteOperationResult failedResult) {
253 if (failedResult != null) {
254 RemoteOperationResult.ResultCode code = failedResult.getCode();
255 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
256 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
257 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
258 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
259 }
260 return false;
261 }
262
263 /**
264 * Synchronize data of folders in the list of received files
265 *
266 * @param files Files to recursively fetch
267 */
268 private void fetchChildren(List<OCFile> files) {
269 int i;
270 for (i=0; i < files.size() && !mCancellation; i++) {
271 OCFile newFile = files.get(i);
272 if (newFile.isDirectory()) {
273 fetchData(newFile.getRemotePath(), newFile.getFileId());
274
275 // Update folder size on DB
276 getStorageManager().calculateFolderSize(newFile.getFileId());
277 }
278 }
279
280 if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");
281 }
282
283
284 /**
285 * Sends a message to any application component interested in the progress of the synchronization.
286 *
287 * @param inProgress 'True' when the synchronization progress is not finished.
288 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
289 */
290 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
291 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
292 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
293 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
294 if (dirRemotePath != null) {
295 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
296 }
297 if (result != null) {
298 i.putExtra(FileSyncService.SYNC_RESULT, result);
299 }
300 getContext().sendStickyBroadcast(i);
301 }
302
303
304
305 /**
306 * Notifies the user about a failed synchronization through the status notification bar
307 */
308 private void notifyFailedSynchronization() {
309 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
310 notification.flags |= Notification.FLAG_AUTO_CANCEL;
311 boolean needsToUpdateCredentials = (mLastFailedResult != null &&
312 ( mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
313 // (mLastFailedResult.isTemporalRedirection() && mLastFailedResult.isIdPRedirection() &&
314 ( mLastFailedResult.isIdPRedirection() &&
315 AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))
316 )
317 );
318 // TODO put something smart in the contentIntent below for all the possible errors
319 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
320 if (needsToUpdateCredentials) {
321 // let the user update credentials with one click
322 Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
323 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
324 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
325 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
326 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
327 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
328 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
329 notification.contentIntent = PendingIntent.getActivity(getContext(), (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
330 notification.setLatestEventInfo(getContext().getApplicationContext(),
331 getContext().getString(R.string.sync_fail_ticker),
332 String.format(getContext().getString(R.string.sync_fail_content_unauthorized), getAccount().name),
333 notification.contentIntent);
334 } else {
335 notification.setLatestEventInfo(getContext().getApplicationContext(),
336 getContext().getString(R.string.sync_fail_ticker),
337 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
338 notification.contentIntent);
339 }
340 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
341 }
342
343
344 /**
345 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
346 *
347 * By now, we won't consider a failed synchronization.
348 */
349 private void notifyFailsInFavourites() {
350 if (mFailedResultsCounter > 0) {
351 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
352 notification.flags |= Notification.FLAG_AUTO_CANCEL;
353 // TODO put something smart in the contentIntent below
354 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
355 notification.setLatestEventInfo(getContext().getApplicationContext(),
356 getContext().getString(R.string.sync_fail_in_favourites_ticker),
357 String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
358 notification.contentIntent);
359 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
360
361 } else {
362 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
363 notification.flags |= Notification.FLAG_AUTO_CANCEL;
364 // TODO put something smart in the contentIntent below
365 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
366 notification.setLatestEventInfo(getContext().getApplicationContext(),
367 getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
368 String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
369 notification.contentIntent);
370 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
371 }
372 }
373
374 /**
375 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
376 * copying them inside the ownCloud local directory was not possible.
377 *
378 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
379 * synchronization problems if a local file is linked to more than one remote file.
380 *
381 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
382 */
383 private void notifyForgottenLocalFiles() {
384 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
385 notification.flags |= Notification.FLAG_AUTO_CANCEL;
386
387 /// includes a pending intent in the notification showing a more detailed explanation
388 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
389 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
390 ArrayList<String> remotePaths = new ArrayList<String>();
391 ArrayList<String> localPaths = new ArrayList<String>();
392 remotePaths.addAll(mForgottenLocalFiles.keySet());
393 localPaths.addAll(mForgottenLocalFiles.values());
394 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
395 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
396 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
397
398 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
399 notification.setLatestEventInfo(getContext().getApplicationContext(),
400 getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
401 String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size(), getContext().getString(R.string.app_name)),
402 notification.contentIntent);
403 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
404
405 }
406
407
408 }