Merge pull request #836 from owncloud/download_folder__fixing_recursive_cancellation
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import android.accounts.Account;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.util.Log;
24
25 import com.owncloud.android.datamodel.FileDataStorageManager;
26 import com.owncloud.android.datamodel.OCFile;
27 import com.owncloud.android.files.services.FileDownloader;
28 import com.owncloud.android.lib.common.OwnCloudClient;
29 import com.owncloud.android.lib.common.operations.OperationCancelledException;
30 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
31 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
32 import com.owncloud.android.lib.common.utils.Log_OC;
33 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
34 import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
35 import com.owncloud.android.lib.resources.files.RemoteFile;
36 import com.owncloud.android.operations.common.SyncOperation;
37 import com.owncloud.android.utils.FileStorageUtils;
38
39 import java.io.File;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Vector;
45 import java.util.concurrent.atomic.AtomicBoolean;
46
47 //import android.support.v4.content.LocalBroadcastManager;
48
49
50 /**
51 * Remote operation performing the synchronization of the list of files contained
52 * in a folder identified with its remote path.
53 *
54 * Fetches the list and properties of the files contained in the given folder, including their
55 * properties, and updates the local database with them.
56 *
57 * Does NOT enter in the child folders to synchronize their contents also.
58 *
59 * @author David A. Velasco
60 */
61 public class SynchronizeFolderOperation extends SyncOperation {
62
63 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
64
65 /** Time stamp for the synchronization process in progress */
66 private long mCurrentSyncTime;
67
68 /** Remote path of the folder to synchronize */
69 private String mRemotePath;
70
71 /** Account where the file to synchronize belongs */
72 private Account mAccount;
73
74 /** Android context; necessary to send requests to the download service */
75 private Context mContext;
76
77 /** Locally cached information about folder to synchronize */
78 private OCFile mLocalFolder;
79
80 /** Files and folders contained in the synchronized folder after a successful operation */
81 //private List<OCFile> mChildren;
82
83 /** Counter of conflicts found between local and remote files */
84 private int mConflictsFound;
85
86 /** Counter of failed operations in synchronization of kept-in-sync files */
87 private int mFailsInFileSyncsFound;
88
89 /** 'True' means that the remote folder changed and should be fetched */
90 private boolean mRemoteFolderChanged;
91
92 private List<OCFile> mFilesForDirectDownload;
93 // to avoid extra PROPFINDs when there was no change in the folder
94
95 private List<SyncOperation> mFilesToSyncContentsWithoutUpload;
96 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
97
98 private List<SyncOperation> mFavouriteFilesToSyncContents;
99 // this will be used for every file when 'folder synchronization' replaces 'folder download'
100
101 private List<SyncOperation> mFoldersToWalkDown;
102
103 private final AtomicBoolean mCancellationRequested;
104
105 /**
106 * Creates a new instance of {@link SynchronizeFolderOperation}.
107 *
108 * @param context Application context.
109 * @param remotePath Path to synchronize.
110 * @param account ownCloud account where the folder is located.
111 * @param currentSyncTime Time stamp for the synchronization process in progress.
112 */
113 public SynchronizeFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){
114 mRemotePath = remotePath;
115 mCurrentSyncTime = currentSyncTime;
116 mAccount = account;
117 mContext = context;
118 mRemoteFolderChanged = false;
119 mFilesForDirectDownload = new Vector<OCFile>();
120 mFilesToSyncContentsWithoutUpload = new Vector<SyncOperation>();
121 mFavouriteFilesToSyncContents = new Vector<SyncOperation>();
122 mFoldersToWalkDown = new Vector<SyncOperation>();
123 mCancellationRequested = new AtomicBoolean(false);
124 }
125
126
127 public int getConflictsFound() {
128 return mConflictsFound;
129 }
130
131 public int getFailsInFileSyncsFound() {
132 return mFailsInFileSyncsFound;
133 }
134
135 /**
136 * Performs the synchronization.
137 *
138 * {@inheritDoc}
139 */
140 @Override
141 protected RemoteOperationResult run(OwnCloudClient client) {
142 RemoteOperationResult result = null;
143 mFailsInFileSyncsFound = 0;
144 mConflictsFound = 0;
145
146 try {
147 // get locally cached information about folder
148 mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
149
150 result = checkForChanges(client);
151
152 if (result.isSuccess()) {
153 if (mRemoteFolderChanged) {
154 result = fetchAndSyncRemoteFolder(client);
155
156 } else {
157 prepareOpsFromLocalKnowledge();
158 }
159
160 if (result.isSuccess()) {
161 syncContents(client);
162 }
163
164 if (mFilesForDirectDownload.isEmpty()) {
165 sendBroadcastForNotifyingUIUpdate(result.isSuccess());
166 }
167 }
168
169 if (mCancellationRequested.get()) {
170 throw new OperationCancelledException();
171 }
172
173 } catch (OperationCancelledException e) {
174 result = new RemoteOperationResult(e);
175
176 // Needed in case that cancellation occurs before starting any download.
177 // If not, yellow arrow continues being shown.
178 sendBroadcastForNotifyingUIUpdate(false);
179
180 Intent intent = new Intent(mContext, FileDownloader.class);
181 intent.setAction(FileDownloader.ACTION_CANCEL_FILE_DOWNLOAD);
182 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
183 intent.putExtra(FileDownloader.EXTRA_FILE, mLocalFolder);
184 mContext.startService(intent);
185 }
186
187 return result;
188
189 }
190
191 private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException {
192 Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
193
194 mRemoteFolderChanged = true;
195 RemoteOperationResult result = null;
196
197 if (mCancellationRequested.get()) {
198 throw new OperationCancelledException();
199 }
200
201 // remote request
202 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
203 result = operation.execute(client);
204 if (result.isSuccess()){
205 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
206
207 // check if remote and local folder are different
208 mRemoteFolderChanged =
209 !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
210
211 result = new RemoteOperationResult(ResultCode.OK);
212
213 Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
214 (mRemoteFolderChanged ? "changed" : "not changed"));
215
216 } else {
217 // check failed
218 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
219 removeLocalFolder();
220 }
221 if (result.isException()) {
222 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
223 result.getLogMessage(), result.getException());
224 } else {
225 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
226 result.getLogMessage());
227 }
228
229 sendBroadcastForNotifyingUIUpdate(result.isSuccess());
230 }
231
232 return result;
233 }
234
235
236 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
237 if (mCancellationRequested.get()) {
238 throw new OperationCancelledException();
239 }
240
241 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
242 RemoteOperationResult result = operation.execute(client);
243 Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
244
245 if (result.isSuccess()) {
246 synchronizeData(result.getData(), client);
247 if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
248 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
249 // should be a different result code, but will do the job
250 }
251 } else {
252 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
253 removeLocalFolder();
254 }
255
256
257 return result;
258 }
259
260
261 private void removeLocalFolder() {
262 FileDataStorageManager storageManager = getStorageManager();
263 if (storageManager.fileExists(mLocalFolder.getFileId())) {
264 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
265 storageManager.removeFolder(
266 mLocalFolder,
267 true,
268 ( mLocalFolder.isDown() && // TODO: debug, I think this is always false for folders
269 mLocalFolder.getStoragePath().startsWith(currentSavePath)
270 )
271 );
272 }
273 }
274
275
276 /**
277 * Synchronizes the data retrieved from the server about the contents of the target folder
278 * with the current data in the local database.
279 *
280 * Grants that mChildren is updated with fresh data after execution.
281 *
282 * @param folderAndFiles Remote folder and children files in Folder
283 *
284 * @param client Client instance to the remote server where the data were
285 * retrieved.
286 * @return 'True' when any change was made in the local data, 'false' otherwise
287 */
288 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client)
289 throws OperationCancelledException {
290 FileDataStorageManager storageManager = getStorageManager();
291
292 // parse data from remote folder
293 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
294 remoteFolder.setParentId(mLocalFolder.getParentId());
295 remoteFolder.setFileId(mLocalFolder.getFileId());
296
297 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
298 + " changed - starting update of local data ");
299
300 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
301 mFilesForDirectDownload.clear();
302 mFilesToSyncContentsWithoutUpload.clear();
303 mFavouriteFilesToSyncContents.clear();
304
305 synchronized(mFoldersToWalkDown) {
306 if (mCancellationRequested.get()) {
307 throw new OperationCancelledException();
308 }
309 mFoldersToWalkDown.clear();
310 }
311
312 // get current data about local contents of the folder to synchronize
313 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder);
314 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
315 for (OCFile file : localFiles) {
316 localFilesMap.put(file.getRemotePath(), file);
317 }
318
319 // loop to synchronize every child
320 OCFile remoteFile = null, localFile = null;
321 for (int i=1; i<folderAndFiles.size(); i++) {
322 /// new OCFile instance with the data from the server
323 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
324 remoteFile.setParentId(mLocalFolder.getFileId());
325
326 /// retrieve local data for the read file
327 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
328 localFile = localFilesMap.remove(remoteFile.getRemotePath());
329
330 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
331 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
332 if (localFile != null) {
333 // some properties of local state are kept unmodified
334 remoteFile.setFileId(localFile.getFileId());
335 remoteFile.setKeepInSync(localFile.keepInSync());
336 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
337 remoteFile.setModificationTimestampAtLastSyncForData(
338 localFile.getModificationTimestampAtLastSyncForData()
339 );
340 remoteFile.setStoragePath(localFile.getStoragePath());
341 // eTag will not be updated unless contents are synchronized
342 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
343 remoteFile.setEtag(localFile.getEtag());
344 if (remoteFile.isFolder()) {
345 remoteFile.setFileLength(localFile.getFileLength());
346 // TODO move operations about size of folders to FileContentProvider
347 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
348 remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
349 remoteFile.setNeedsUpdateThumbnail(true);
350 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
351 }
352 remoteFile.setPublicLink(localFile.getPublicLink());
353 remoteFile.setShareByLink(localFile.isShareByLink());
354 } else {
355 // remote eTag will not be updated unless contents are synchronized
356 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
357 remoteFile.setEtag("");
358 }
359
360 /// check and fix, if needed, local storage path
361 searchForLocalFileInDefaultPath(remoteFile);
362
363 /// classify file to sync/download contents later
364 if (remoteFile.isFolder()) {
365 /// to download children files recursively
366 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(
367 mContext,
368 remoteFile.getRemotePath(),
369 mAccount,
370 mCurrentSyncTime
371 );
372
373 synchronized(mFoldersToWalkDown) {
374 if (mCancellationRequested.get()) {
375 throw new OperationCancelledException();
376 }
377 mFoldersToWalkDown.add(synchFolderOp);
378 }
379
380 } else if (remoteFile.keepInSync()) {
381 /// prepare content synchronization for kept-in-sync files
382 SynchronizeFileOperation operation = new SynchronizeFileOperation(
383 localFile,
384 remoteFile,
385 mAccount,
386 true,
387 mContext
388 );
389 mFavouriteFilesToSyncContents.add(operation);
390
391 } else {
392 /// prepare limited synchronization for regular files
393 SynchronizeFileOperation operation = new SynchronizeFileOperation(
394 localFile,
395 remoteFile,
396 mAccount,
397 true,
398 false,
399 mContext
400 );
401 mFilesToSyncContentsWithoutUpload.add(operation);
402 }
403
404 updatedFiles.add(remoteFile);
405 }
406
407 // save updated contents in local database
408 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
409
410 }
411
412
413 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
414 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder);
415 for (OCFile child : children) {
416 /// classify file to sync/download contents later
417 if (child.isFolder()) {
418 /// to download children files recursively
419 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(
420 mContext,
421 child.getRemotePath(),
422 mAccount,
423 mCurrentSyncTime
424 );
425
426 synchronized(mFoldersToWalkDown) {
427 if (mCancellationRequested.get()) {
428 throw new OperationCancelledException();
429 }
430 mFoldersToWalkDown.add(synchFolderOp);
431 }
432
433 } else {
434 /// prepare limited synchronization for regular files
435 if (!child.isDown()) {
436 mFilesForDirectDownload.add(child);
437 }
438 }
439 }
440 }
441
442
443 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
444 startDirectDownloads();
445 startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client);
446 startContentSynchronizations(mFavouriteFilesToSyncContents, client);
447 walkSubfolders(client); // this must be the last!
448 }
449
450
451 private void startDirectDownloads() throws OperationCancelledException {
452 for (OCFile file : mFilesForDirectDownload) {
453 if (mCancellationRequested.get()) {
454 throw new OperationCancelledException();
455 }
456 Intent i = new Intent(mContext, FileDownloader.class);
457 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
458 i.putExtra(FileDownloader.EXTRA_FILE, file);
459 mContext.startService(i);
460 }
461 }
462
463 /**
464 * Performs a list of synchronization operations, determining if a download or upload is needed
465 * or if exists conflict due to changes both in local and remote contents of the each file.
466 *
467 * If download or upload is needed, request the operation to the corresponding service and goes
468 * on.
469 *
470 * @param filesToSyncContents Synchronization operations to execute.
471 * @param client Interface to the remote ownCloud server.
472 */
473 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents, OwnCloudClient client)
474 throws OperationCancelledException {
475
476 RemoteOperationResult contentsResult = null;
477 for (SyncOperation op: filesToSyncContents) {
478 if (mCancellationRequested.get()) {
479 throw new OperationCancelledException();
480 }
481 contentsResult = op.execute(getStorageManager(), mContext);
482 if (!contentsResult.isSuccess()) {
483 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
484 mConflictsFound++;
485 } else {
486 mFailsInFileSyncsFound++;
487 if (contentsResult.getException() != null) {
488 Log_OC.e(TAG, "Error while synchronizing file : "
489 + contentsResult.getLogMessage(), contentsResult.getException());
490 } else {
491 Log_OC.e(TAG, "Error while synchronizing file : "
492 + contentsResult.getLogMessage());
493 }
494 }
495 // TODO - use the errors count in notifications
496 } // won't let these fails break the synchronization process
497 }
498 }
499
500
501 private void walkSubfolders(OwnCloudClient client) throws OperationCancelledException {
502 RemoteOperationResult contentsResult = null;
503 for (SyncOperation op: mFoldersToWalkDown) {
504 if (mCancellationRequested.get()) {
505 throw new OperationCancelledException();
506 }
507 contentsResult = op.execute(client, getStorageManager()); // to watch out: possibly deep recursion
508 if (!contentsResult.isSuccess()) {
509 // TODO - some kind of error count, and use it with notifications
510 if (contentsResult.getException() != null) {
511 Log_OC.e(TAG, "Non blocking exception : "
512 + contentsResult.getLogMessage(), contentsResult.getException());
513 } else {
514 Log_OC.e(TAG, "Non blocking error : " + contentsResult.getLogMessage());
515 }
516 } // won't let these fails break the synchronization process
517 }
518 }
519
520
521 /**
522 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
523 *
524 * @param remote remote file read from the server (remote file or folder).
525 * @return New OCFile instance representing the remote resource described by we.
526 */
527 private OCFile fillOCFile(RemoteFile remote) {
528 OCFile file = new OCFile(remote.getRemotePath());
529 file.setCreationTimestamp(remote.getCreationTimestamp());
530 file.setFileLength(remote.getLength());
531 file.setMimetype(remote.getMimeType());
532 file.setModificationTimestamp(remote.getModifiedTimestamp());
533 file.setEtag(remote.getEtag());
534 file.setPermissions(remote.getPermissions());
535 file.setRemoteId(remote.getRemoteId());
536 return file;
537 }
538
539
540 /**
541 * Scans the default location for saving local copies of files searching for
542 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
543 * parameter.
544 *
545 * @param file File to associate a possible 'lost' local file.
546 */
547 private void searchForLocalFileInDefaultPath(OCFile file) {
548 if (file.getStoragePath() == null && !file.isFolder()) {
549 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
550 if (f.exists()) {
551 file.setStoragePath(f.getAbsolutePath());
552 file.setLastSyncDateForData(f.lastModified());
553 }
554 }
555 }
556
557 private void sendBroadcastForNotifyingUIUpdate(boolean result) {
558 // Send a broadcast message for notifying UI update
559 Intent uiUpdate = new Intent(FileDownloader.getDownloadFinishMessage());
560 uiUpdate.putExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, result);
561 uiUpdate.putExtra(FileDownloader.ACCOUNT_NAME, mAccount.name);
562 uiUpdate.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mRemotePath);
563 uiUpdate.putExtra(FileDownloader.EXTRA_FILE_PATH, mLocalFolder.getRemotePath());
564 mContext.sendStickyBroadcast(uiUpdate);
565 }
566
567
568 /**
569 * Cancel operation
570 */
571 public void cancel() {
572 mCancellationRequested.set(true);
573
574 synchronized(mFoldersToWalkDown) {
575 // cancel 'child' synchronizations
576 for (SyncOperation synchOp : mFoldersToWalkDown) {
577 ((SynchronizeFolderOperation) synchOp).cancel();
578 }
579 }
580 }
581
582 public String getFolderPath() {
583 String path = mLocalFolder.getStoragePath();
584 if (path != null && path.length() > 0) {
585 return path;
586 }
587 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
588 }
589 }