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
.services
.OperationsService
;
38 import com
.owncloud
.android
.utils
.FileStorageUtils
;
41 import java
.util
.ArrayList
;
42 import java
.util
.HashMap
;
43 import java
.util
.List
;
45 import java
.util
.Vector
;
46 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
48 //import android.support.v4.content.LocalBroadcastManager;
52 * Remote operation performing the synchronization of the list of files contained
53 * in a folder identified with its remote path.
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.
58 * Does NOT enter in the child folders to synchronize their contents also.
60 * @author David A. Velasco
62 public class SynchronizeFolderOperation
extends SyncOperation
{
64 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
66 /** Time stamp for the synchronization process in progress */
67 private long mCurrentSyncTime
;
69 /** Remote path of the folder to synchronize */
70 private String mRemotePath
;
72 /** Account where the file to synchronize belongs */
73 private Account mAccount
;
75 /** Android context; necessary to send requests to the download service */
76 private Context mContext
;
78 /** Locally cached information about folder to synchronize */
79 private OCFile mLocalFolder
;
81 /** Files and folders contained in the synchronized folder after a successful operation */
82 //private List<OCFile> mChildren;
84 /** Counter of conflicts found between local and remote files */
85 private int mConflictsFound
;
87 /** Counter of failed operations in synchronization of kept-in-sync files */
88 private int mFailsInFileSyncsFound
;
90 /** 'True' means that the remote folder changed and should be fetched */
91 private boolean mRemoteFolderChanged
;
93 private List
<OCFile
> mFilesForDirectDownload
;
94 // to avoid extra PROPFINDs when there was no change in the folder
96 private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
;
97 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
99 private List
<SyncOperation
> mFavouriteFilesToSyncContents
;
100 // this will be used for every file when 'folder synchronization' replaces 'folder download'
102 private final AtomicBoolean mCancellationRequested
;
105 * Creates a new instance of {@link SynchronizeFolderOperation}.
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.
112 public SynchronizeFolderOperation(Context context
, String remotePath
, Account account
, long currentSyncTime
){
113 mRemotePath
= remotePath
;
114 mCurrentSyncTime
= currentSyncTime
;
117 mRemoteFolderChanged
= false
;
118 mFilesForDirectDownload
= new Vector
<OCFile
>();
119 mFilesToSyncContentsWithoutUpload
= new Vector
<SyncOperation
>();
120 mFavouriteFilesToSyncContents
= new Vector
<SyncOperation
>();
121 mCancellationRequested
= new AtomicBoolean(false
);
125 public int getConflictsFound() {
126 return mConflictsFound
;
129 public int getFailsInFileSyncsFound() {
130 return mFailsInFileSyncsFound
;
134 * Performs the synchronization.
139 protected RemoteOperationResult
run(OwnCloudClient client
) {
140 RemoteOperationResult result
= null
;
141 mFailsInFileSyncsFound
= 0;
145 // get locally cached information about folder
146 mLocalFolder
= getStorageManager().getFileByPath(mRemotePath
);
148 result
= checkForChanges(client
);
150 if (result
.isSuccess()) {
151 if (mRemoteFolderChanged
) {
152 result
= fetchAndSyncRemoteFolder(client
);
155 prepareOpsFromLocalKnowledge();
158 if (result
.isSuccess()) {
159 syncContents(client
);
162 if (mFilesForDirectDownload
.isEmpty()) {
163 sendBroadcastForNotifyingUIUpdate(result
.isSuccess());
167 if (mCancellationRequested
.get()) {
168 throw new OperationCancelledException();
171 } catch (OperationCancelledException e
) {
172 result
= new RemoteOperationResult(e
);
174 // Needed in case that cancellation occurs before starting any download.
175 // If not, yellow arrow continues being shown.
176 sendBroadcastForNotifyingUIUpdate(false
);
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 if (mCancellationRequested
.get()) {
304 throw new OperationCancelledException();
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
);
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());
321 /// retrieve local data for the read file
322 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
323 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
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()
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");
347 remoteFile
.setPublicLink(localFile
.getPublicLink());
348 remoteFile
.setShareByLink(localFile
.isShareByLink());
350 // remote eTag will not be updated unless contents are synchronized
351 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
352 remoteFile
.setEtag("");
355 /// check and fix, if needed, local storage path
356 searchForLocalFileInDefaultPath(remoteFile
);
358 /// classify file to sync/download contents later
359 if (remoteFile
.isFolder()) {
360 /// to download children files recursively
361 startSyncFolderOperation(remoteFile
.getRemotePath());
363 if (mCancellationRequested
.get()) {
364 throw new OperationCancelledException();
367 } else if (remoteFile
.keepInSync()) {
368 /// prepare content synchronization for kept-in-sync files
369 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
376 mFavouriteFilesToSyncContents
.add(operation
);
379 /// prepare limited synchronization for regular files
380 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
388 mFilesToSyncContentsWithoutUpload
.add(operation
);
391 updatedFiles
.add(remoteFile
);
394 // save updated contents in local database
395 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
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();
412 /// prepare limited synchronization for regular files
413 if (!child
.isDown()) {
414 mFilesForDirectDownload
.add(child
);
421 private void syncContents(OwnCloudClient client
) throws OperationCancelledException
{
422 startDirectDownloads();
423 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
424 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
428 private void startDirectDownloads() throws OperationCancelledException
{
429 for (OCFile file
: mFilesForDirectDownload
) {
430 if (mCancellationRequested
.get()) {
431 throw new OperationCancelledException();
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
);
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.
444 * If download or upload is needed, request the operation to the corresponding service and goes
447 * @param filesToSyncContents Synchronization operations to execute.
448 * @param client Interface to the remote ownCloud server.
450 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
)
451 throws OperationCancelledException
{
453 RemoteOperationResult contentsResult
= null
;
454 for (SyncOperation op
: filesToSyncContents
) {
455 if (mCancellationRequested
.get()) {
456 throw new OperationCancelledException();
458 contentsResult
= op
.execute(getStorageManager(), mContext
);
459 if (!contentsResult
.isSuccess()) {
460 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
463 mFailsInFileSyncsFound
++;
464 if (contentsResult
.getException() != null
) {
465 Log_OC
.e(TAG
, "Error while synchronizing file : "
466 + contentsResult
.getLogMessage(), contentsResult
.getException());
468 Log_OC
.e(TAG
, "Error while synchronizing file : "
469 + contentsResult
.getLogMessage());
472 // TODO - use the errors count in notifications
473 } // won't let these fails break the synchronization process
479 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
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.
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());
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
502 * @param file File to associate a possible 'lost' local file.
504 private void searchForLocalFileInDefaultPath(OCFile file
) {
505 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
506 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
508 file
.setStoragePath(f
.getAbsolutePath());
509 file
.setLastSyncDateForData(f
.lastModified());
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
);
528 public void cancel() {
529 mCancellationRequested
.set(true
);
532 public String
getFolderPath() {
533 String path
= mLocalFolder
.getStoragePath();
534 if (path
!= null
&& path
.length() > 0) {
537 return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
);
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
);