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