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
.datamodel
.FileDataStorageManager
;
43 import com
.owncloud
.android
.datamodel
.OCFile
;
45 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
46 import com
.owncloud
.android
.lib
.resources
.shares
.OCShare
;
47 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
48 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
49 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
50 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
51 import com
.owncloud
.android
.lib
.resources
.shares
.GetRemoteSharesForFileOperation
;
52 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
53 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
54 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
55 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
57 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
58 import com
.owncloud
.android
.utils
.FileStorageUtils
;
63 * Remote operation performing the synchronization of the list of files contained
64 * in a folder identified with its remote path.
66 * Fetches the list and properties of the files contained in the given folder, including their
67 * properties, and updates the local database with them.
69 * Does NOT enter in the child folders to synchronize their contents also.
71 public class RefreshFolderOperation
extends RemoteOperation
{
73 private static final String TAG
= RefreshFolderOperation
.class.getSimpleName();
75 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
=
76 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
77 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
=
78 RefreshFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
80 /** Time stamp for the synchronization process in progress */
81 private long mCurrentSyncTime
;
83 /** Remote folder to synchronize */
84 private OCFile mLocalFolder
;
86 /** Access to the local database */
87 private FileDataStorageManager mStorageManager
;
89 /** Account where the file to synchronize belongs */
90 private Account mAccount
;
92 /** Android context; necessary to send requests to the download service */
93 private Context mContext
;
95 /** Files and folders contained in the synchronized folder after a successful operation */
96 private List
<OCFile
> mChildren
;
98 /** Counter of conflicts found between local and remote files */
99 private int mConflictsFound
;
101 /** Counter of failed operations in synchronization of kept-in-sync files */
102 private int mFailsInFavouritesFound
;
105 * Map of remote and local paths to files that where locally stored in a location
106 * out of the ownCloud folder and couldn't be copied automatically into it
108 private Map
<String
, String
> mForgottenLocalFiles
;
110 /** 'True' means that this operation is part of a full account synchronization */
111 private boolean mSyncFullAccount
;
113 /** 'True' means that Share resources bound to the files into should be refreshed also */
114 private boolean mIsShareSupported
;
116 /** 'True' means that the remote folder changed and should be fetched */
117 private boolean mRemoteFolderChanged
;
119 /** 'True' means that Etag will be ignored */
120 private boolean mIgnoreETag
;
124 * Creates a new instance of {@link RefreshFolderOperation}.
126 * @param folder Folder to synchronize.
127 * @param currentSyncTime Time stamp for the synchronization process in progress.
128 * @param syncFullAccount 'True' means that this operation is part of a full account
130 * @param isShareSupported 'True' means that the server supports the sharing API.
131 * @param ignoreEtag 'True' means that the content of the remote folder should
132 * be fetched and updated even though the 'eTag' did not
134 * @param dataStorageManager Interface with the local database.
135 * @param account ownCloud account where the folder is located.
136 * @param context Application context.
138 public RefreshFolderOperation(OCFile folder
,
139 long currentSyncTime
,
140 boolean syncFullAccount
,
141 boolean isShareSupported
,
143 FileDataStorageManager dataStorageManager
,
146 mLocalFolder
= folder
;
147 mCurrentSyncTime
= currentSyncTime
;
148 mSyncFullAccount
= syncFullAccount
;
149 mIsShareSupported
= isShareSupported
;
150 mStorageManager
= dataStorageManager
;
153 mForgottenLocalFiles
= new HashMap
<String
, String
>();
154 mRemoteFolderChanged
= false
;
155 mIgnoreETag
= ignoreETag
;
159 public int getConflictsFound() {
160 return mConflictsFound
;
163 public int getFailsInFavouritesFound() {
164 return mFailsInFavouritesFound
;
167 public Map
<String
, String
> getForgottenLocalFiles() {
168 return mForgottenLocalFiles
;
172 * Returns the list of files and folders contained in the synchronized folder,
173 * if called after synchronization is complete.
175 * @return List of files and folders contained in the synchronized folder.
177 public List
<OCFile
> getChildren() {
182 * Performs the synchronization.
187 protected RemoteOperationResult
run(OwnCloudClient client
) {
188 RemoteOperationResult result
= null
;
189 mFailsInFavouritesFound
= 0;
191 mForgottenLocalFiles
.clear();
193 if (FileUtils
.PATH_SEPARATOR
.equals(mLocalFolder
.getRemotePath()) && !mSyncFullAccount
) {
194 updateOCVersion(client
);
197 result
= checkForChanges(client
);
199 if (result
.isSuccess()) {
200 if (mRemoteFolderChanged
) {
201 result
= fetchAndSyncRemoteFolder(client
);
203 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
207 if (!mSyncFullAccount
) {
209 EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
213 if (result
.isSuccess() && mIsShareSupported
&& !mSyncFullAccount
) {
214 refreshSharesForFolder(client
); // share result is ignored
217 if (!mSyncFullAccount
) {
219 EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
228 private void updateOCVersion(OwnCloudClient client
) {
229 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(mAccount
, mContext
);
230 RemoteOperationResult result
= update
.execute(client
);
231 if (result
.isSuccess()) {
232 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
237 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
238 mRemoteFolderChanged
= true
;
239 RemoteOperationResult result
= null
;
240 String remotePath
= null
;
242 remotePath
= mLocalFolder
.getRemotePath();
243 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
246 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
247 result
= operation
.execute(client
);
248 if (result
.isSuccess()){
249 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
252 // check if remote and local folder are different
253 mRemoteFolderChanged
=
254 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
257 result
= new RemoteOperationResult(ResultCode
.OK
);
259 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
260 (mRemoteFolderChanged ?
"changed" : "not changed"));
264 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
267 if (result
.isException()) {
268 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
269 result
.getLogMessage(), result
.getException());
271 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
272 result
.getLogMessage());
280 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
281 String remotePath
= mLocalFolder
.getRemotePath();
282 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
283 RemoteOperationResult result
= operation
.execute(client
);
284 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
286 if (result
.isSuccess()) {
287 synchronizeData(result
.getData(), client
);
288 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
289 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
);
290 // should be a different result code, but will do the job
293 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
301 private void removeLocalFolder() {
302 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
303 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
304 mStorageManager
.removeFolder(
307 ( mLocalFolder
.isDown() &&
308 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
316 * Synchronizes the data retrieved from the server about the contents of the target folder
317 * with the current data in the local database.
319 * Grants that mChildren is updated with fresh data after execution.
321 * @param folderAndFiles Remote folder and children files in Folder
323 * @param client Client instance to the remote server where the data were
325 * @return 'True' when any change was made in the local data, 'false' otherwise
327 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
328 // get 'fresh data' from the database
329 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
331 // parse data from remote folder
332 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
333 remoteFolder
.setParentId(mLocalFolder
.getParentId());
334 remoteFolder
.setFileId(mLocalFolder
.getFileId());
336 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
337 + " changed - starting update of local data ");
339 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
340 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
342 // get current data about local contents of the folder to synchronize
343 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
344 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
345 for (OCFile file
: localFiles
) {
346 localFilesMap
.put(file
.getRemotePath(), file
);
349 // loop to update every child
350 OCFile remoteFile
= null
, localFile
= null
;
351 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
352 /// new OCFile instance with the data from the server
353 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
354 remoteFile
.setParentId(mLocalFolder
.getFileId());
356 /// retrieve local data for the read file
357 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
358 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
360 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
361 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
362 if (localFile
!= null
) {
363 // some properties of local state are kept unmodified
364 remoteFile
.setFileId(localFile
.getFileId());
365 remoteFile
.setKeepInSync(localFile
.keepInSync());
366 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
367 remoteFile
.setModificationTimestampAtLastSyncForData(
368 localFile
.getModificationTimestampAtLastSyncForData()
370 remoteFile
.setStoragePath(localFile
.getStoragePath());
371 // eTag will not be updated unless contents are synchronized
372 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
373 remoteFile
.setEtag(localFile
.getEtag());
374 if (remoteFile
.isFolder()) {
375 remoteFile
.setFileLength(localFile
.getFileLength());
376 // TODO move operations about size of folders to FileContentProvider
377 } else if (mRemoteFolderChanged
&& remoteFile
.isImage() &&
378 remoteFile
.getModificationTimestamp() != localFile
.getModificationTimestamp()) {
379 remoteFile
.setNeedsUpdateThumbnail(true
);
380 Log
.d(TAG
, "Image " + remoteFile
.getFileName() + " updated on the server");
382 remoteFile
.setPublicLink(localFile
.getPublicLink());
383 remoteFile
.setShareByLink(localFile
.isShareByLink());
385 // remote eTag will not be updated unless contents are synchronized
386 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
387 remoteFile
.setEtag("");
390 /// check and fix, if needed, local storage path
391 checkAndFixForeignStoragePath(remoteFile
); // policy - local files are COPIED
392 // into the ownCloud local folder;
393 searchForLocalFileInDefaultPath(remoteFile
); // legacy
395 /// prepare content synchronization for kept-in-sync files
396 if (remoteFile
.keepInSync()) {
397 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
404 filesToSyncContents
.add(operation
);
407 updatedFiles
.add(remoteFile
);
410 // save updated contents in local database
411 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
413 // request for the synchronization of file contents AFTER saving current remote properties
414 startContentSynchronizations(filesToSyncContents
, client
);
416 mChildren
= updatedFiles
;
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(
430 List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
432 RemoteOperationResult contentsResult
= null
;
433 for (SynchronizeFileOperation op
: filesToSyncContents
) {
434 contentsResult
= op
.execute(mStorageManager
, mContext
); // async
435 if (!contentsResult
.isSuccess()) {
436 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
439 mFailsInFavouritesFound
++;
440 if (contentsResult
.getException() != null
) {
441 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
442 + contentsResult
.getLogMessage(), contentsResult
.getException());
444 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
445 + contentsResult
.getLogMessage());
448 } // won't let these fails break the synchronization process
453 public boolean isMultiStatus(int status
) {
454 return (status
== HttpStatus
.SC_MULTI_STATUS
);
458 * Creates and populates a new {@link OCFile} object with the data read from the server.
460 * @param remote remote file read from the server (remote file or folder).
461 * @return New OCFile instance representing the remote resource described by we.
463 private OCFile
fillOCFile(RemoteFile remote
) {
464 OCFile file
= new OCFile(remote
.getRemotePath());
465 file
.setCreationTimestamp(remote
.getCreationTimestamp());
466 file
.setFileLength(remote
.getLength());
467 file
.setMimetype(remote
.getMimeType());
468 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
469 file
.setEtag(remote
.getEtag());
470 file
.setPermissions(remote
.getPermissions());
471 file
.setRemoteId(remote
.getRemoteId());
477 * Checks the storage path of the OCFile received as parameter.
478 * If it's out of the local ownCloud folder, tries to copy the file inside it.
480 * If the copy fails, the link to the local file is nullified. The account of forgotten
481 * files is kept in {@link #mForgottenLocalFiles}
483 * @param file File to check and fix.
485 private void checkAndFixForeignStoragePath(OCFile file
) {
486 String storagePath
= file
.getStoragePath();
487 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
488 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
489 /// fix storagePaths out of the local ownCloud folder
490 File originalFile
= new File(storagePath
);
491 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
492 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
493 file
.setStoragePath(null
);
496 InputStream
in = null
;
497 OutputStream out
= null
;
499 File expectedFile
= new File(expectedPath
);
500 File expectedParent
= expectedFile
.getParentFile();
501 expectedParent
.mkdirs();
502 if (!expectedParent
.isDirectory()) {
503 throw new IOException(
504 "Unexpected error: parent directory could not be created"
507 expectedFile
.createNewFile();
508 if (!expectedFile
.isFile()) {
509 throw new IOException("Unexpected error: target file could not be created");
511 in = new FileInputStream(originalFile
);
512 out
= new FileOutputStream(expectedFile
);
513 byte[] buf
= new byte[1024];
515 while ((len
= in.read(buf
)) > 0){
516 out
.write(buf
, 0, len
);
518 file
.setStoragePath(expectedPath
);
520 } catch (Exception e
) {
521 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
522 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
523 file
.setStoragePath(null
);
527 if (in != null
) in.close();
528 } catch (Exception e
) {
529 Log_OC
.d(TAG
, "Weird exception while closing input stream for "
530 + storagePath
+ " (ignoring)", e
);
533 if (out
!= null
) out
.close();
534 } catch (Exception e
) {
535 Log_OC
.d(TAG
, "Weird exception while closing output stream for "
536 + expectedPath
+ " (ignoring)", e
);
544 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
545 RemoteOperationResult result
= null
;
548 GetRemoteSharesForFileOperation operation
=
549 new GetRemoteSharesForFileOperation(mLocalFolder
.getRemotePath(), false
, true
);
550 result
= operation
.execute(client
);
552 if (result
.isSuccess()) {
553 // update local database
554 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
555 for(Object obj
: result
.getData()) {
556 shares
.add((OCShare
) obj
);
558 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
566 * Scans the default location for saving local copies of files searching for
567 * a 'lost' file with the same full name as the {@link OCFile} received as
570 * @param file File to associate a possible 'lost' local file.
572 private void searchForLocalFileInDefaultPath(OCFile file
) {
573 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
574 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
576 file
.setStoragePath(f
.getAbsolutePath());
577 file
.setLastSyncDateForData(f
.lastModified());
584 * Sends a message to any application component interested in the progress
585 * of the synchronization.
588 * @param dirRemotePath Remote path of a folder that was just synchronized
589 * (with or without success)
592 private void sendLocalBroadcast(
593 String event
, String dirRemotePath
, RemoteOperationResult result
595 Log_OC
.d(TAG
, "Send broadcast " + event
);
596 Intent intent
= new Intent(event
);
597 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
598 if (dirRemotePath
!= null
) {
599 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
601 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
602 mContext
.sendStickyBroadcast(intent
);
603 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
607 public boolean getRemoteFolderChanged() {
608 return mRemoteFolderChanged
;