1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
18 package com
.owncloud
.android
.operations
;
20 import android
.accounts
.Account
;
21 import android
.content
.Context
;
22 import android
.content
.Intent
;
23 import android
.util
.Log
;
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
;
40 import java
.util
.ArrayList
;
41 import java
.util
.HashMap
;
42 import java
.util
.List
;
44 import java
.util
.Vector
;
45 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
47 //import android.support.v4.content.LocalBroadcastManager;
51 * Remote operation performing the synchronization of the list of files contained
52 * in a folder identified with its remote path.
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.
57 * Does NOT enter in the child folders to synchronize their contents also.
59 * @author David A. Velasco
61 public class SynchronizeFolderOperation
extends SyncOperation
{
63 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
65 /** Time stamp for the synchronization process in progress */
66 private long mCurrentSyncTime
;
68 /** Remote path of the folder to synchronize */
69 private String mRemotePath
;
71 /** Account where the file to synchronize belongs */
72 private Account mAccount
;
74 /** Android context; necessary to send requests to the download service */
75 private Context mContext
;
77 /** Locally cached information about folder to synchronize */
78 private OCFile mLocalFolder
;
80 /** Files and folders contained in the synchronized folder after a successful operation */
81 //private List<OCFile> mChildren;
83 /** Counter of conflicts found between local and remote files */
84 private int mConflictsFound
;
86 /** Counter of failed operations in synchronization of kept-in-sync files */
87 private int mFailsInFileSyncsFound
;
89 /** 'True' means that the remote folder changed and should be fetched */
90 private boolean mRemoteFolderChanged
;
92 private List
<OCFile
> mFilesForDirectDownload
;
93 // to avoid extra PROPFINDs when there was no change in the folder
95 private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
;
96 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
98 private List
<SyncOperation
> mFavouriteFilesToSyncContents
;
99 // this will be used for every file when 'folder synchronization' replaces 'folder download'
101 private List
<SyncOperation
> mFoldersToWalkDown
;
103 private final AtomicBoolean mCancellationRequested
;
106 * Creates a new instance of {@link SynchronizeFolderOperation}.
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.
113 public SynchronizeFolderOperation(Context context
, String remotePath
, Account account
, long currentSyncTime
){
114 mRemotePath
= remotePath
;
115 mCurrentSyncTime
= currentSyncTime
;
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
);
127 public int getConflictsFound() {
128 return mConflictsFound
;
131 public int getFailsInFileSyncsFound() {
132 return mFailsInFileSyncsFound
;
136 * Performs the synchronization.
141 protected RemoteOperationResult
run(OwnCloudClient client
) {
142 RemoteOperationResult result
= null
;
143 mFailsInFileSyncsFound
= 0;
147 // get locally cached information about folder
148 mLocalFolder
= getStorageManager().getFileByPath(mRemotePath
);
150 result
= checkForChanges(client
);
152 if (result
.isSuccess()) {
153 if (mRemoteFolderChanged
) {
154 result
= fetchAndSyncRemoteFolder(client
);
157 prepareOpsFromLocalKnowledge();
160 if (result
.isSuccess()) {
161 syncContents(client
);
164 if (mFilesForDirectDownload
.isEmpty()) {
165 sendBroadcastForNotifyingUIUpdate(result
.isSuccess());
169 if (mCancellationRequested
.get()) {
170 throw new OperationCancelledException();
173 } catch (OperationCancelledException e
) {
174 result
= new RemoteOperationResult(e
);
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
);
189 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) throws OperationCancelledException
{
190 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
192 mRemoteFolderChanged
= true
;
193 RemoteOperationResult result
= null
;
195 if (mCancellationRequested
.get()) {
196 throw new OperationCancelledException();
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));
205 // check if remote and local folder are different
206 mRemoteFolderChanged
=
207 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
209 result
= new RemoteOperationResult(ResultCode
.OK
);
211 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
212 (mRemoteFolderChanged ?
"changed" : "not changed"));
216 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
219 if (result
.isException()) {
220 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
221 result
.getLogMessage(), result
.getException());
223 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
224 result
.getLogMessage());
227 sendBroadcastForNotifyingUIUpdate(result
.isSuccess());
234 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) throws OperationCancelledException
{
235 if (mCancellationRequested
.get()) {
236 throw new OperationCancelledException();
239 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
240 RemoteOperationResult result
= operation
.execute(client
);
241 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
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
250 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
259 private void removeLocalFolder() {
260 FileDataStorageManager storageManager
= getStorageManager();
261 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
262 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
263 storageManager
.removeFolder(
266 ( mLocalFolder
.isDown() && // TODO: debug, I think this is always false for folders
267 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
275 * Synchronizes the data retrieved from the server about the contents of the target folder
276 * with the current data in the local database.
278 * Grants that mChildren is updated with fresh data after execution.
280 * @param folderAndFiles Remote folder and children files in Folder
282 * @param client Client instance to the remote server where the data were
284 * @return 'True' when any change was made in the local data, 'false' otherwise
286 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
)
287 throws OperationCancelledException
{
288 FileDataStorageManager storageManager
= getStorageManager();
290 // parse data from remote folder
291 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
292 remoteFolder
.setParentId(mLocalFolder
.getParentId());
293 remoteFolder
.setFileId(mLocalFolder
.getFileId());
295 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
296 + " changed - starting update of local data ");
298 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
299 mFilesForDirectDownload
.clear();
300 mFilesToSyncContentsWithoutUpload
.clear();
301 mFavouriteFilesToSyncContents
.clear();
303 synchronized(mFoldersToWalkDown
) {
304 if (mCancellationRequested
.get()) {
305 throw new OperationCancelledException();
307 mFoldersToWalkDown
.clear();
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
);
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());
324 /// retrieve local data for the read file
325 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
326 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
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()
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");
350 remoteFile
.setPublicLink(localFile
.getPublicLink());
351 remoteFile
.setShareByLink(localFile
.isShareByLink());
353 // remote eTag will not be updated unless contents are synchronized
354 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
355 remoteFile
.setEtag("");
358 /// check and fix, if needed, local storage path
359 searchForLocalFileInDefaultPath(remoteFile
);
361 /// classify file to sync/download contents later
362 if (remoteFile
.isFolder()) {
363 /// to download children files recursively
364 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation(
366 remoteFile
.getRemotePath(),
371 synchronized(mFoldersToWalkDown
) {
372 if (mCancellationRequested
.get()) {
373 throw new OperationCancelledException();
375 mFoldersToWalkDown
.add(synchFolderOp
);
378 } else if (remoteFile
.keepInSync()) {
379 /// prepare content synchronization for kept-in-sync files
380 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
387 mFavouriteFilesToSyncContents
.add(operation
);
390 /// prepare limited synchronization for regular files
391 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
399 mFilesToSyncContentsWithoutUpload
.add(operation
);
402 updatedFiles
.add(remoteFile
);
405 // save updated contents in local database
406 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
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(
419 child
.getRemotePath(),
424 synchronized(mFoldersToWalkDown
) {
425 if (mCancellationRequested
.get()) {
426 throw new OperationCancelledException();
428 mFoldersToWalkDown
.add(synchFolderOp
);
432 /// prepare limited synchronization for regular files
433 if (!child
.isDown()) {
434 mFilesForDirectDownload
.add(child
);
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!
449 private void startDirectDownloads() throws OperationCancelledException
{
450 for (OCFile file
: mFilesForDirectDownload
) {
451 if (mCancellationRequested
.get()) {
452 throw new OperationCancelledException();
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
);
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.
465 * If download or upload is needed, request the operation to the corresponding service and goes
468 * @param filesToSyncContents Synchronization operations to execute.
469 * @param client Interface to the remote ownCloud server.
471 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
)
472 throws OperationCancelledException
{
474 RemoteOperationResult contentsResult
= null
;
475 for (SyncOperation op
: filesToSyncContents
) {
476 if (mCancellationRequested
.get()) {
477 throw new OperationCancelledException();
479 contentsResult
= op
.execute(getStorageManager(), mContext
);
480 if (!contentsResult
.isSuccess()) {
481 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
484 mFailsInFileSyncsFound
++;
485 if (contentsResult
.getException() != null
) {
486 Log_OC
.e(TAG
, "Error while synchronizing file : "
487 + contentsResult
.getLogMessage(), contentsResult
.getException());
489 Log_OC
.e(TAG
, "Error while synchronizing file : "
490 + contentsResult
.getLogMessage());
493 // TODO - use the errors count in notifications
494 } // won't let these fails break the synchronization process
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();
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());
512 Log_OC
.e(TAG
, "Non blocking error : " + contentsResult
.getLogMessage());
514 } // won't let these fails break the synchronization process
520 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
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.
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());
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
543 * @param file File to associate a possible 'lost' local file.
545 private void searchForLocalFileInDefaultPath(OCFile file
) {
546 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
547 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
549 file
.setStoragePath(f
.getAbsolutePath());
550 file
.setLastSyncDateForData(f
.lastModified());
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
);
569 public void cancel() {
570 mCancellationRequested
.set(true
);
572 synchronized(mFoldersToWalkDown
) {
573 // cancel 'child' synchronizations
574 for (SyncOperation synchOp
: mFoldersToWalkDown
) {
575 ((SynchronizeFolderOperation
) synchOp
).cancel();
580 public String
getFolderPath() {
581 String path
= mLocalFolder
.getStoragePath();
582 if (path
!= null
&& path
.length() > 0) {
585 return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
);