Fix for downloads that are not cancelled
[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 /// cancellation of download needs to be done separately in any case; a SynchronizeFolderOperation
177 // may finish much sooner than the real download of the files in the folder
178 Intent intent = new Intent(mContext, FileDownloader.class);
179 intent.setAction(FileDownloader.ACTION_CANCEL_FILE_DOWNLOAD);
180 intent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
181 intent.putExtra(FileDownloader.EXTRA_FILE, mLocalFolder);
182 mContext.startService(intent);
183 }
184
185 return result;
186
187 }
188
189 private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException {
190 Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
191
192 mRemoteFolderChanged = true;
193 RemoteOperationResult result = null;
194
195 if (mCancellationRequested.get()) {
196 throw new OperationCancelledException();
197 }
198
199 // remote request
200 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
201 result = operation.execute(client);
202 if (result.isSuccess()){
203 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
204
205 // check if remote and local folder are different
206 mRemoteFolderChanged =
207 !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
208
209 result = new RemoteOperationResult(ResultCode.OK);
210
211 Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
212 (mRemoteFolderChanged ? "changed" : "not changed"));
213
214 } else {
215 // check failed
216 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
217 removeLocalFolder();
218 }
219 if (result.isException()) {
220 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
221 result.getLogMessage(), result.getException());
222 } else {
223 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
224 result.getLogMessage());
225 }
226
227 sendBroadcastForNotifyingUIUpdate(result.isSuccess());
228 }
229
230 return result;
231 }
232
233
234 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
235 if (mCancellationRequested.get()) {
236 throw new OperationCancelledException();
237 }
238
239 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
240 RemoteOperationResult result = operation.execute(client);
241 Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
242
243 if (result.isSuccess()) {
244 synchronizeData(result.getData(), client);
245 if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
246 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
247 // should be a different result code, but will do the job
248 }
249 } else {
250 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
251 removeLocalFolder();
252 }
253
254
255 return result;
256 }
257
258
259 private void removeLocalFolder() {
260 FileDataStorageManager storageManager = getStorageManager();
261 if (storageManager.fileExists(mLocalFolder.getFileId())) {
262 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
263 storageManager.removeFolder(
264 mLocalFolder,
265 true,
266 ( mLocalFolder.isDown() && // TODO: debug, I think this is always false for folders
267 mLocalFolder.getStoragePath().startsWith(currentSavePath)
268 )
269 );
270 }
271 }
272
273
274 /**
275 * Synchronizes the data retrieved from the server about the contents of the target folder
276 * with the current data in the local database.
277 *
278 * Grants that mChildren is updated with fresh data after execution.
279 *
280 * @param folderAndFiles Remote folder and children files in Folder
281 *
282 * @param client Client instance to the remote server where the data were
283 * retrieved.
284 * @return 'True' when any change was made in the local data, 'false' otherwise
285 */
286 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client)
287 throws OperationCancelledException {
288 FileDataStorageManager storageManager = getStorageManager();
289
290 // parse data from remote folder
291 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
292 remoteFolder.setParentId(mLocalFolder.getParentId());
293 remoteFolder.setFileId(mLocalFolder.getFileId());
294
295 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
296 + " changed - starting update of local data ");
297
298 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
299 mFilesForDirectDownload.clear();
300 mFilesToSyncContentsWithoutUpload.clear();
301 mFavouriteFilesToSyncContents.clear();
302
303 synchronized(mFoldersToWalkDown) {
304 if (mCancellationRequested.get()) {
305 throw new OperationCancelledException();
306 }
307 mFoldersToWalkDown.clear();
308 }
309
310 // get current data about local contents of the folder to synchronize
311 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder);
312 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
313 for (OCFile file : localFiles) {
314 localFilesMap.put(file.getRemotePath(), file);
315 }
316
317 // loop to synchronize every child
318 OCFile remoteFile = null, localFile = null;
319 for (int i=1; i<folderAndFiles.size(); i++) {
320 /// new OCFile instance with the data from the server
321 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
322 remoteFile.setParentId(mLocalFolder.getFileId());
323
324 /// retrieve local data for the read file
325 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
326 localFile = localFilesMap.remove(remoteFile.getRemotePath());
327
328 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
329 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
330 if (localFile != null) {
331 // some properties of local state are kept unmodified
332 remoteFile.setFileId(localFile.getFileId());
333 remoteFile.setKeepInSync(localFile.keepInSync());
334 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
335 remoteFile.setModificationTimestampAtLastSyncForData(
336 localFile.getModificationTimestampAtLastSyncForData()
337 );
338 remoteFile.setStoragePath(localFile.getStoragePath());
339 // eTag will not be updated unless contents are synchronized
340 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
341 remoteFile.setEtag(localFile.getEtag());
342 if (remoteFile.isFolder()) {
343 remoteFile.setFileLength(localFile.getFileLength());
344 // TODO move operations about size of folders to FileContentProvider
345 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
346 remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
347 remoteFile.setNeedsUpdateThumbnail(true);
348 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
349 }
350 remoteFile.setPublicLink(localFile.getPublicLink());
351 remoteFile.setShareByLink(localFile.isShareByLink());
352 } else {
353 // remote eTag will not be updated unless contents are synchronized
354 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
355 remoteFile.setEtag("");
356 }
357
358 /// check and fix, if needed, local storage path
359 searchForLocalFileInDefaultPath(remoteFile);
360
361 /// classify file to sync/download contents later
362 if (remoteFile.isFolder()) {
363 /// to download children files recursively
364 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(
365 mContext,
366 remoteFile.getRemotePath(),
367 mAccount,
368 mCurrentSyncTime
369 );
370
371 synchronized(mFoldersToWalkDown) {
372 if (mCancellationRequested.get()) {
373 throw new OperationCancelledException();
374 }
375 mFoldersToWalkDown.add(synchFolderOp);
376 }
377
378 } else if (remoteFile.keepInSync()) {
379 /// prepare content synchronization for kept-in-sync files
380 SynchronizeFileOperation operation = new SynchronizeFileOperation(
381 localFile,
382 remoteFile,
383 mAccount,
384 true,
385 mContext
386 );
387 mFavouriteFilesToSyncContents.add(operation);
388
389 } else {
390 /// prepare limited synchronization for regular files
391 SynchronizeFileOperation operation = new SynchronizeFileOperation(
392 localFile,
393 remoteFile,
394 mAccount,
395 true,
396 false,
397 mContext
398 );
399 mFilesToSyncContentsWithoutUpload.add(operation);
400 }
401
402 updatedFiles.add(remoteFile);
403 }
404
405 // save updated contents in local database
406 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
407
408 }
409
410
411 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
412 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder);
413 for (OCFile child : children) {
414 /// classify file to sync/download contents later
415 if (child.isFolder()) {
416 /// to download children files recursively
417 SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(
418 mContext,
419 child.getRemotePath(),
420 mAccount,
421 mCurrentSyncTime
422 );
423
424 synchronized(mFoldersToWalkDown) {
425 if (mCancellationRequested.get()) {
426 throw new OperationCancelledException();
427 }
428 mFoldersToWalkDown.add(synchFolderOp);
429 }
430
431 } else {
432 /// prepare limited synchronization for regular files
433 if (!child.isDown()) {
434 mFilesForDirectDownload.add(child);
435 }
436 }
437 }
438 }
439
440
441 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
442 startDirectDownloads();
443 startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client);
444 startContentSynchronizations(mFavouriteFilesToSyncContents, client);
445 walkSubfolders(client); // this must be the last!
446 }
447
448
449 private void startDirectDownloads() throws OperationCancelledException {
450 for (OCFile file : mFilesForDirectDownload) {
451 if (mCancellationRequested.get()) {
452 throw new OperationCancelledException();
453 }
454 Intent i = new Intent(mContext, FileDownloader.class);
455 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
456 i.putExtra(FileDownloader.EXTRA_FILE, file);
457 mContext.startService(i);
458 }
459 }
460
461 /**
462 * Performs a list of synchronization operations, determining if a download or upload is needed
463 * or if exists conflict due to changes both in local and remote contents of the each file.
464 *
465 * If download or upload is needed, request the operation to the corresponding service and goes
466 * on.
467 *
468 * @param filesToSyncContents Synchronization operations to execute.
469 * @param client Interface to the remote ownCloud server.
470 */
471 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents, OwnCloudClient client)
472 throws OperationCancelledException {
473
474 RemoteOperationResult contentsResult = null;
475 for (SyncOperation op: filesToSyncContents) {
476 if (mCancellationRequested.get()) {
477 throw new OperationCancelledException();
478 }
479 contentsResult = op.execute(getStorageManager(), mContext);
480 if (!contentsResult.isSuccess()) {
481 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
482 mConflictsFound++;
483 } else {
484 mFailsInFileSyncsFound++;
485 if (contentsResult.getException() != null) {
486 Log_OC.e(TAG, "Error while synchronizing file : "
487 + contentsResult.getLogMessage(), contentsResult.getException());
488 } else {
489 Log_OC.e(TAG, "Error while synchronizing file : "
490 + contentsResult.getLogMessage());
491 }
492 }
493 // TODO - use the errors count in notifications
494 } // won't let these fails break the synchronization process
495 }
496 }
497
498
499 private void walkSubfolders(OwnCloudClient client) throws OperationCancelledException {
500 RemoteOperationResult contentsResult = null;
501 for (SyncOperation op: mFoldersToWalkDown) {
502 if (mCancellationRequested.get()) {
503 throw new OperationCancelledException();
504 }
505 contentsResult = op.execute(client, getStorageManager()); // to watch out: possibly deep recursion
506 if (!contentsResult.isSuccess()) {
507 // TODO - some kind of error count, and use it with notifications
508 if (contentsResult.getException() != null) {
509 Log_OC.e(TAG, "Non blocking exception : "
510 + contentsResult.getLogMessage(), contentsResult.getException());
511 } else {
512 Log_OC.e(TAG, "Non blocking error : " + contentsResult.getLogMessage());
513 }
514 } // won't let these fails break the synchronization process
515 }
516 }
517
518
519 /**
520 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
521 *
522 * @param remote remote file read from the server (remote file or folder).
523 * @return New OCFile instance representing the remote resource described by we.
524 */
525 private OCFile fillOCFile(RemoteFile remote) {
526 OCFile file = new OCFile(remote.getRemotePath());
527 file.setCreationTimestamp(remote.getCreationTimestamp());
528 file.setFileLength(remote.getLength());
529 file.setMimetype(remote.getMimeType());
530 file.setModificationTimestamp(remote.getModifiedTimestamp());
531 file.setEtag(remote.getEtag());
532 file.setPermissions(remote.getPermissions());
533 file.setRemoteId(remote.getRemoteId());
534 return file;
535 }
536
537
538 /**
539 * Scans the default location for saving local copies of files searching for
540 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
541 * parameter.
542 *
543 * @param file File to associate a possible 'lost' local file.
544 */
545 private void searchForLocalFileInDefaultPath(OCFile file) {
546 if (file.getStoragePath() == null && !file.isFolder()) {
547 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
548 if (f.exists()) {
549 file.setStoragePath(f.getAbsolutePath());
550 file.setLastSyncDateForData(f.lastModified());
551 }
552 }
553 }
554
555 private void sendBroadcastForNotifyingUIUpdate(boolean result) {
556 // Send a broadcast message for notifying UI update
557 Intent uiUpdate = new Intent(FileDownloader.getDownloadFinishMessage());
558 uiUpdate.putExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, result);
559 uiUpdate.putExtra(FileDownloader.ACCOUNT_NAME, mAccount.name);
560 uiUpdate.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mRemotePath);
561 uiUpdate.putExtra(FileDownloader.EXTRA_FILE_PATH, mLocalFolder.getRemotePath());
562 mContext.sendStickyBroadcast(uiUpdate);
563 }
564
565
566 /**
567 * Cancel operation
568 */
569 public void cancel() {
570 mCancellationRequested.set(true);
571
572 synchronized(mFoldersToWalkDown) {
573 // cancel 'child' synchronizations
574 for (SyncOperation synchOp : mFoldersToWalkDown) {
575 ((SynchronizeFolderOperation) synchOp).cancel();
576 }
577 }
578 }
579
580 public String getFolderPath() {
581 String path = mLocalFolder.getStoragePath();
582 if (path != null && path.length() > 0) {
583 return path;
584 }
585 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
586 }
587 }