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 // Send a broadcast message for notifying UI update
166 Intent uiUpdate
= new Intent(FileDownloader
.getDownloadFinishMessage());
167 uiUpdate
.putExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, result
.isSuccess());
168 uiUpdate
.putExtra(FileDownloader
.ACCOUNT_NAME
, mAccount
.name
);
169 uiUpdate
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mRemotePath
);
170 uiUpdate
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mLocalFolder
.getRemotePath());
171 mContext
.sendStickyBroadcast(uiUpdate
);
174 } catch (OperationCancelledException e
) {
175 result
= new RemoteOperationResult(e
);
177 // cancel 'child' synchronizations
178 for (SyncOperation synchOp
: mFoldersToWalkDown
) {
179 ((SynchronizeFolderOperation
) synchOp
).cancel();
187 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) throws OperationCancelledException
{
188 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
190 mRemoteFolderChanged
= true
;
191 RemoteOperationResult result
= null
;
193 if (mCancellationRequested
.get()) {
194 throw new OperationCancelledException();
198 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mRemotePath
);
199 result
= operation
.execute(client
);
200 if (result
.isSuccess()){
201 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
203 // check if remote and local folder are different
204 mRemoteFolderChanged
=
205 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
207 result
= new RemoteOperationResult(ResultCode
.OK
);
209 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
210 (mRemoteFolderChanged ?
"changed" : "not changed"));
214 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
217 if (result
.isException()) {
218 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
219 result
.getLogMessage(), result
.getException());
221 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
222 result
.getLogMessage());
230 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) throws OperationCancelledException
{
231 if (mCancellationRequested
.get()) {
232 throw new OperationCancelledException();
235 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
236 RemoteOperationResult result
= operation
.execute(client
);
237 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
239 if (result
.isSuccess()) {
240 synchronizeData(result
.getData(), client
);
241 if (mConflictsFound
> 0 || mFailsInFileSyncsFound
> 0) {
242 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
243 // should be a different result code, but will do the job
246 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
255 private void removeLocalFolder() {
256 FileDataStorageManager storageManager
= getStorageManager();
257 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
258 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
259 storageManager
.removeFolder(
262 ( mLocalFolder
.isDown() && // TODO: debug, I think this is always false for folders
263 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
271 * Synchronizes the data retrieved from the server about the contents of the target folder
272 * with the current data in the local database.
274 * Grants that mChildren is updated with fresh data after execution.
276 * @param folderAndFiles Remote folder and children files in Folder
278 * @param client Client instance to the remote server where the data were
280 * @return 'True' when any change was made in the local data, 'false' otherwise
282 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
283 FileDataStorageManager storageManager
= getStorageManager();
285 // parse data from remote folder
286 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
287 remoteFolder
.setParentId(mLocalFolder
.getParentId());
288 remoteFolder
.setFileId(mLocalFolder
.getFileId());
290 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
291 + " changed - starting update of local data ");
293 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
294 mFilesForDirectDownload
.clear();
295 mFilesToSyncContentsWithoutUpload
.clear();
296 mFavouriteFilesToSyncContents
.clear();
297 mFoldersToWalkDown
.clear();
299 // get current data about local contents of the folder to synchronize
300 List
<OCFile
> localFiles
= storageManager
.getFolderContent(mLocalFolder
);
301 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
302 for (OCFile file
: localFiles
) {
303 localFilesMap
.put(file
.getRemotePath(), file
);
306 // loop to synchronize every child
307 OCFile remoteFile
= null
, localFile
= null
;
308 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
309 /// new OCFile instance with the data from the server
310 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
311 remoteFile
.setParentId(mLocalFolder
.getFileId());
313 /// retrieve local data for the read file
314 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
315 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
317 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
318 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
319 if (localFile
!= null
) {
320 // some properties of local state are kept unmodified
321 remoteFile
.setFileId(localFile
.getFileId());
322 remoteFile
.setKeepInSync(localFile
.keepInSync());
323 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
324 remoteFile
.setModificationTimestampAtLastSyncForData(
325 localFile
.getModificationTimestampAtLastSyncForData()
327 remoteFile
.setStoragePath(localFile
.getStoragePath());
328 // eTag will not be updated unless contents are synchronized
329 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
330 remoteFile
.setEtag(localFile
.getEtag());
331 if (remoteFile
.isFolder()) {
332 remoteFile
.setFileLength(localFile
.getFileLength());
333 // TODO move operations about size of folders to FileContentProvider
334 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
335 remoteFile
.getModificationTimestamp() != localFile
.getModificationTimestamp()) {
336 remoteFile
.setNeedsUpdateThumbnail(true
);
337 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
339 remoteFile
.setPublicLink(localFile
.getPublicLink());
340 remoteFile
.setShareByLink(localFile
.isShareByLink());
342 // remote eTag will not be updated unless contents are synchronized
343 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
344 remoteFile
.setEtag("");
347 /// check and fix, if needed, local storage path
348 searchForLocalFileInDefaultPath(remoteFile
);
350 /// classify file to sync/download contents later
351 if (remoteFile
.isFolder()) {
352 /// to download children files recursively
353 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation(
355 remoteFile
.getRemotePath(),
359 mFoldersToWalkDown
.add(synchFolderOp
);
361 } else if (remoteFile
.keepInSync()) {
362 /// prepare content synchronization for kept-in-sync files
363 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
370 mFavouriteFilesToSyncContents
.add(operation
);
373 /// prepare limited synchronization for regular files
374 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
382 mFilesToSyncContentsWithoutUpload
.add(operation
);
385 updatedFiles
.add(remoteFile
);
388 // save updated contents in local database
389 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
394 private void prepareOpsFromLocalKnowledge() {
395 List
<OCFile
> children
= getStorageManager().getFolderContent(mLocalFolder
);
396 for (OCFile child
: children
) {
397 /// classify file to sync/download contents later
398 if (child
.isFolder()) {
399 /// to download children files recursively
400 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation(
402 child
.getRemotePath(),
406 mFoldersToWalkDown
.add(synchFolderOp
);
409 /// prepare limited synchronization for regular files
410 if (!child
.isDown()) {
411 mFilesForDirectDownload
.add(child
);
418 private void syncContents(OwnCloudClient client
) throws OperationCancelledException
{
419 startDirectDownloads();
420 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
421 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
422 walkSubfolders(client
); // this must be the last!
426 private void startDirectDownloads() throws OperationCancelledException
{
427 for (OCFile file
: mFilesForDirectDownload
) {
428 if (mCancellationRequested
.get()) {
429 throw new OperationCancelledException();
431 Intent i
= new Intent(mContext
, FileDownloader
.class);
432 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
433 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
434 mContext
.startService(i
);
439 * Performs a list of synchronization operations, determining if a download or upload is needed
440 * or if exists conflict due to changes both in local and remote contents of the each file.
442 * If download or upload is needed, request the operation to the corresponding service and goes
445 * @param filesToSyncContents Synchronization operations to execute.
446 * @param client Interface to the remote ownCloud server.
448 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
)
449 throws OperationCancelledException
{
451 RemoteOperationResult contentsResult
= null
;
452 for (SyncOperation op
: filesToSyncContents
) {
453 if (mCancellationRequested
.get()) {
454 throw new OperationCancelledException();
456 contentsResult
= op
.execute(getStorageManager(), mContext
);
457 if (!contentsResult
.isSuccess()) {
458 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
461 mFailsInFileSyncsFound
++;
462 if (contentsResult
.getException() != null
) {
463 Log_OC
.e(TAG
, "Error while synchronizing file : "
464 + contentsResult
.getLogMessage(), contentsResult
.getException());
466 Log_OC
.e(TAG
, "Error while synchronizing file : "
467 + contentsResult
.getLogMessage());
470 // TODO - use the errors count in notifications
471 } // won't let these fails break the synchronization process
476 private void walkSubfolders(OwnCloudClient client
) throws OperationCancelledException
{
477 RemoteOperationResult contentsResult
= null
;
478 for (SyncOperation op
: mFoldersToWalkDown
) {
479 if (mCancellationRequested
.get()) {
480 throw new OperationCancelledException();
482 contentsResult
= op
.execute(client
, getStorageManager()); // to watch out: possibly deep recursion
483 if (!contentsResult
.isSuccess()) {
484 // TODO - some kind of error count, and use it with notifications
485 if (contentsResult
.getException() != null
) {
486 Log_OC
.e(TAG
, "Non blocking exception : "
487 + contentsResult
.getLogMessage(), contentsResult
.getException());
489 Log_OC
.e(TAG
, "Non blocking error : " + contentsResult
.getLogMessage());
491 } // won't let these fails break the synchronization process
497 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
499 * @param remote remote file read from the server (remote file or folder).
500 * @return New OCFile instance representing the remote resource described by we.
502 private OCFile
fillOCFile(RemoteFile remote
) {
503 OCFile file
= new OCFile(remote
.getRemotePath());
504 file
.setCreationTimestamp(remote
.getCreationTimestamp());
505 file
.setFileLength(remote
.getLength());
506 file
.setMimetype(remote
.getMimeType());
507 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
508 file
.setEtag(remote
.getEtag());
509 file
.setPermissions(remote
.getPermissions());
510 file
.setRemoteId(remote
.getRemoteId());
516 * Scans the default location for saving local copies of files searching for
517 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
520 * @param file File to associate a possible 'lost' local file.
522 private void searchForLocalFileInDefaultPath(OCFile file
) {
523 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
524 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
526 file
.setStoragePath(f
.getAbsolutePath());
527 file
.setLastSyncDateForData(f
.lastModified());
536 public void cancel() {
537 mCancellationRequested
.set(true
);