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
);
164 if (mCancellationRequested
.get()) {
165 throw new OperationCancelledException();
168 } catch (OperationCancelledException e
) {
169 result
= new RemoteOperationResult(e
);
176 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) throws OperationCancelledException
{
177 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
179 mRemoteFolderChanged
= true
;
180 RemoteOperationResult result
= null
;
182 if (mCancellationRequested
.get()) {
183 throw new OperationCancelledException();
187 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mRemotePath
);
188 result
= operation
.execute(client
);
189 if (result
.isSuccess()){
190 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
192 // check if remote and local folder are different
193 mRemoteFolderChanged
=
194 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
196 result
= new RemoteOperationResult(ResultCode
.OK
);
198 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
199 (mRemoteFolderChanged ?
"changed" : "not changed"));
203 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
206 if (result
.isException()) {
207 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
208 result
.getLogMessage(), result
.getException());
210 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
211 result
.getLogMessage());
220 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) throws OperationCancelledException
{
221 if (mCancellationRequested
.get()) {
222 throw new OperationCancelledException();
225 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
226 RemoteOperationResult result
= operation
.execute(client
);
227 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
229 if (result
.isSuccess()) {
230 synchronizeData(result
.getData(), client
);
231 if (mConflictsFound
> 0 || mFailsInFileSyncsFound
> 0) {
232 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
233 // should be a different result code, but will do the job
236 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
245 private void removeLocalFolder() {
246 FileDataStorageManager storageManager
= getStorageManager();
247 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
248 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
249 storageManager
.removeFolder(
252 ( mLocalFolder
.isDown() && // TODO: debug, I think this is always false for folders
253 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
261 * Synchronizes the data retrieved from the server about the contents of the target folder
262 * with the current data in the local database.
264 * Grants that mChildren is updated with fresh data after execution.
266 * @param folderAndFiles Remote folder and children files in Folder
268 * @param client Client instance to the remote server where the data were
270 * @return 'True' when any change was made in the local data, 'false' otherwise
272 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
)
273 throws OperationCancelledException
{
274 FileDataStorageManager storageManager
= getStorageManager();
276 // parse data from remote folder
277 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
278 remoteFolder
.setParentId(mLocalFolder
.getParentId());
279 remoteFolder
.setFileId(mLocalFolder
.getFileId());
281 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
282 + " changed - starting update of local data ");
284 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
285 mFilesForDirectDownload
.clear();
286 mFilesToSyncContentsWithoutUpload
.clear();
287 mFavouriteFilesToSyncContents
.clear();
289 if (mCancellationRequested
.get()) {
290 throw new OperationCancelledException();
293 // get current data about local contents of the folder to synchronize
294 List
<OCFile
> localFiles
= storageManager
.getFolderContent(mLocalFolder
);
295 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
296 for (OCFile file
: localFiles
) {
297 localFilesMap
.put(file
.getRemotePath(), file
);
300 // loop to synchronize every child
301 OCFile remoteFile
= null
, localFile
= null
;
302 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
303 /// new OCFile instance with the data from the server
304 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
305 remoteFile
.setParentId(mLocalFolder
.getFileId());
307 /// retrieve local data for the read file
308 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
309 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
311 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
312 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
313 if (localFile
!= null
) {
314 // some properties of local state are kept unmodified
315 remoteFile
.setFileId(localFile
.getFileId());
316 remoteFile
.setKeepInSync(localFile
.keepInSync());
317 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
318 remoteFile
.setModificationTimestampAtLastSyncForData(
319 localFile
.getModificationTimestampAtLastSyncForData()
321 remoteFile
.setStoragePath(localFile
.getStoragePath());
322 // eTag will not be updated unless contents are synchronized
323 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
324 remoteFile
.setEtag(localFile
.getEtag());
325 if (remoteFile
.isFolder()) {
326 remoteFile
.setFileLength(localFile
.getFileLength());
327 // TODO move operations about size of folders to FileContentProvider
328 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
329 remoteFile
.getModificationTimestamp() != localFile
.getModificationTimestamp()) {
330 remoteFile
.setNeedsUpdateThumbnail(true
);
331 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
333 remoteFile
.setPublicLink(localFile
.getPublicLink());
334 remoteFile
.setShareByLink(localFile
.isShareByLink());
336 // remote eTag will not be updated unless contents are synchronized
337 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
338 remoteFile
.setEtag("");
341 /// check and fix, if needed, local storage path
342 searchForLocalFileInDefaultPath(remoteFile
);
344 /// classify file to sync/download contents later
345 if (remoteFile
.isFolder()) {
346 /// to download children files recursively
347 synchronized(mCancellationRequested
) {
348 if (mCancellationRequested
.get()) {
349 throw new OperationCancelledException();
351 startSyncFolderOperation(remoteFile
.getRemotePath());
354 } else if (remoteFile
.keepInSync()) {
355 /// prepare content synchronization for kept-in-sync files
356 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
363 mFavouriteFilesToSyncContents
.add(operation
);
366 /// prepare limited synchronization for regular files
367 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
375 mFilesToSyncContentsWithoutUpload
.add(operation
);
378 updatedFiles
.add(remoteFile
);
381 // save updated contents in local database
382 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
387 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException
{
388 List
<OCFile
> children
= getStorageManager().getFolderContent(mLocalFolder
);
389 for (OCFile child
: children
) {
390 /// classify file to sync/download contents later
391 if (child
.isFolder()) {
392 /// to download children files recursively
393 synchronized(mCancellationRequested
) {
394 if (mCancellationRequested
.get()) {
395 throw new OperationCancelledException();
397 startSyncFolderOperation(child
.getRemotePath());
401 /// prepare limited synchronization for regular files
402 if (!child
.isDown()) {
403 mFilesForDirectDownload
.add(child
);
410 private void syncContents(OwnCloudClient client
) throws OperationCancelledException
{
411 startDirectDownloads();
412 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
413 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
417 private void startDirectDownloads() throws OperationCancelledException
{
418 for (OCFile file
: mFilesForDirectDownload
) {
419 synchronized(mCancellationRequested
) {
420 if (mCancellationRequested
.get()) {
421 throw new OperationCancelledException();
423 Intent i
= new Intent(mContext
, FileDownloader
.class);
424 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
425 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
426 mContext
.startService(i
);
432 * Performs a list of synchronization operations, determining if a download or upload is needed
433 * or if exists conflict due to changes both in local and remote contents of the each file.
435 * If download or upload is needed, request the operation to the corresponding service and goes
438 * @param filesToSyncContents Synchronization operations to execute.
439 * @param client Interface to the remote ownCloud server.
441 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
, OwnCloudClient client
)
442 throws OperationCancelledException
{
444 Log_OC
.v(TAG
, "Starting content synchronization... ");
445 RemoteOperationResult contentsResult
= null
;
446 for (SyncOperation op
: filesToSyncContents
) {
447 if (mCancellationRequested
.get()) {
448 throw new OperationCancelledException();
450 contentsResult
= op
.execute(getStorageManager(), mContext
);
451 if (!contentsResult
.isSuccess()) {
452 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
455 mFailsInFileSyncsFound
++;
456 if (contentsResult
.getException() != null
) {
457 Log_OC
.e(TAG
, "Error while synchronizing file : "
458 + contentsResult
.getLogMessage(), contentsResult
.getException());
460 Log_OC
.e(TAG
, "Error while synchronizing file : "
461 + contentsResult
.getLogMessage());
464 // TODO - use the errors count in notifications
465 } // won't let these fails break the synchronization process
471 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
473 * @param remote remote file read from the server (remote file or folder).
474 * @return New OCFile instance representing the remote resource described by we.
476 private OCFile
fillOCFile(RemoteFile remote
) {
477 OCFile file
= new OCFile(remote
.getRemotePath());
478 file
.setCreationTimestamp(remote
.getCreationTimestamp());
479 file
.setFileLength(remote
.getLength());
480 file
.setMimetype(remote
.getMimeType());
481 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
482 file
.setEtag(remote
.getEtag());
483 file
.setPermissions(remote
.getPermissions());
484 file
.setRemoteId(remote
.getRemoteId());
490 * Scans the default location for saving local copies of files searching for
491 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
494 * @param file File to associate a possible 'lost' local file.
496 private void searchForLocalFileInDefaultPath(OCFile file
) {
497 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
498 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
500 file
.setStoragePath(f
.getAbsolutePath());
501 file
.setLastSyncDateForData(f
.lastModified());
510 public void cancel() {
511 mCancellationRequested
.set(true
);
514 public String
getFolderPath() {
515 String path
= mLocalFolder
.getStoragePath();
516 if (path
!= null
&& path
.length() > 0) {
519 return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
);
522 private void startSyncFolderOperation(String path
){
523 Intent intent
= new Intent(mContext
, OperationsService
.class);
524 intent
.setAction(OperationsService
.ACTION_SYNC_FOLDER
);
525 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, mAccount
);
526 intent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, path
);
527 mContext
.startService(intent
);
530 public String
getRemotePath() {