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
.RemoteOperation
;
31 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
32 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
33 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
34 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
35 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
36 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
37 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
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
;
92 private final AtomicBoolean mCancellationRequested
= new AtomicBoolean(false
);
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 List
<SyncOperation
> mFoldersToWalkDown
;
107 * Creates a new instance of {@link SynchronizeFolderOperation}.
109 * @param context Application context.
110 * @param remotePath Path to synchronize.
111 * @param account ownCloud account where the folder is located.
112 * @param currentSyncTime Time stamp for the synchronization process in progress.
114 public SynchronizeFolderOperation(Context context
, String remotePath
, Account account
, long currentSyncTime
){
115 mRemotePath
= remotePath
;
116 mCurrentSyncTime
= currentSyncTime
;
119 mRemoteFolderChanged
= false
;
120 mFilesForDirectDownload
= new Vector
<OCFile
>();
121 mFilesToSyncContentsWithoutUpload
= new Vector
<SyncOperation
>();
122 mFavouriteFilesToSyncContents
= new Vector
<SyncOperation
>();
123 mFoldersToWalkDown
= new Vector
<SyncOperation
>();
128 public int getConflictsFound() {
129 return mConflictsFound
;
132 public int getFailsInFileSyncsFound() {
133 return mFailsInFileSyncsFound
;
137 * Performs the synchronization.
142 protected RemoteOperationResult
run(OwnCloudClient client
) {
143 RemoteOperationResult result
= null
;
144 mFailsInFileSyncsFound
= 0;
147 synchronized(mCancellationRequested
) {
148 if (mCancellationRequested
.get()) {
149 // Cancel each operation in mFoldersToWalkDown
150 for (SyncOperation synchOp
: mFoldersToWalkDown
) {
151 ((SynchronizeFolderOperation
) synchOp
).cancel();
153 return new RemoteOperationResult(new OperationCancelledException());
157 // get locally cached information about folder
158 mLocalFolder
= getStorageManager().getFileByPath(mRemotePath
);
160 result
= checkForChanges(client
);
162 if (result
.isSuccess()) {
163 if (mRemoteFolderChanged
) {
164 result
= fetchAndSyncRemoteFolder(client
);
167 prepareOpsFromLocalKnowledge();
170 if (result
.isSuccess()) {
171 syncContents(client
);
179 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
180 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
182 mRemoteFolderChanged
= true
;
183 RemoteOperationResult result
= null
;
186 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mRemotePath
);
187 result
= operation
.execute(client
);
188 if (result
.isSuccess()){
189 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
191 // check if remote and local folder are different
192 mRemoteFolderChanged
=
193 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
195 result
= new RemoteOperationResult(ResultCode
.OK
);
197 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
198 (mRemoteFolderChanged ?
"changed" : "not changed"));
202 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
205 if (result
.isException()) {
206 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
207 result
.getLogMessage(), result
.getException());
209 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
210 result
.getLogMessage());
218 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
219 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
220 RemoteOperationResult result
= operation
.execute(client
);
221 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
223 if (result
.isSuccess()) {
224 synchronizeData(result
.getData(), client
);
225 if (mConflictsFound
> 0 || mFailsInFileSyncsFound
> 0) {
226 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
227 // should be a different result code, but will do the job
230 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
239 private void removeLocalFolder() {
240 FileDataStorageManager storageManager
= getStorageManager();
241 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
242 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
243 storageManager
.removeFolder(
246 ( mLocalFolder
.isDown() && // TODO: debug, I think this is always false for folders
247 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
255 * Synchronizes the data retrieved from the server about the contents of the target folder
256 * with the current data in the local database.
258 * Grants that mChildren is updated with fresh data after execution.
260 * @param folderAndFiles Remote folder and children files in Folder
262 * @param client Client instance to the remote server where the data were
264 * @return 'True' when any change was made in the local data, 'false' otherwise
266 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
267 FileDataStorageManager storageManager
= getStorageManager();
269 // parse data from remote folder
270 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
271 remoteFolder
.setParentId(mLocalFolder
.getParentId());
272 remoteFolder
.setFileId(mLocalFolder
.getFileId());
274 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
275 + " changed - starting update of local data ");
277 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
278 mFilesForDirectDownload
.clear();
279 mFilesToSyncContentsWithoutUpload
.clear();
280 mFavouriteFilesToSyncContents
.clear();
281 mFoldersToWalkDown
.clear();
283 // get current data about local contents of the folder to synchronize
284 List
<OCFile
> localFiles
= storageManager
.getFolderContent(mLocalFolder
);
285 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
286 for (OCFile file
: localFiles
) {
287 localFilesMap
.put(file
.getRemotePath(), file
);
290 // loop to synchronize every child
291 OCFile remoteFile
= null
, localFile
= null
;
292 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
293 /// new OCFile instance with the data from the server
294 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
295 remoteFile
.setParentId(mLocalFolder
.getFileId());
297 /// retrieve local data for the read file
298 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
299 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
301 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
302 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
303 if (localFile
!= null
) {
304 // some properties of local state are kept unmodified
305 remoteFile
.setFileId(localFile
.getFileId());
306 remoteFile
.setKeepInSync(localFile
.keepInSync());
307 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
308 remoteFile
.setModificationTimestampAtLastSyncForData(
309 localFile
.getModificationTimestampAtLastSyncForData()
311 remoteFile
.setStoragePath(localFile
.getStoragePath());
312 // eTag will not be updated unless contents are synchronized
313 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
314 remoteFile
.setEtag(localFile
.getEtag());
315 if (remoteFile
.isFolder()) {
316 remoteFile
.setFileLength(localFile
.getFileLength());
317 // TODO move operations about size of folders to FileContentProvider
318 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
319 remoteFile
.getModificationTimestamp() != localFile
.getModificationTimestamp()) {
320 remoteFile
.setNeedsUpdateThumbnail(true
);
321 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
323 remoteFile
.setPublicLink(localFile
.getPublicLink());
324 remoteFile
.setShareByLink(localFile
.isShareByLink());
326 // remote eTag will not be updated unless contents are synchronized
327 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
328 remoteFile
.setEtag("");
331 /// check and fix, if needed, local storage path
332 searchForLocalFileInDefaultPath(remoteFile
);
334 /// classify file to sync/download contents later
335 if (remoteFile
.isFolder()) {
336 /// to download children files recursively
337 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation(
339 remoteFile
.getRemotePath(),
343 mFoldersToWalkDown
.add(synchFolderOp
);
345 } else if (remoteFile
.keepInSync()) {
346 /// prepare content synchronization for kept-in-sync files
347 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
354 mFavouriteFilesToSyncContents
.add(operation
);
357 /// prepare limited synchronization for regular files
358 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
366 mFilesToSyncContentsWithoutUpload
.add(operation
);
369 updatedFiles
.add(remoteFile
);
372 // save updated contents in local database
373 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
378 private void prepareOpsFromLocalKnowledge() {
379 List
<OCFile
> children
= getStorageManager().getFolderContent(mLocalFolder
);
380 for (OCFile child
: children
) {
381 /// classify file to sync/download contents later
382 if (child
.isFolder()) {
383 /// to download children files recursively
384 SynchronizeFolderOperation synchFolderOp
= new SynchronizeFolderOperation(
386 child
.getRemotePath(),
390 mFoldersToWalkDown
.add(synchFolderOp
);
393 /// prepare limited synchronization for regular files
394 if (!child
.isDown()) {
395 mFilesForDirectDownload
.add(child
);
402 private void syncContents(OwnCloudClient client
) {
403 startDirectDownloads();
404 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
405 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
406 walkSubfolders(client
); // this must be the last!
410 private void startDirectDownloads() {
411 for (OCFile file
: mFilesForDirectDownload
) {
412 Intent i
= new Intent(mContext
, FileDownloader
.class);
413 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
414 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
415 mContext
.startService(i
);
420 * Performs a list of synchronization operations, determining if a download or upload is needed
421 * or if exists conflict due to changes both in local and remote contents of the each file.
423 * If download or upload is needed, request the operation to the corresponding service and goes
426 * @param filesToSyncContents Synchronization operations to execute.
427 * @param client Interface to the remote ownCloud server.
429 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
) {
430 RemoteOperationResult contentsResult
= null
;
431 for (SyncOperation op
: filesToSyncContents
) {
432 contentsResult
= op
.execute(getStorageManager(), mContext
);
433 if (!contentsResult
.isSuccess()) {
434 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
437 mFailsInFileSyncsFound
++;
438 if (contentsResult
.getException() != null
) {
439 Log_OC
.e(TAG
, "Error while synchronizing file : "
440 + contentsResult
.getLogMessage(), contentsResult
.getException());
442 Log_OC
.e(TAG
, "Error while synchronizing file : "
443 + contentsResult
.getLogMessage());
446 // TODO - use the errors count in notifications
447 } // won't let these fails break the synchronization process
452 private void walkSubfolders(OwnCloudClient client
) {
453 RemoteOperationResult contentsResult
= null
;
454 for (SyncOperation op
: mFoldersToWalkDown
) {
455 contentsResult
= op
.execute(client
, getStorageManager()); // to watch out: possibly deep recursion
456 if (!contentsResult
.isSuccess()) {
457 // TODO - some kind of error count, and use it with notifications
458 if (contentsResult
.getException() != null
) {
459 Log_OC
.e(TAG
, "Non blocking exception : "
460 + contentsResult
.getLogMessage(), contentsResult
.getException());
462 Log_OC
.e(TAG
, "Non blocking error : " + contentsResult
.getLogMessage());
464 } // won't let these fails break the synchronization process
470 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
472 * @param remote remote file read from the server (remote file or folder).
473 * @return New OCFile instance representing the remote resource described by we.
475 private OCFile
fillOCFile(RemoteFile remote
) {
476 OCFile file
= new OCFile(remote
.getRemotePath());
477 file
.setCreationTimestamp(remote
.getCreationTimestamp());
478 file
.setFileLength(remote
.getLength());
479 file
.setMimetype(remote
.getMimeType());
480 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
481 file
.setEtag(remote
.getEtag());
482 file
.setPermissions(remote
.getPermissions());
483 file
.setRemoteId(remote
.getRemoteId());
489 * Scans the default location for saving local copies of files searching for
490 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
493 * @param file File to associate a possible 'lost' local file.
495 private void searchForLocalFileInDefaultPath(OCFile file
) {
496 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
497 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
499 file
.setStoragePath(f
.getAbsolutePath());
500 file
.setLastSyncDateForData(f
.lastModified());
509 public void cancel(){
510 mCancellationRequested
.set(true
);