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