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
.io
.FileInputStream
;
25 import java
.io
.FileOutputStream
;
26 import java
.io
.IOException
;
27 import java
.io
.InputStream
;
28 import java
.io
.OutputStream
;
29 import java
.util
.ArrayList
;
30 import java
.util
.HashMap
;
31 import java
.util
.List
;
33 import java
.util
.Vector
;
35 import org
.apache
.http
.HttpStatus
;
36 import android
.accounts
.Account
;
37 import android
.content
.Context
;
38 import android
.content
.Intent
;
39 import android
.util
.Log
;
40 //import android.support.v4.content.LocalBroadcastManager;
42 import com
.owncloud
.android
.MainApp
;
43 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
44 import com
.owncloud
.android
.datamodel
.OCFile
;
46 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
47 import com
.owncloud
.android
.lib
.resources
.shares
.OCShare
;
48 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
49 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
50 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
51 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
52 import com
.owncloud
.android
.lib
.resources
.shares
.GetRemoteSharesForFileOperation
;
53 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
54 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
55 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
56 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
58 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
59 import com
.owncloud
.android
.utils
.FileStorageUtils
;
64 * Remote operation performing the synchronization of the list of files contained
65 * in a folder identified with its remote path.
67 * Fetches the list and properties of the files contained in the given folder, including their
68 * properties, and updates the local database with them.
70 * Does NOT enter in the child folders to synchronize their contents also.
72 public class RefreshFolderOperation
extends RemoteOperation
{
74 private static final String TAG
= RefreshFolderOperation
.class.getSimpleName();
76 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
=
77 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
78 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
=
79 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
81 /** Time stamp for the synchronization process in progress */
82 private long mCurrentSyncTime
;
84 /** Remote folder to synchronize */
85 private OCFile mLocalFolder
;
87 /** Access to the local database */
88 private FileDataStorageManager mStorageManager
;
90 /** Account where the file to synchronize belongs */
91 private Account mAccount
;
93 /** Android context; necessary to send requests to the download service */
94 private Context mContext
;
96 /** Files and folders contained in the synchronized folder after a successful operation */
97 private List
<OCFile
> mChildren
;
99 /** Counter of conflicts found between local and remote files */
100 private int mConflictsFound
;
102 /** Counter of failed operations in synchronization of kept-in-sync files */
103 private int mFailsInFavouritesFound
;
106 * Map of remote and local paths to files that where locally stored in a location
107 * out of the ownCloud folder and couldn't be copied automatically into it
109 private Map
<String
, String
> mForgottenLocalFiles
;
111 /** 'True' means that this operation is part of a full account synchronization */
112 private boolean mSyncFullAccount
;
114 /** 'True' means that Share resources bound to the files into should be refreshed also */
115 private boolean mIsShareSupported
;
117 /** 'True' means that the remote folder changed and should be fetched */
118 private boolean mRemoteFolderChanged
;
120 /** 'True' means that Etag will be ignored */
121 private boolean mIgnoreETag
;
125 * Creates a new instance of {@link RefreshFolderOperation}.
127 * @param folder Folder to synchronize.
128 * @param currentSyncTime Time stamp for the synchronization process in progress.
129 * @param syncFullAccount 'True' means that this operation is part of a full account
131 * @param isShareSupported 'True' means that the server supports the sharing API.
132 * @param ignoreETag 'True' means that the content of the remote folder should
133 * be fetched and updated even though the 'eTag' did not
135 * @param dataStorageManager Interface with the local database.
136 * @param account ownCloud account where the folder is located.
137 * @param context Application context.
139 public RefreshFolderOperation(OCFile folder
,
140 long currentSyncTime
,
141 boolean syncFullAccount
,
142 boolean isShareSupported
,
144 FileDataStorageManager dataStorageManager
,
147 mLocalFolder
= folder
;
148 mCurrentSyncTime
= currentSyncTime
;
149 mSyncFullAccount
= syncFullAccount
;
150 mIsShareSupported
= isShareSupported
;
151 mStorageManager
= dataStorageManager
;
154 mForgottenLocalFiles
= new HashMap
<String
, String
>();
155 mRemoteFolderChanged
= false
;
156 mIgnoreETag
= ignoreETag
;
160 public int getConflictsFound() {
161 return mConflictsFound
;
164 public int getFailsInFavouritesFound() {
165 return mFailsInFavouritesFound
;
168 public Map
<String
, String
> getForgottenLocalFiles() {
169 return mForgottenLocalFiles
;
173 * Returns the list of files and folders contained in the synchronized folder,
174 * if called after synchronization is complete.
176 * @return List of files and folders contained in the synchronized folder.
178 public List
<OCFile
> getChildren() {
183 * Performs the synchronization.
188 protected RemoteOperationResult
run(OwnCloudClient client
) {
189 RemoteOperationResult result
= null
;
190 mFailsInFavouritesFound
= 0;
192 mForgottenLocalFiles
.clear();
194 if (FileUtils
.PATH_SEPARATOR
.equals(mLocalFolder
.getRemotePath()) && !mSyncFullAccount
) {
195 updateOCVersion(client
);
198 result
= checkForChanges(client
);
200 if (result
.isSuccess()) {
201 if (mRemoteFolderChanged
) {
202 result
= fetchAndSyncRemoteFolder(client
);
204 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
, false
);
208 if (!mSyncFullAccount
) {
210 EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
214 if (result
.isSuccess() && mIsShareSupported
&& !mSyncFullAccount
) {
215 refreshSharesForFolder(client
); // share result is ignored
218 if (!mSyncFullAccount
) {
220 EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
229 private void updateOCVersion(OwnCloudClient client
) {
230 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(mAccount
, mContext
);
231 RemoteOperationResult result
= update
.execute(client
);
232 if (result
.isSuccess()) {
233 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
238 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
239 mRemoteFolderChanged
= true
;
240 RemoteOperationResult result
= null
;
241 String remotePath
= null
;
243 remotePath
= mLocalFolder
.getRemotePath();
244 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
247 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
248 result
= operation
.execute(client
);
249 if (result
.isSuccess()){
250 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
253 // check if remote and local folder are different
254 String remoteFolderETag
= remoteFolder
.getEtag();
255 if (remoteFolderETag
!= null
) {
256 mRemoteFolderChanged
=
257 !(remoteFolderETag
.equalsIgnoreCase(mLocalFolder
.getEtag()));
259 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
260 "No ETag received from server");
264 result
= new RemoteOperationResult(ResultCode
.OK
);
266 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
267 (mRemoteFolderChanged ?
"changed" : "not changed"));
271 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
274 if (result
.isException()) {
275 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
276 result
.getLogMessage(), result
.getException());
278 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
279 result
.getLogMessage());
287 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
288 String remotePath
= mLocalFolder
.getRemotePath();
289 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
290 RemoteOperationResult result
= operation
.execute(client
);
291 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
293 if (result
.isSuccess()) {
294 synchronizeData(result
.getData(), client
);
295 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
296 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
297 // should be a different result code, but will do the job
300 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
308 private void removeLocalFolder() {
309 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
310 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
311 mStorageManager
.removeFolder(
314 ( mLocalFolder
.isDown() &&
315 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
323 * Synchronizes the data retrieved from the server about the contents of the target folder
324 * with the current data in the local database.
326 * Grants that mChildren is updated with fresh data after execution.
328 * @param folderAndFiles Remote folder and children files in Folder
330 * @param client Client instance to the remote server where the data were
332 * @return 'True' when any change was made in the local data, 'false' otherwise
334 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
335 // get 'fresh data' from the database
336 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
338 // parse data from remote folder
339 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
340 remoteFolder
.setParentId(mLocalFolder
.getParentId());
341 remoteFolder
.setFileId(mLocalFolder
.getFileId());
343 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
344 + " changed - starting update of local data ");
346 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
347 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
349 // get current data about local contents of the folder to synchronize
350 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
, false
);
351 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
352 for (OCFile file
: localFiles
) {
353 localFilesMap
.put(file
.getRemotePath(), file
);
356 // loop to update every child
357 OCFile remoteFile
= null
, localFile
= null
;
358 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
359 /// new OCFile instance with the data from the server
360 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
361 remoteFile
.setParentId(mLocalFolder
.getFileId());
363 /// retrieve local data for the read file
364 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
365 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
367 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
368 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
369 if (localFile
!= null
) {
370 // some properties of local state are kept unmodified
371 remoteFile
.setFileId(localFile
.getFileId());
372 remoteFile
.setFavorite(localFile
.isFavorite());
373 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
374 remoteFile
.setModificationTimestampAtLastSyncForData(
375 localFile
.getModificationTimestampAtLastSyncForData()
377 remoteFile
.setStoragePath(localFile
.getStoragePath());
378 // eTag will not be updated unless contents are synchronized
379 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
380 remoteFile
.setEtag(localFile
.getEtag());
381 if (remoteFile
.isFolder()) {
382 remoteFile
.setFileLength(localFile
.getFileLength());
383 // TODO move operations about size of folders to FileContentProvider
384 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
385 remoteFile
.getModificationTimestamp() !=
386 localFile
.getModificationTimestamp()) {
387 remoteFile
.setNeedsUpdateThumbnail(true
);
388 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
390 remoteFile
.setPublicLink(localFile
.getPublicLink());
391 remoteFile
.setShareByLink(localFile
.isShareByLink());
393 // remote eTag will not be updated unless contents are synchronized
394 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
395 remoteFile
.setEtag("");
398 /// check and fix, if needed, local storage path
399 checkAndFixForeignStoragePath(remoteFile
); // policy - local files are COPIED
400 // into the ownCloud local folder;
401 searchForLocalFileInDefaultPath(remoteFile
); // legacy
403 /// prepare content synchronization for kept-in-sync files
404 if (remoteFile
.isFavorite()) {
405 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
412 filesToSyncContents
.add(operation
);
415 updatedFiles
.add(remoteFile
);
418 // save updated contents in local database
419 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
421 // request for the synchronization of file contents AFTER saving current remote properties
422 startContentSynchronizations(filesToSyncContents
, client
);
424 mChildren
= updatedFiles
;
428 * Performs a list of synchronization operations, determining if a download or upload is needed
429 * or if exists conflict due to changes both in local and remote contents of the each file.
431 * If download or upload is needed, request the operation to the corresponding service and goes
434 * @param filesToSyncContents Synchronization operations to execute.
435 * @param client Interface to the remote ownCloud server.
437 private void startContentSynchronizations(
438 List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
440 RemoteOperationResult contentsResult
= null
;
441 for (SynchronizeFileOperation op
: filesToSyncContents
) {
442 contentsResult
= op
.execute(mStorageManager
, mContext
); // async
443 if (!contentsResult
.isSuccess()) {
444 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
447 mFailsInFavouritesFound
++;
448 if (contentsResult
.getException() != null
) {
449 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
450 + contentsResult
.getLogMessage(), contentsResult
.getException());
452 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
453 + contentsResult
.getLogMessage());
456 } // won't let these fails break the synchronization process
461 public boolean isMultiStatus(int status
) {
462 return (status
== HttpStatus
.SC_MULTI_STATUS
);
466 * Creates and populates a new {@link OCFile} object with the data read from the server.
468 * @param remote remote file read from the server (remote file or folder).
469 * @return New OCFile instance representing the remote resource described by we.
471 private OCFile
fillOCFile(RemoteFile remote
) {
472 OCFile file
= new OCFile(remote
.getRemotePath());
473 file
.setCreationTimestamp(remote
.getCreationTimestamp());
474 file
.setFileLength(remote
.getLength());
475 file
.setMimetype(remote
.getMimeType());
476 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
477 file
.setEtag(remote
.getEtag());
478 file
.setPermissions(remote
.getPermissions());
479 file
.setRemoteId(remote
.getRemoteId());
485 * Checks the storage path of the OCFile received as parameter.
486 * If it's out of the local ownCloud folder, tries to copy the file inside it.
488 * If the copy fails, the link to the local file is nullified. The account of forgotten
489 * files is kept in {@link #mForgottenLocalFiles}
491 * @param file File to check and fix.
493 private void checkAndFixForeignStoragePath(OCFile file
) {
494 String storagePath
= file
.getStoragePath();
495 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
496 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
497 /// fix storagePaths out of the local ownCloud folder
498 File originalFile
= new File(storagePath
);
499 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
500 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
501 file
.setStoragePath(null
);
504 InputStream
in = null
;
505 OutputStream out
= null
;
507 File expectedFile
= new File(expectedPath
);
508 File expectedParent
= expectedFile
.getParentFile();
509 expectedParent
.mkdirs();
510 if (!expectedParent
.isDirectory()) {
511 throw new IOException(
512 "Unexpected error: parent directory could not be created"
515 expectedFile
.createNewFile();
516 if (!expectedFile
.isFile()) {
517 throw new IOException("Unexpected error: target file could not be created");
519 in = new FileInputStream(originalFile
);
520 out
= new FileOutputStream(expectedFile
);
521 byte[] buf
= new byte[1024];
523 while ((len
= in.read(buf
)) > 0){
524 out
.write(buf
, 0, len
);
526 file
.setStoragePath(expectedPath
);
528 } catch (Exception e
) {
529 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
530 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
531 file
.setStoragePath(null
);
535 if (in != null
) in.close();
536 } catch (Exception e
) {
537 Log_OC
.d(TAG
, "Weird exception while closing input stream for "
538 + storagePath
+ " (ignoring)", e
);
541 if (out
!= null
) out
.close();
542 } catch (Exception e
) {
543 Log_OC
.d(TAG
, "Weird exception while closing output stream for "
544 + expectedPath
+ " (ignoring)", e
);
552 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
553 RemoteOperationResult result
= null
;
556 GetRemoteSharesForFileOperation operation
=
557 new GetRemoteSharesForFileOperation(mLocalFolder
.getRemotePath(), false
, true
);
558 result
= operation
.execute(client
);
560 if (result
.isSuccess()) {
561 // update local database
562 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
563 for(Object obj
: result
.getData()) {
564 shares
.add((OCShare
) obj
);
566 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
574 * Scans the default location for saving local copies of files searching for
575 * a 'lost' file with the same full name as the {@link OCFile} received as
578 * @param file File to associate a possible 'lost' local file.
580 private void searchForLocalFileInDefaultPath(OCFile file
) {
581 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
582 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
584 file
.setStoragePath(f
.getAbsolutePath());
585 file
.setLastSyncDateForData(f
.lastModified());
592 * Sends a message to any application component interested in the progress
593 * of the synchronization.
596 * @param dirRemotePath Remote path of a folder that was just synchronized
597 * (with or without success)
600 private void sendLocalBroadcast(
601 String event
, String dirRemotePath
, RemoteOperationResult result
603 Log_OC
.d(TAG
, "Send broadcast " + event
);
604 Intent intent
= new Intent(event
);
605 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
606 if (dirRemotePath
!= null
) {
607 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
609 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
610 mContext
.sendStickyBroadcast(intent
);
611 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
615 public boolean getRemoteFolderChanged() {
616 return mRemoteFolderChanged
;