Merge pull request #118 from owncloud/loggingtool
[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.Log_OC;
32 import com.owncloud.android.R;
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 android.accounts.Account;
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 (UnknownHostException 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 }
113
114 Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
115 sendStickyBroadcast(true, null, null); // message to signal the start of the synchronization to the UI
116
117 try {
118 updateOCVersion();
119 mCurrentSyncTime = System.currentTimeMillis();
120 if (!mCancellation) {
121 fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);
122
123 } else {
124 Log_OC.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");
125 }
126
127
128 } finally {
129 // it's important making this although very unexpected errors occur; that's the reason for the finally
130
131 if (mFailedResultsCounter > 0 && mIsManualSync) {
132 /// don't let the system synchronization manager retries MANUAL synchronizations
133 // (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
134 mSyncResult.tooManyRetries = true;
135
136 /// notify the user about the failure of MANUAL synchronization
137 notifyFailedSynchronization();
138
139 }
140 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
141 notifyFailsInFavourites();
142 }
143 if (mForgottenLocalFiles.size() > 0) {
144 notifyForgottenLocalFiles();
145
146 }
147 sendStickyBroadcast(false, null, mLastFailedResult); // message to signal the end to the UI
148 }
149
150 }
151
152
153 /**
154 * Called by system SyncManager when a synchronization is required to be cancelled.
155 *
156 * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder
157 * fetched will be still saved in the database. See onPerformSync implementation.
158 */
159 @Override
160 public void onSyncCanceled() {
161 Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
162 mCancellation = true;
163 super.onSyncCanceled();
164 }
165
166
167 /**
168 * Updates the locally stored version value of the ownCloud server
169 */
170 private void updateOCVersion() {
171 UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
172 RemoteOperationResult result = update.execute(getClient());
173 if (!result.isSuccess()) {
174 mLastFailedResult = result;
175 }
176 }
177
178
179
180 /**
181 * Synchronize the properties of files and folders contained in a remote folder given by remotePath.
182 *
183 * @param remotePath Remote path to the folder to synchronize.
184 * @param parentId Database Id of the folder to synchronize.
185 */
186 private void fetchData(String remotePath, long parentId) {
187
188 if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))
189 return;
190
191 // perform folder synchronization
192 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation( remotePath,
193 mCurrentSyncTime,
194 parentId,
195 getStorageManager(),
196 getAccount(),
197 getContext()
198 );
199 RemoteOperationResult result = synchFolderOp.execute(getClient());
200
201
202 // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
203 sendStickyBroadcast(true, remotePath, null);
204
205 if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
206
207 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
208 mConflictsFound += synchFolderOp.getConflictsFound();
209 mFailsInFavouritesFound += synchFolderOp.getFailsInFavouritesFound();
210 }
211 if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
212 mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
213 }
214 // synchronize children folders
215 List<OCFile> children = synchFolderOp.getChildren();
216 fetchChildren(children); // beware of the 'hidden' recursion here!
217
218 } else {
219 if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
220 mSyncResult.stats.numAuthExceptions++;
221
222 } else if (result.getException() instanceof DavException) {
223 mSyncResult.stats.numParseExceptions++;
224
225 } else if (result.getException() instanceof IOException) {
226 mSyncResult.stats.numIoExceptions++;
227 }
228 mFailedResultsCounter++;
229 mLastFailedResult = result;
230 }
231
232 }
233
234 /**
235 * Checks if a failed result should terminate the synchronization process immediately, according to
236 * OUR OWN POLICY
237 *
238 * @param failedResult Remote operation result to check.
239 * @return 'True' if the result should immediately finish the synchronization
240 */
241 private boolean isFinisher(RemoteOperationResult failedResult) {
242 if (failedResult != null) {
243 RemoteOperationResult.ResultCode code = failedResult.getCode();
244 return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||
245 code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||
246 code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||
247 code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));
248 }
249 return false;
250 }
251
252 /**
253 * Synchronize data of folders in the list of received files
254 *
255 * @param files Files to recursively fetch
256 */
257 private void fetchChildren(List<OCFile> files) {
258 int i;
259 for (i=0; i < files.size() && !mCancellation; i++) {
260 OCFile newFile = files.get(i);
261 if (newFile.isDirectory()) {
262 fetchData(newFile.getRemotePath(), newFile.getFileId());
263 }
264 }
265 if (mCancellation && i <files.size()) Log_OC.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");
266 }
267
268
269 /**
270 * Sends a message to any application component interested in the progress of the synchronization.
271 *
272 * @param inProgress 'True' when the synchronization progress is not finished.
273 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
274 */
275 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
276 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
277 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
278 i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);
279 if (dirRemotePath != null) {
280 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
281 }
282 if (result != null) {
283 i.putExtra(FileSyncService.SYNC_RESULT, result);
284 }
285 getContext().sendStickyBroadcast(i);
286 }
287
288
289
290 /**
291 * Notifies the user about a failed synchronization through the status notification bar
292 */
293 private void notifyFailedSynchronization() {
294 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
295 notification.flags |= Notification.FLAG_AUTO_CANCEL;
296 // TODO put something smart in the contentIntent below
297 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
298 notification.setLatestEventInfo(getContext().getApplicationContext(),
299 getContext().getString(R.string.sync_fail_ticker),
300 String.format(getContext().getString(R.string.sync_fail_content), getAccount().name),
301 notification.contentIntent);
302 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);
303 }
304
305
306 /**
307 * Notifies the user about conflicts and strange fails when trying to synchronize the contents of kept-in-sync files.
308 *
309 * By now, we won't consider a failed synchronization.
310 */
311 private void notifyFailsInFavourites() {
312 if (mFailedResultsCounter > 0) {
313 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_in_favourites_ticker), System.currentTimeMillis());
314 notification.flags |= Notification.FLAG_AUTO_CANCEL;
315 // TODO put something smart in the contentIntent below
316 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
317 notification.setLatestEventInfo(getContext().getApplicationContext(),
318 getContext().getString(R.string.sync_fail_in_favourites_ticker),
319 String.format(getContext().getString(R.string.sync_fail_in_favourites_content), mFailedResultsCounter + mConflictsFound, mConflictsFound),
320 notification.contentIntent);
321 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_in_favourites_ticker, notification);
322
323 } else {
324 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_conflicts_in_favourites_ticker), System.currentTimeMillis());
325 notification.flags |= Notification.FLAG_AUTO_CANCEL;
326 // TODO put something smart in the contentIntent below
327 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
328 notification.setLatestEventInfo(getContext().getApplicationContext(),
329 getContext().getString(R.string.sync_conflicts_in_favourites_ticker),
330 String.format(getContext().getString(R.string.sync_conflicts_in_favourites_content), mConflictsFound),
331 notification.contentIntent);
332 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_conflicts_in_favourites_ticker, notification);
333 }
334 }
335
336
337 /**
338 * Notifies the user about local copies of files out of the ownCloud local directory that were 'forgotten' because
339 * copying them inside the ownCloud local directory was not possible.
340 *
341 * We don't want links to files out of the ownCloud local directory (foreign files) anymore. It's easy to have
342 * synchronization problems if a local file is linked to more than one remote file.
343 *
344 * We won't consider a synchronization as failed when foreign files can not be copied to the ownCloud local directory.
345 */
346 private void notifyForgottenLocalFiles() {
347 Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_foreign_files_forgotten_ticker), System.currentTimeMillis());
348 notification.flags |= Notification.FLAG_AUTO_CANCEL;
349
350 /// includes a pending intent in the notification showing a more detailed explanation
351 Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
352 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
353 ArrayList<String> remotePaths = new ArrayList<String>();
354 ArrayList<String> localPaths = new ArrayList<String>();
355 remotePaths.addAll(mForgottenLocalFiles.keySet());
356 localPaths.addAll(mForgottenLocalFiles.values());
357 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
358 explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
359 explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
360
361 notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), explanationIntent, 0);
362 notification.setLatestEventInfo(getContext().getApplicationContext(),
363 getContext().getString(R.string.sync_foreign_files_forgotten_ticker),
364 String.format(getContext().getString(R.string.sync_foreign_files_forgotten_content), mForgottenLocalFiles.size(), getContext().getString(R.string.app_name)),
365 notification.contentIntent);
366 ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_foreign_files_forgotten_ticker, notification);
367
368 }
369
370
371 }