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