Fix. Subfolders are not cancelled correctly
[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.services.OperationsService;
38 import com.owncloud.android.utils.FileStorageUtils;
39
40 import java.io.File;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Vector;
46 import java.util.concurrent.atomic.AtomicBoolean;
47
48 //import android.support.v4.content.LocalBroadcastManager;
49
50
51 /**
52 * Remote operation performing the synchronization of the list of files contained
53 * in a folder identified with its remote path.
54 *
55 * Fetches the list and properties of the files contained in the given folder, including their
56 * properties, and updates the local database with them.
57 *
58 * Does NOT enter in the child folders to synchronize their contents also.
59 *
60 * @author David A. Velasco
61 */
62 public class SynchronizeFolderOperation extends SyncOperation {
63
64 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
65
66 /** Time stamp for the synchronization process in progress */
67 private long mCurrentSyncTime;
68
69 /** Remote path of the folder to synchronize */
70 private String mRemotePath;
71
72 /** Account where the file to synchronize belongs */
73 private Account mAccount;
74
75 /** Android context; necessary to send requests to the download service */
76 private Context mContext;
77
78 /** Locally cached information about folder to synchronize */
79 private OCFile mLocalFolder;
80
81 /** Files and folders contained in the synchronized folder after a successful operation */
82 //private List<OCFile> mChildren;
83
84 /** Counter of conflicts found between local and remote files */
85 private int mConflictsFound;
86
87 /** Counter of failed operations in synchronization of kept-in-sync files */
88 private int mFailsInFileSyncsFound;
89
90 /** 'True' means that the remote folder changed and should be fetched */
91 private boolean mRemoteFolderChanged;
92
93 private List<OCFile> mFilesForDirectDownload;
94 // to avoid extra PROPFINDs when there was no change in the folder
95
96 private List<SyncOperation> mFilesToSyncContentsWithoutUpload;
97 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
98
99 private List<SyncOperation> mFavouriteFilesToSyncContents;
100 // this will be used for every file when 'folder synchronization' replaces 'folder download'
101
102 private final AtomicBoolean mCancellationRequested;
103
104 /**
105 * Creates a new instance of {@link SynchronizeFolderOperation}.
106 *
107 * @param context Application context.
108 * @param remotePath Path to synchronize.
109 * @param account ownCloud account where the folder is located.
110 * @param currentSyncTime Time stamp for the synchronization process in progress.
111 */
112 public SynchronizeFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){
113 mRemotePath = remotePath;
114 mCurrentSyncTime = currentSyncTime;
115 mAccount = account;
116 mContext = context;
117 mRemoteFolderChanged = false;
118 mFilesForDirectDownload = new Vector<OCFile>();
119 mFilesToSyncContentsWithoutUpload = new Vector<SyncOperation>();
120 mFavouriteFilesToSyncContents = new Vector<SyncOperation>();
121 mCancellationRequested = new AtomicBoolean(false);
122 }
123
124
125 public int getConflictsFound() {
126 return mConflictsFound;
127 }
128
129 public int getFailsInFileSyncsFound() {
130 return mFailsInFileSyncsFound;
131 }
132
133 /**
134 * Performs the synchronization.
135 *
136 * {@inheritDoc}
137 */
138 @Override
139 protected RemoteOperationResult run(OwnCloudClient client) {
140 RemoteOperationResult result = null;
141 mFailsInFileSyncsFound = 0;
142 mConflictsFound = 0;
143
144 try {
145 // get locally cached information about folder
146 mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
147
148 result = checkForChanges(client);
149
150 if (result.isSuccess()) {
151 if (mRemoteFolderChanged) {
152 result = fetchAndSyncRemoteFolder(client);
153
154 } else {
155 prepareOpsFromLocalKnowledge();
156 }
157
158 if (result.isSuccess()) {
159 syncContents(client);
160 }
161
162 if (mFilesForDirectDownload.isEmpty()) {
163 sendBroadcastForNotifyingUIUpdate(result.isSuccess());
164 }
165 }
166
167 if (mCancellationRequested.get()) {
168 throw new OperationCancelledException();
169 }
170
171 } catch (OperationCancelledException e) {
172 result = new RemoteOperationResult(e);
173
174 // Needed in case that cancellation occurs before starting any download.
175 // If not, yellow arrow continues being shown.
176 sendBroadcastForNotifyingUIUpdate(false);
177
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 if (mCancellationRequested.get()) {
304 throw new OperationCancelledException();
305 }
306
307 // get current data about local contents of the folder to synchronize
308 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder);
309 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
310 for (OCFile file : localFiles) {
311 localFilesMap.put(file.getRemotePath(), file);
312 }
313
314 // loop to synchronize every child
315 OCFile remoteFile = null, localFile = null;
316 for (int i=1; i<folderAndFiles.size(); i++) {
317 /// new OCFile instance with the data from the server
318 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
319 remoteFile.setParentId(mLocalFolder.getFileId());
320
321 /// retrieve local data for the read file
322 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
323 localFile = localFilesMap.remove(remoteFile.getRemotePath());
324
325 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
326 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
327 if (localFile != null) {
328 // some properties of local state are kept unmodified
329 remoteFile.setFileId(localFile.getFileId());
330 remoteFile.setKeepInSync(localFile.keepInSync());
331 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
332 remoteFile.setModificationTimestampAtLastSyncForData(
333 localFile.getModificationTimestampAtLastSyncForData()
334 );
335 remoteFile.setStoragePath(localFile.getStoragePath());
336 // eTag will not be updated unless contents are synchronized
337 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
338 remoteFile.setEtag(localFile.getEtag());
339 if (remoteFile.isFolder()) {
340 remoteFile.setFileLength(localFile.getFileLength());
341 // TODO move operations about size of folders to FileContentProvider
342 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
343 remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
344 remoteFile.setNeedsUpdateThumbnail(true);
345 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
346 }
347 remoteFile.setPublicLink(localFile.getPublicLink());
348 remoteFile.setShareByLink(localFile.isShareByLink());
349 } else {
350 // remote eTag will not be updated unless contents are synchronized
351 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
352 remoteFile.setEtag("");
353 }
354
355 /// check and fix, if needed, local storage path
356 searchForLocalFileInDefaultPath(remoteFile);
357
358 /// classify file to sync/download contents later
359 if (remoteFile.isFolder()) {
360 /// to download children files recursively
361 startSyncFolderOperation(remoteFile.getRemotePath());
362
363 if (mCancellationRequested.get()) {
364 throw new OperationCancelledException();
365 }
366
367 } else if (remoteFile.keepInSync()) {
368 /// prepare content synchronization for kept-in-sync files
369 SynchronizeFileOperation operation = new SynchronizeFileOperation(
370 localFile,
371 remoteFile,
372 mAccount,
373 true,
374 mContext
375 );
376 mFavouriteFilesToSyncContents.add(operation);
377
378 } else {
379 /// prepare limited synchronization for regular files
380 SynchronizeFileOperation operation = new SynchronizeFileOperation(
381 localFile,
382 remoteFile,
383 mAccount,
384 true,
385 false,
386 mContext
387 );
388 mFilesToSyncContentsWithoutUpload.add(operation);
389 }
390
391 updatedFiles.add(remoteFile);
392 }
393
394 // save updated contents in local database
395 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
396
397 }
398
399
400 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
401 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder);
402 for (OCFile child : children) {
403 /// classify file to sync/download contents later
404 if (child.isFolder()) {
405 /// to download children files recursively
406 startSyncFolderOperation(child.getRemotePath());
407 if (mCancellationRequested.get()) {
408 throw new OperationCancelledException();
409 }
410
411 } else {
412 /// prepare limited synchronization for regular files
413 if (!child.isDown()) {
414 mFilesForDirectDownload.add(child);
415 }
416 }
417 }
418 }
419
420
421 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
422 startDirectDownloads();
423 startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client);
424 startContentSynchronizations(mFavouriteFilesToSyncContents, client);
425 }
426
427
428 private void startDirectDownloads() throws OperationCancelledException {
429 for (OCFile file : mFilesForDirectDownload) {
430 if (mCancellationRequested.get()) {
431 throw new OperationCancelledException();
432 }
433 Intent i = new Intent(mContext, FileDownloader.class);
434 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
435 i.putExtra(FileDownloader.EXTRA_FILE, file);
436 mContext.startService(i);
437 }
438 }
439
440 /**
441 * Performs a list of synchronization operations, determining if a download or upload is needed
442 * or if exists conflict due to changes both in local and remote contents of the each file.
443 *
444 * If download or upload is needed, request the operation to the corresponding service and goes
445 * on.
446 *
447 * @param filesToSyncContents Synchronization operations to execute.
448 * @param client Interface to the remote ownCloud server.
449 */
450 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents, OwnCloudClient client)
451 throws OperationCancelledException {
452
453 RemoteOperationResult contentsResult = null;
454 for (SyncOperation op: filesToSyncContents) {
455 if (mCancellationRequested.get()) {
456 throw new OperationCancelledException();
457 }
458 contentsResult = op.execute(getStorageManager(), mContext);
459 if (!contentsResult.isSuccess()) {
460 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
461 mConflictsFound++;
462 } else {
463 mFailsInFileSyncsFound++;
464 if (contentsResult.getException() != null) {
465 Log_OC.e(TAG, "Error while synchronizing file : "
466 + contentsResult.getLogMessage(), contentsResult.getException());
467 } else {
468 Log_OC.e(TAG, "Error while synchronizing file : "
469 + contentsResult.getLogMessage());
470 }
471 }
472 // TODO - use the errors count in notifications
473 } // won't let these fails break the synchronization process
474 }
475 }
476
477
478 /**
479 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
480 *
481 * @param remote remote file read from the server (remote file or folder).
482 * @return New OCFile instance representing the remote resource described by we.
483 */
484 private OCFile fillOCFile(RemoteFile remote) {
485 OCFile file = new OCFile(remote.getRemotePath());
486 file.setCreationTimestamp(remote.getCreationTimestamp());
487 file.setFileLength(remote.getLength());
488 file.setMimetype(remote.getMimeType());
489 file.setModificationTimestamp(remote.getModifiedTimestamp());
490 file.setEtag(remote.getEtag());
491 file.setPermissions(remote.getPermissions());
492 file.setRemoteId(remote.getRemoteId());
493 return file;
494 }
495
496
497 /**
498 * Scans the default location for saving local copies of files searching for
499 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
500 * parameter.
501 *
502 * @param file File to associate a possible 'lost' local file.
503 */
504 private void searchForLocalFileInDefaultPath(OCFile file) {
505 if (file.getStoragePath() == null && !file.isFolder()) {
506 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
507 if (f.exists()) {
508 file.setStoragePath(f.getAbsolutePath());
509 file.setLastSyncDateForData(f.lastModified());
510 }
511 }
512 }
513
514 private void sendBroadcastForNotifyingUIUpdate(boolean result) {
515 // Send a broadcast message for notifying UI update
516 Intent uiUpdate = new Intent(FileDownloader.getDownloadFinishMessage());
517 uiUpdate.putExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, result);
518 uiUpdate.putExtra(FileDownloader.ACCOUNT_NAME, mAccount.name);
519 uiUpdate.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mRemotePath);
520 uiUpdate.putExtra(FileDownloader.EXTRA_FILE_PATH, mLocalFolder.getRemotePath());
521 mContext.sendStickyBroadcast(uiUpdate);
522 }
523
524
525 /**
526 * Cancel operation
527 */
528 public void cancel() {
529 mCancellationRequested.set(true);
530 }
531
532 public String getFolderPath() {
533 String path = mLocalFolder.getStoragePath();
534 if (path != null && path.length() > 0) {
535 return path;
536 }
537 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
538 }
539
540 private void startSyncFolderOperation(String path){
541 Intent intent = new Intent(mContext, OperationsService.class);
542 intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
543 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
544 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
545 mContext.startService(intent);
546 }
547 }