2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 package com
.owncloud
.android
.operations
;
23 import android
.accounts
.Account
;
24 import android
.content
.Context
;
25 import android
.content
.Intent
;
26 import android
.util
.Log
;
28 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
29 import com
.owncloud
.android
.datamodel
.OCFile
;
30 import com
.owncloud
.android
.files
.services
.FileDownloader
;
31 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
32 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
;
33 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
34 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
35 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
36 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
37 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
38 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
39 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
40 import com
.owncloud
.android
.services
.OperationsService
;
41 import com
.owncloud
.android
.utils
.FileStorageUtils
;
44 import java
.util
.ArrayList
;
45 import java
.util
.HashMap
;
46 import java
.util
.List
;
48 import java
.util
.Vector
;
49 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
51 //import android.support.v4.content.LocalBroadcastManager;
55 * Remote operation performing the synchronization of the list of files contained
56 * in a folder identified with its remote path.
58 * Fetches the list and properties of the files contained in the given folder, including their
59 * properties, and updates the local database with them.
61 * Does NOT enter in the child folders to synchronize their contents also.
63 public class SynchronizeFolderOperation
extends SyncOperation
{
65 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
67 /** Time stamp for the synchronization process in progress */
68 private long mCurrentSyncTime
;
70 /** Remote path of the folder to synchronize */
71 private String mRemotePath
;
73 /** Account where the file to synchronize belongs */
74 private Account mAccount
;
76 /** Android context; necessary to send requests to the download service */
77 private Context mContext
;
79 /** Locally cached information about folder to synchronize */
80 private OCFile mLocalFolder
;
82 /** Files and folders contained in the synchronized folder after a successful operation */
83 //private List<OCFile> mChildren;
85 /** Counter of conflicts found between local and remote files */
86 private int mConflictsFound
;
88 /** Counter of failed operations in synchronization of kept-in-sync files */
89 private int mFailsInFileSyncsFound
;
91 /** 'True' means that the remote folder changed and should be fetched */
92 private boolean mRemoteFolderChanged
;
94 private List
<OCFile
> mFilesForDirectDownload
;
95 // to avoid extra PROPFINDs when there was no change in the folder
97 private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
;
98 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
100 private List
<SyncOperation
> mFavouriteFilesToSyncContents
;
101 // this will be used for every file when 'folder synchronization' replaces 'folder download'
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 mCancellationRequested
= new AtomicBoolean(false
);
126 public int getConflictsFound() {
127 return mConflictsFound
;
130 public int getFailsInFileSyncsFound() {
131 return mFailsInFileSyncsFound
;
135 * Performs the synchronization.
140 protected RemoteOperationResult
run(OwnCloudClient client
) {
141 RemoteOperationResult result
= null
;
142 mFailsInFileSyncsFound
= 0;
146 // get locally cached information about folder
147 mLocalFolder
= getStorageManager().getFileByPath(mRemotePath
);
149 result
= checkForChanges(client
);
151 if (result
.isSuccess()) {
152 if (mRemoteFolderChanged
) {
153 result
= fetchAndSyncRemoteFolder(client
);
156 prepareOpsFromLocalKnowledge();
159 if (result
.isSuccess()) {
160 syncContents(client
);
165 if (mCancellationRequested
.get()) {
166 throw new OperationCancelledException();
169 } catch (OperationCancelledException e
) {
170 result
= new RemoteOperationResult(e
);
177 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) throws OperationCancelledException
{
178 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
180 mRemoteFolderChanged
= true
;
181 RemoteOperationResult result
= null
;
183 if (mCancellationRequested
.get()) {
184 throw new OperationCancelledException();
188 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mRemotePath
);
189 result
= operation
.execute(client
);
190 if (result
.isSuccess()){
191 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
193 // check if remote and local folder are different
194 mRemoteFolderChanged
=
195 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
197 result
= new RemoteOperationResult(ResultCode
.OK
);
199 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
200 (mRemoteFolderChanged ?
"changed" : "not changed"));
204 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
207 if (result
.isException()) {
208 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
209 result
.getLogMessage(), result
.getException());
211 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
212 result
.getLogMessage());
221 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) throws OperationCancelledException
{
222 if (mCancellationRequested
.get()) {
223 throw new OperationCancelledException();
226 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
227 RemoteOperationResult result
= operation
.execute(client
);
228 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
230 if (result
.isSuccess()) {
231 synchronizeData(result
.getData(), client
);
232 if (mConflictsFound
> 0 || mFailsInFileSyncsFound
> 0) {
233 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
234 // should be a different result code, but will do the job
237 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
246 private void removeLocalFolder() {
247 FileDataStorageManager storageManager
= getStorageManager();
248 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
249 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
250 storageManager
.removeFolder(
253 ( mLocalFolder
.isDown() && // TODO: debug, I think this is always false for folders
254 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
262 * Synchronizes the data retrieved from the server about the contents of the target folder
263 * with the current data in the local database.
265 * Grants that mChildren is updated with fresh data after execution.
267 * @param folderAndFiles Remote folder and children files in Folder
269 * @param client Client instance to the remote server where the data were
271 * @return 'True' when any change was made in the local data, 'false' otherwise
273 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
)
274 throws OperationCancelledException
{
275 FileDataStorageManager storageManager
= getStorageManager();
277 // parse data from remote folder
278 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
279 remoteFolder
.setParentId(mLocalFolder
.getParentId());
280 remoteFolder
.setFileId(mLocalFolder
.getFileId());
282 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
283 + " changed - starting update of local data ");
285 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
286 mFilesForDirectDownload
.clear();
287 mFilesToSyncContentsWithoutUpload
.clear();
288 mFavouriteFilesToSyncContents
.clear();
290 if (mCancellationRequested
.get()) {
291 throw new OperationCancelledException();
294 // get current data about local contents of the folder to synchronize
295 List
<OCFile
> localFiles
= storageManager
.getFolderContent(mLocalFolder
);
296 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
297 for (OCFile file
: localFiles
) {
298 localFilesMap
.put(file
.getRemotePath(), file
);
301 // loop to synchronize every child
302 OCFile remoteFile
= null
, localFile
= null
;
303 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
304 /// new OCFile instance with the data from the server
305 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
306 remoteFile
.setParentId(mLocalFolder
.getFileId());
308 /// retrieve local data for the read file
309 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
310 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
312 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
313 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
314 if (localFile
!= null
) {
315 // some properties of local state are kept unmodified
316 remoteFile
.setFileId(localFile
.getFileId());
317 remoteFile
.setKeepInSync(localFile
.keepInSync());
318 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
319 remoteFile
.setModificationTimestampAtLastSyncForData(
320 localFile
.getModificationTimestampAtLastSyncForData()
322 remoteFile
.setStoragePath(localFile
.getStoragePath());
323 // eTag will not be updated unless contents are synchronized
324 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
325 remoteFile
.setEtag(localFile
.getEtag());
326 if (remoteFile
.isFolder()) {
327 remoteFile
.setFileLength(localFile
.getFileLength());
328 // TODO move operations about size of folders to FileContentProvider
329 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
330 remoteFile
.getModificationTimestamp() != localFile
.getModificationTimestamp()) {
331 remoteFile
.setNeedsUpdateThumbnail(true
);
332 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
334 remoteFile
.setPublicLink(localFile
.getPublicLink());
335 remoteFile
.setShareByLink(localFile
.isShareByLink());
337 // remote eTag will not be updated unless contents are synchronized
338 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
339 remoteFile
.setEtag("");
342 /// check and fix, if needed, local storage path
343 searchForLocalFileInDefaultPath(remoteFile
);
345 /// classify file to sync/download contents later
346 if (remoteFile
.isFolder()) {
347 /// to download children files recursively
348 synchronized(mCancellationRequested
) {
349 if (mCancellationRequested
.get()) {
350 throw new OperationCancelledException();
352 startSyncFolderOperation(remoteFile
.getRemotePath());
355 } else if (remoteFile
.keepInSync()) {
356 /// prepare content synchronization for kept-in-sync files
357 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
364 mFavouriteFilesToSyncContents
.add(operation
);
367 /// prepare limited synchronization for regular files
368 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
376 mFilesToSyncContentsWithoutUpload
.add(operation
);
379 updatedFiles
.add(remoteFile
);
382 // save updated contents in local database
383 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
388 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException
{
389 List
<OCFile
> children
= getStorageManager().getFolderContent(mLocalFolder
);
390 for (OCFile child
: children
) {
391 /// classify file to sync/download contents later
392 if (child
.isFolder()) {
393 /// to download children files recursively
394 synchronized(mCancellationRequested
) {
395 if (mCancellationRequested
.get()) {
396 throw new OperationCancelledException();
398 startSyncFolderOperation(child
.getRemotePath());
402 /// prepare limited synchronization for regular files
403 if (!child
.isDown()) {
404 mFilesForDirectDownload
.add(child
);
411 private void syncContents(OwnCloudClient client
) throws OperationCancelledException
{
412 startDirectDownloads();
413 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
414 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
418 private void startDirectDownloads() throws OperationCancelledException
{
419 for (OCFile file
: mFilesForDirectDownload
) {
420 synchronized(mCancellationRequested
) {
421 if (mCancellationRequested
.get()) {
422 throw new OperationCancelledException();
424 Intent i
= new Intent(mContext
, FileDownloader
.class);
425 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
426 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
427 mContext
.startService(i
);
433 * Performs a list of synchronization operations, determining if a download or upload is needed
434 * or if exists conflict due to changes both in local and remote contents of the each file.
436 * If download or upload is needed, request the operation to the corresponding service and goes
439 * @param filesToSyncContents Synchronization operations to execute.
440 * @param client Interface to the remote ownCloud server.
442 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
)
443 throws OperationCancelledException
{
445 Log_OC
.v(TAG
, "Starting content synchronization... ");
446 RemoteOperationResult contentsResult
= null
;
447 for (SyncOperation op
: filesToSyncContents
) {
448 if (mCancellationRequested
.get()) {
449 throw new OperationCancelledException();
451 contentsResult
= op
.execute(getStorageManager(), mContext
);
452 if (!contentsResult
.isSuccess()) {
453 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
456 mFailsInFileSyncsFound
++;
457 if (contentsResult
.getException() != null
) {
458 Log_OC
.e(TAG
, "Error while synchronizing file : "
459 + contentsResult
.getLogMessage(), contentsResult
.getException());
461 Log_OC
.e(TAG
, "Error while synchronizing file : "
462 + contentsResult
.getLogMessage());
465 // TODO - use the errors count in notifications
466 } // won't let these fails break the synchronization process
472 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
474 * @param remote remote file read from the server (remote file or folder).
475 * @return New OCFile instance representing the remote resource described by we.
477 private OCFile
fillOCFile(RemoteFile remote
) {
478 OCFile file
= new OCFile(remote
.getRemotePath());
479 file
.setCreationTimestamp(remote
.getCreationTimestamp());
480 file
.setFileLength(remote
.getLength());
481 file
.setMimetype(remote
.getMimeType());
482 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
483 file
.setEtag(remote
.getEtag());
484 file
.setPermissions(remote
.getPermissions());
485 file
.setRemoteId(remote
.getRemoteId());
491 * Scans the default location for saving local copies of files searching for
492 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
495 * @param file File to associate a possible 'lost' local file.
497 private void searchForLocalFileInDefaultPath(OCFile file
) {
498 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
499 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
501 file
.setStoragePath(f
.getAbsolutePath());
502 file
.setLastSyncDateForData(f
.lastModified());
511 public void cancel() {
512 mCancellationRequested
.set(true
);
515 public String
getFolderPath() {
516 String path
= mLocalFolder
.getStoragePath();
517 if (path
!= null
&& path
.length() > 0) {
520 return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
);
523 private void startSyncFolderOperation(String path
){
524 Intent intent
= new Intent(mContext
, OperationsService
.class);
525 intent
.setAction(OperationsService
.ACTION_SYNC_FOLDER
);
526 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, mAccount
);
527 intent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, path
);
528 mContext
.startService(intent
);
531 public String
getRemotePath() {