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 java
.util
.ArrayList
;
24 import java
.util
.HashMap
;
25 import java
.util
.List
;
27 import java
.util
.Vector
;
29 import android
.accounts
.Account
;
30 import android
.content
.Context
;
31 import android
.content
.Intent
;
32 import android
.util
.Log
;
34 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
35 import com
.owncloud
.android
.datamodel
.OCFile
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
38 import com
.owncloud
.android
.lib
.resources
.shares
.OCShare
;
39 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
40 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
43 import com
.owncloud
.android
.lib
.resources
.shares
.GetRemoteSharesForFileOperation
;
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
;
48 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
49 import com
.owncloud
.android
.utils
.FileStorageUtils
;
54 * Remote operation performing the synchronization of the list of files contained
55 * in a folder identified with its remote path.
57 * Fetches the list and properties of the files contained in the given folder, including their
58 * properties, and updates the local database with them.
60 * Does NOT enter in the child folders to synchronize their contents also.
62 public class RefreshFolderOperation
extends RemoteOperation
{
64 private static final String TAG
= RefreshFolderOperation
.class.getSimpleName();
66 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
=
67 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
68 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
=
69 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
71 /** Time stamp for the synchronization process in progress */
72 private long mCurrentSyncTime
;
74 /** Remote folder to synchronize */
75 private OCFile mLocalFolder
;
77 /** Access to the local database */
78 private FileDataStorageManager mStorageManager
;
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 /** Files and folders contained in the synchronized folder after a successful operation */
87 private List
<OCFile
> mChildren
;
89 /** Counter of conflicts found between local and remote files */
90 private int mConflictsFound
;
92 /** Counter of failed operations in synchronization of kept-in-sync files */
93 private int mFailsInFavouritesFound
;
96 * Map of remote and local paths to files that where locally stored in a location
97 * out of the ownCloud folder and couldn't be copied automatically into it
99 private Map
<String
, String
> mForgottenLocalFiles
;
101 /** 'True' means that this operation is part of a full account synchronization */
102 private boolean mSyncFullAccount
;
104 /** 'True' means that Share resources bound to the files into should be refreshed also */
105 private boolean mIsShareSupported
;
107 /** 'True' means that the remote folder changed and should be fetched */
108 private boolean mRemoteFolderChanged
;
110 /** 'True' means that Etag will be ignored */
111 private boolean mIgnoreETag
;
113 private List
<SynchronizeFileOperation
> mFilesToSyncContents
;
114 // this will be used for every file when 'folder synchronization' replaces 'folder download'
118 * Creates a new instance of {@link RefreshFolderOperation}.
120 * @param folder Folder to synchronize.
121 * @param currentSyncTime Time stamp for the synchronization process in progress.
122 * @param syncFullAccount 'True' means that this operation is part of a full account
124 * @param isShareSupported 'True' means that the server supports the sharing API.
125 * @param ignoreETag 'True' means that the content of the remote folder should
126 * be fetched and updated even though the 'eTag' did not
128 * @param dataStorageManager Interface with the local database.
129 * @param account ownCloud account where the folder is located.
130 * @param context Application context.
132 public RefreshFolderOperation(OCFile folder
,
133 long currentSyncTime
,
134 boolean syncFullAccount
,
135 boolean isShareSupported
,
137 FileDataStorageManager dataStorageManager
,
140 mLocalFolder
= folder
;
141 mCurrentSyncTime
= currentSyncTime
;
142 mSyncFullAccount
= syncFullAccount
;
143 mIsShareSupported
= isShareSupported
;
144 mStorageManager
= dataStorageManager
;
147 mForgottenLocalFiles
= new HashMap
<String
, String
>();
148 mRemoteFolderChanged
= false
;
149 mIgnoreETag
= ignoreETag
;
150 mFilesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
154 public int getConflictsFound() {
155 return mConflictsFound
;
158 public int getFailsInFavouritesFound() {
159 return mFailsInFavouritesFound
;
162 public Map
<String
, String
> getForgottenLocalFiles() {
163 return mForgottenLocalFiles
;
167 * Returns the list of files and folders contained in the synchronized folder,
168 * if called after synchronization is complete.
170 * @return List of files and folders contained in the synchronized folder.
172 public List
<OCFile
> getChildren() {
177 * Performs the synchronization.
182 protected RemoteOperationResult
run(OwnCloudClient client
) {
183 RemoteOperationResult result
= null
;
184 mFailsInFavouritesFound
= 0;
186 mForgottenLocalFiles
.clear();
188 if (OCFile
.ROOT_PATH
.equals(mLocalFolder
.getRemotePath()) && !mSyncFullAccount
) {
189 updateOCVersion(client
);
193 result
= checkForChanges(client
);
195 if (result
.isSuccess()) {
196 if (mRemoteFolderChanged
) {
197 result
= fetchAndSyncRemoteFolder(client
);
199 fetchFavoritesToSyncFromLocalData();
200 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
, false
);
203 if (result
.isSuccess()) {
204 // request for the synchronization of KEPT-IN-SYNC file contents
205 startContentSynchronizations(mFilesToSyncContents
, client
);
209 if (!mSyncFullAccount
) {
211 EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
215 if (result
.isSuccess() && mIsShareSupported
&& !mSyncFullAccount
) {
216 refreshSharesForFolder(client
); // share result is ignored
219 if (!mSyncFullAccount
) {
221 EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
230 private void updateOCVersion(OwnCloudClient client
) {
231 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(mAccount
, mContext
);
232 RemoteOperationResult result
= update
.execute(client
);
233 if (result
.isSuccess()) {
234 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
236 // Update Capabilities for this account
237 if (update
.getOCVersion().isVersionWithCapabilitiesAPI()) {
238 updateCapabilities(client
);
240 Log_OC
.d(TAG
, "Capabilities API disabled");
245 private void updateCapabilities(OwnCloudClient client
){
246 GetCapabilitiesOperarion getCapabilities
= new GetCapabilitiesOperarion();
247 RemoteOperationResult result
= getCapabilities
.execute(mStorageManager
,mContext
);
248 if (!result
.isSuccess()){
249 Log_OC
.d(TAG
, "Update Capabilities unsuccessfully");
253 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
254 mRemoteFolderChanged
= true
;
255 RemoteOperationResult result
= null
;
256 String remotePath
= mLocalFolder
.getRemotePath();
258 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
261 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
262 result
= operation
.execute(client
);
263 if (result
.isSuccess()){
264 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
267 // check if remote and local folder are different
268 String remoteFolderETag
= remoteFolder
.getEtag();
269 if (remoteFolderETag
!= null
) {
270 mRemoteFolderChanged
=
271 !(remoteFolderETag
.equalsIgnoreCase(mLocalFolder
.getEtag()));
273 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
274 "No ETag received from server");
278 result
= new RemoteOperationResult(ResultCode
.OK
);
280 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
281 (mRemoteFolderChanged ?
"changed" : "not changed"));
285 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
288 if (result
.isException()) {
289 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
290 result
.getLogMessage(), result
.getException());
292 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
293 result
.getLogMessage());
301 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
302 String remotePath
= mLocalFolder
.getRemotePath();
303 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
304 RemoteOperationResult result
= operation
.execute(client
);
305 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
307 if (result
.isSuccess()) {
308 synchronizeData(result
.getData(), client
);
309 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
310 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
311 // should be a different result code, but will do the job
314 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
322 private void removeLocalFolder() {
323 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
324 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
325 mStorageManager
.removeFolder(
328 ( mLocalFolder
.isDown() &&
329 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
337 * Synchronizes the data retrieved from the server about the contents of the target folder
338 * with the current data in the local database.
340 * Grants that mChildren is updated with fresh data after execution.
342 * @param folderAndFiles Remote folder and children files in Folder
344 * @param client Client instance to the remote server where the data were
346 * @return 'True' when any change was made in the local data, 'false' otherwise
348 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
349 // get 'fresh data' from the database
350 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
352 // parse data from remote folder
353 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) folderAndFiles
.get(0));
354 remoteFolder
.setParentId(mLocalFolder
.getParentId());
355 remoteFolder
.setFileId(mLocalFolder
.getFileId());
357 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
358 + " changed - starting update of local data ");
360 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
361 mFilesToSyncContents
.clear();
363 // get current data about local contents of the folder to synchronize
364 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
, false
);
365 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
366 for (OCFile file
: localFiles
) {
367 localFilesMap
.put(file
.getRemotePath(), file
);
370 // loop to update every child
371 OCFile remoteFile
= null
, localFile
= null
, updatedFile
= null
;
373 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
374 /// new OCFile instance with the data from the server
375 r
= (RemoteFile
) folderAndFiles
.get(i
);
376 remoteFile
= FileStorageUtils
.fillOCFile(r
);
378 /// new OCFile instance to merge fresh data from server with local state
379 updatedFile
= FileStorageUtils
.fillOCFile(r
);
380 updatedFile
.setParentId(mLocalFolder
.getFileId());
382 /// retrieve local data for the read file
383 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
384 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
386 /// add to updatedFile data about LOCAL STATE (not existing in server)
387 updatedFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
388 if (localFile
!= null
) {
389 updatedFile
.setFileId(localFile
.getFileId());
390 updatedFile
.setFavorite(localFile
.isFavorite());
391 updatedFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
392 updatedFile
.setModificationTimestampAtLastSyncForData(
393 localFile
.getModificationTimestampAtLastSyncForData()
395 updatedFile
.setStoragePath(localFile
.getStoragePath());
396 // eTag will not be updated unless file CONTENTS are synchronized
397 updatedFile
.setEtag(localFile
.getEtag());
398 if (updatedFile
.isFolder()) {
399 updatedFile
.setFileLength(localFile
.getFileLength());
400 // TODO move operations about size of folders to FileContentProvider
401 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
402 remoteFile
.getModificationTimestamp() !=
403 localFile
.getModificationTimestamp()) {
404 updatedFile
.setNeedsUpdateThumbnail(true
);
405 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
407 updatedFile
.setPublicLink(localFile
.getPublicLink());
408 updatedFile
.setShareViaLink(localFile
.isSharedViaLink());
409 updatedFile
.setShareWithSharee(localFile
.isSharedWithSharee());
410 updatedFile
.setEtagInConflict(localFile
.getEtagInConflict());
412 // remote eTag will not be updated unless file CONTENTS are synchronized
413 updatedFile
.setEtag("");
416 /// check and fix, if needed, local storage path
417 FileStorageUtils
.searchForLocalFileInDefaultPath(updatedFile
, mAccount
);
419 /// prepare content synchronization for kept-in-sync files
420 if (updatedFile
.isFavorite()) {
421 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
428 mFilesToSyncContents
.add(operation
);
431 updatedFiles
.add(updatedFile
);
434 // save updated contents in local database
435 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
437 mChildren
= updatedFiles
;
441 * Performs a list of synchronization operations, determining if a download or upload is needed
442 * or if exists conflict due to changes both in local and remote contents of the each file.
444 * If download or upload is needed, request the operation to the corresponding service and goes
447 * @param filesToSyncContents Synchronization operations to execute.
448 * @param client Interface to the remote ownCloud server.
450 private void startContentSynchronizations(
451 List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
453 RemoteOperationResult contentsResult
= null
;
454 for (SynchronizeFileOperation op
: filesToSyncContents
) {
455 contentsResult
= op
.execute(mStorageManager
, mContext
); // async
456 if (!contentsResult
.isSuccess()) {
457 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
460 mFailsInFavouritesFound
++;
461 if (contentsResult
.getException() != null
) {
462 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
463 + contentsResult
.getLogMessage(), contentsResult
.getException());
465 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
466 + contentsResult
.getLogMessage());
469 } // won't let these fails break the synchronization process
475 * Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
477 * @param client Handler of a session with an OC server.
478 * @return The result of the remote operation retrieving the Share resources in the folder refreshed by
481 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
482 RemoteOperationResult result
= null
;
485 GetRemoteSharesForFileOperation operation
=
486 new GetRemoteSharesForFileOperation(mLocalFolder
.getRemotePath(), true
, true
);
487 result
= operation
.execute(client
);
489 if (result
.isSuccess()) {
490 // update local database
491 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
492 for(Object obj
: result
.getData()) {
493 shares
.add((OCShare
) obj
);
495 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
503 * Sends a message to any application component interested in the progress
504 * of the synchronization.
507 * @param dirRemotePath Remote path of a folder that was just synchronized
508 * (with or without success)
511 private void sendLocalBroadcast(
512 String event
, String dirRemotePath
, RemoteOperationResult result
514 Log_OC
.d(TAG
, "Send broadcast " + event
);
515 Intent intent
= new Intent(event
);
516 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
517 if (dirRemotePath
!= null
) {
518 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
520 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
521 mContext
.sendStickyBroadcast(intent
);
522 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
526 private void fetchFavoritesToSyncFromLocalData() {
527 List
<OCFile
> children
= mStorageManager
.getFolderContent(mLocalFolder
, false
);
528 for (OCFile child
: children
) {
529 if (!child
.isFolder() && child
.isFavorite()) {
530 SynchronizeFileOperation operation
= new SynchronizeFileOperation(
532 child
, // cheating with the remote file to get an update to server; to refactor
537 mFilesToSyncContents
.add(operation
);