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
;
24 import java
.util
.ArrayList
;
25 import java
.util
.HashMap
;
26 import java
.util
.List
;
28 import java
.util
.Vector
;
30 import android
.accounts
.Account
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.util
.Log
;
36 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
37 import com
.owncloud
.android
.datamodel
.OCFile
;
38 import com
.owncloud
.android
.files
.services
.FileDownloader
;
39 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
40 import com
.owncloud
.android
.lib
.common
.operations
.OperationCancelledException
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
42 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
43 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
44 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
45 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
46 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
47 import com
.owncloud
.android
.operations
.common
.SyncOperation
;
48 import com
.owncloud
.android
.services
.OperationsService
;
49 import com
.owncloud
.android
.utils
.FileStorageUtils
;
51 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
53 //import android.support.v4.content.LocalBroadcastManager;
57 * Remote operation performing the DOWNLOAD of the list of files contained
58 * in a folder identified with its remote path.
60 * Fetches the list and properties of the files contained in the given folder, including their
61 * properties, and updates the local database with them.
63 * Does NOT enter in the child folders to download their contents also, BUT request for a new operation instance
66 * TODO: REMOVE WHEN SYNCHRONIZATION OF FULL FOLDERS IS GOOD ENOUGH
68 * This class is here just to keep the 'download folder' option available separately until 'sync folder' is ready to go
70 public class DownloadFolderOperation
extends SyncOperation
{
72 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
74 /** Time stamp for the synchronization process in progress */
75 private long mCurrentSyncTime
;
77 /** Remote path of the folder to synchronize */
78 private String mRemotePath
;
80 /** Account where the file to synchronize belongs */
81 private Account mAccount
;
83 /** Android context; necessary to send requests to the download service */
84 private Context mContext
;
86 /** Locally cached information about folder to synchronize */
87 private OCFile mLocalFolder
;
89 /** Files and folders contained in the synchronized folder after a successful operation */
90 //private List<OCFile> mChildren;
92 /** Counter of conflicts found between local and remote files */
93 private int mConflictsFound
;
95 /** Counter of failed operations in synchronization of kept-in-sync files */
96 private int mFailsInFileSyncsFound
;
98 /** 'True' means that the remote folder changed and should be fetched */
99 private boolean mRemoteFolderChanged
;
101 private List
<OCFile
> mFilesForDirectDownload
;
102 // to avoid extra PROPFINDs when there was no change in the folder
104 private List
<SyncOperation
> mFilesToSyncContentsWithoutUpload
;
105 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
107 private List
<SyncOperation
> mFavouriteFilesToSyncContents
;
108 // this will be used for every file when 'folder synchronization' replaces 'folder download'
110 private final AtomicBoolean mCancellationRequested
;
113 * Creates a new instance of {@link DownloadFolderOperation}.
115 * @param context Application context.
116 * @param remotePath Path to synchronize.
117 * @param account ownCloud account where the folder is located.
118 * @param currentSyncTime Time stamp for the synchronization process in progress.
120 public DownloadFolderOperation(Context context
, String remotePath
, Account account
,
121 long currentSyncTime
){
122 mRemotePath
= remotePath
;
123 mCurrentSyncTime
= currentSyncTime
;
126 mRemoteFolderChanged
= false
;
127 mFilesForDirectDownload
= new Vector
<OCFile
>();
128 mFilesToSyncContentsWithoutUpload
= new Vector
<SyncOperation
>();
129 mFavouriteFilesToSyncContents
= new Vector
<SyncOperation
>();
130 mCancellationRequested
= new AtomicBoolean(false
);
134 public int getConflictsFound() {
135 return mConflictsFound
;
138 public int getFailsInFileSyncsFound() {
139 return mFailsInFileSyncsFound
;
143 * Performs the synchronization.
148 protected RemoteOperationResult
run(OwnCloudClient client
) {
149 RemoteOperationResult result
= null
;
150 mFailsInFileSyncsFound
= 0;
154 // get locally cached information about folder
155 mLocalFolder
= getStorageManager().getFileByPath(mRemotePath
);
157 result
= checkForChanges(client
);
159 if (result
.isSuccess()) {
160 if (mRemoteFolderChanged
) {
161 result
= fetchAndSyncRemoteFolder(client
);
164 prepareOpsFromLocalKnowledge();
167 if (result
.isSuccess()) {
168 syncContents(client
);
173 if (mCancellationRequested
.get()) {
174 throw new OperationCancelledException();
177 } catch (OperationCancelledException e
) {
178 result
= new RemoteOperationResult(e
);
185 private RemoteOperationResult
checkForChanges(OwnCloudClient client
)
186 throws OperationCancelledException
{
187 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ mRemotePath
);
189 mRemoteFolderChanged
= true
;
190 RemoteOperationResult result
= null
;
192 if (mCancellationRequested
.get()) {
193 throw new OperationCancelledException();
197 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(mRemotePath
);
198 result
= operation
.execute(client
);
199 if (result
.isSuccess()){
200 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
202 // check if remote and local folder are different
203 mRemoteFolderChanged
=
204 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
206 result
= new RemoteOperationResult(ResultCode
.OK
);
208 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
209 (mRemoteFolderChanged ?
"changed" : "not changed"));
213 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
216 if (result
.isException()) {
217 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
218 result
.getLogMessage(), result
.getException());
220 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ mRemotePath
+ " : " +
221 result
.getLogMessage());
230 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
)
231 throws OperationCancelledException
{
232 if (mCancellationRequested
.get()) {
233 throw new OperationCancelledException();
236 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(mRemotePath
);
237 RemoteOperationResult result
= operation
.execute(client
);
238 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ mRemotePath
);
240 if (result
.isSuccess()) {
241 synchronizeData(result
.getData(), client
);
242 if (mConflictsFound
> 0 || mFailsInFileSyncsFound
> 0) {
243 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
244 // should be a different result code, but will do the job
247 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
256 private void removeLocalFolder() {
257 FileDataStorageManager storageManager
= getStorageManager();
258 if (storageManager
.fileExists(mLocalFolder
.getFileId())) {
259 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
260 storageManager
.removeFolder(
263 ( mLocalFolder
.isDown() && // TODO: debug, I think this is
264 // always false for folders
265 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
273 * Synchronizes the data retrieved from the server about the contents of the target folder
274 * with the current data in the local database.
276 * Grants that mChildren is updated with fresh data after execution.
278 * @param folderAndFiles Remote folder and children files in Folder
280 * @param client Client instance to the remote server where the data were
282 * @return 'True' when any change was made in the local data, 'false' otherwise
284 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
)
285 throws OperationCancelledException
{
286 FileDataStorageManager storageManager
= getStorageManager();
288 // parse data from remote folder
289 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
290 remoteFolder
.setParentId(mLocalFolder
.getParentId());
291 remoteFolder
.setFileId(mLocalFolder
.getFileId());
293 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
294 + " changed - starting update of local data ");
296 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
297 mFilesForDirectDownload
.clear();
298 mFilesToSyncContentsWithoutUpload
.clear();
299 mFavouriteFilesToSyncContents
.clear();
301 if (mCancellationRequested
.get()) {
302 throw new OperationCancelledException();
305 // get current data about local contents of the folder to synchronize
306 // TODO Enable when "On Device" is recovered ?
307 List
<OCFile
> localFiles
= storageManager
.getFolderContent(mLocalFolder
/*, false*/);
308 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
309 for (OCFile file
: localFiles
) {
310 localFilesMap
.put(file
.getRemotePath(), file
);
313 // loop to synchronize every child
314 OCFile remoteFile
= null
, localFile
= null
;
315 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
316 /// new OCFile instance with the data from the server
317 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
318 remoteFile
.setParentId(mLocalFolder
.getFileId());
320 /// retrieve local data for the read file
321 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
322 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
324 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
325 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
326 if (localFile
!= null
) {
327 // some properties of local state are kept unmodified
328 remoteFile
.setFileId(localFile
.getFileId());
329 remoteFile
.setFavorite(localFile
.isFavorite());
330 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
331 remoteFile
.setModificationTimestampAtLastSyncForData(
332 localFile
.getModificationTimestampAtLastSyncForData()
334 remoteFile
.setStoragePath(localFile
.getStoragePath());
335 // eTag will not be updated unless contents are synchronized
336 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
337 remoteFile
.setEtag(localFile
.getEtag());
338 if (remoteFile
.isFolder()) {
339 remoteFile
.setFileLength(localFile
.getFileLength());
340 // TODO move operations about size of folders to FileContentProvider
341 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
342 remoteFile
.getModificationTimestamp() !=
343 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 synchronized (mCancellationRequested
) {
362 if (mCancellationRequested
.get()) {
363 throw new OperationCancelledException();
365 startSyncFolderOperation(remoteFile
.getRemotePath());
368 } else if (remoteFile
.isFavorite()) {
369 /// prepare content synchronization for kept-in-sync files
370 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
377 mFavouriteFilesToSyncContents
.add(operation
);
380 /// prepare limited synchronization for regular files
381 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
389 mFilesToSyncContentsWithoutUpload
.add(operation
);
392 updatedFiles
.add(remoteFile
);
395 // save updated contents in local database
396 storageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
401 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException
{
402 // TODO Enable when "On Device" is recovered ?
403 List
<OCFile
> children
= getStorageManager().getFolderContent(mLocalFolder
/*, false*/);
404 for (OCFile child
: children
) {
405 /// classify file to sync/download contents later
406 if (child
.isFolder()) {
407 /// to download children files recursively
408 synchronized(mCancellationRequested
) {
409 if (mCancellationRequested
.get()) {
410 throw new OperationCancelledException();
412 startSyncFolderOperation(child
.getRemotePath());
416 /// prepare limited synchronization for regular files
417 if (!child
.isDown()) {
418 mFilesForDirectDownload
.add(child
);
427 private void syncContents(OwnCloudClient client
) throws OperationCancelledException
{
428 startDirectDownloads();
429 startContentSynchronizations(mFilesToSyncContentsWithoutUpload
, client
);
430 startContentSynchronizations(mFavouriteFilesToSyncContents
, client
);
434 private void startDirectDownloads() throws OperationCancelledException
{
435 for (OCFile file
: mFilesForDirectDownload
) {
436 synchronized(mCancellationRequested
) {
437 if (mCancellationRequested
.get()) {
438 throw new OperationCancelledException();
440 Intent i
= new Intent(mContext
, FileDownloader
.class);
441 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
442 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
443 mContext
.startService(i
);
449 * Performs a list of synchronization operations, determining if a download or upload is needed
450 * or if exists conflict due to changes both in local and remote contents of the each file.
452 * If download or upload is needed, request the operation to the corresponding service and goes
455 * @param filesToSyncContents Synchronization operations to execute.
456 * @param client Interface to the remote ownCloud server.
458 private void startContentSynchronizations(List
<SyncOperation
> filesToSyncContents
,
459 OwnCloudClient client
)
460 throws OperationCancelledException
{
462 Log_OC
.v(TAG
, "Starting content synchronization... ");
463 RemoteOperationResult contentsResult
= null
;
464 for (SyncOperation op
: filesToSyncContents
) {
465 if (mCancellationRequested
.get()) {
466 throw new OperationCancelledException();
468 contentsResult
= op
.execute(getStorageManager(), mContext
);
469 if (!contentsResult
.isSuccess()) {
470 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
473 mFailsInFileSyncsFound
++;
474 if (contentsResult
.getException() != null
) {
475 Log_OC
.e(TAG
, "Error while synchronizing file : "
476 + contentsResult
.getLogMessage(), contentsResult
.getException());
478 Log_OC
.e(TAG
, "Error while synchronizing file : "
479 + contentsResult
.getLogMessage());
482 // TODO - use the errors count in notifications
483 } // won't let these fails break the synchronization process
489 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
490 * object with the data read from the server.
492 * @param remote remote file read from the server (remote file or folder).
493 * @return New OCFile instance representing the remote resource described by we.
495 private OCFile
fillOCFile(RemoteFile remote
) {
496 OCFile file
= new OCFile(remote
.getRemotePath());
497 file
.setCreationTimestamp(remote
.getCreationTimestamp());
498 file
.setFileLength(remote
.getLength());
499 file
.setMimetype(remote
.getMimeType());
500 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
501 file
.setEtag(remote
.getEtag());
502 file
.setPermissions(remote
.getPermissions());
503 file
.setRemoteId(remote
.getRemoteId());
509 * Scans the default location for saving local copies of files searching for
510 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
511 * received as parameter.
513 * @param file File to associate a possible 'lost' local file.
515 private void searchForLocalFileInDefaultPath(OCFile file
) {
516 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
517 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
519 file
.setStoragePath(f
.getAbsolutePath());
520 file
.setLastSyncDateForData(f
.lastModified());
529 public void cancel() {
530 mCancellationRequested
.set(true
);
533 public String
getFolderPath() {
534 String path
= mLocalFolder
.getStoragePath();
535 if (path
!= null
&& path
.length() > 0) {
538 return FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, mLocalFolder
);
541 private void startSyncFolderOperation(String path
){
542 Intent intent
= new Intent(mContext
, OperationsService
.class);
543 intent
.setAction(OperationsService
.ACTION_DOWNLOAD_FOLDER
);
544 intent
.putExtra(OperationsService
.EXTRA_ACCOUNT
, mAccount
);
545 intent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, path
);
546 mContext
.startService(intent
);
549 public String
getRemotePath() {