1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 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
;
21 import java
.io
.FileInputStream
;
22 import java
.io
.FileOutputStream
;
23 import java
.io
.IOException
;
24 import java
.io
.InputStream
;
25 import java
.io
.OutputStream
;
26 import java
.util
.ArrayList
;
27 import java
.util
.HashMap
;
28 import java
.util
.List
;
30 import java
.util
.Vector
;
32 import org
.apache
.http
.HttpStatus
;
33 import android
.accounts
.Account
;
34 import android
.content
.Context
;
35 import android
.content
.Intent
;
37 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
38 import com
.owncloud
.android
.datamodel
.OCFile
;
39 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavClient
;
40 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavEntry
;
41 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
42 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
43 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
.ResultCode
;
44 import com
.owncloud
.android
.oc_framework
.operations
.remote
.ReadRemoteFileOperation
;
45 import com
.owncloud
.android
.oc_framework
.operations
.remote
.ReadRemoteFolderOperation
;
46 import com
.owncloud
.android
.oc_framework
.operations
.RemoteFile
;
47 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
48 import com
.owncloud
.android
.utils
.FileStorageUtils
;
49 import com
.owncloud
.android
.utils
.Log_OC
;
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 * @author David A. Velasco
64 public class SynchronizeFolderOperation
extends RemoteOperation
{
66 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
69 /** Time stamp for the synchronization process in progress */
70 private long mCurrentSyncTime
;
72 /** Remote folder to synchronize */
73 private OCFile mLocalFolder
;
75 /** Access to the local database */
76 private FileDataStorageManager mStorageManager
;
78 /** Account where the file to synchronize belongs */
79 private Account mAccount
;
81 /** Android context; necessary to send requests to the download service */
82 private Context mContext
;
84 /** Files and folders contained in the synchronized folder after a successful operation */
85 private List
<OCFile
> mChildren
;
87 /** Counter of conflicts found between local and remote files */
88 private int mConflictsFound
;
90 /** Counter of failed operations in synchronization of kept-in-sync files */
91 private int mFailsInFavouritesFound
;
93 /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
94 private Map
<String
, String
> mForgottenLocalFiles
;
96 /** 'True' means that this operation is part of a full account synchronization */
97 private boolean mSyncFullAccount
;
99 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
100 private boolean mRemoteFolderChanged
;
104 * Creates a new instance of {@link SynchronizeFolderOperation}.
106 * @param remoteFolderPath Remote folder to synchronize.
107 * @param currentSyncTime Time stamp for the synchronization process in progress.
108 * @param localFolderId Identifier in the local database of the folder to synchronize.
109 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
110 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
111 * @param dataStorageManager Interface with the local database.
112 * @param account ownCloud account where the folder is located.
113 * @param context Application context.
115 public SynchronizeFolderOperation( OCFile folder
,
116 long currentSyncTime
,
117 boolean syncFullAccount
,
118 FileDataStorageManager dataStorageManager
,
121 mLocalFolder
= folder
;
122 mCurrentSyncTime
= currentSyncTime
;
123 mSyncFullAccount
= syncFullAccount
;
124 mStorageManager
= dataStorageManager
;
127 mForgottenLocalFiles
= new HashMap
<String
, String
>();
128 mRemoteFolderChanged
= false
;
132 public int getConflictsFound() {
133 return mConflictsFound
;
136 public int getFailsInFavouritesFound() {
137 return mFailsInFavouritesFound
;
140 public Map
<String
, String
> getForgottenLocalFiles() {
141 return mForgottenLocalFiles
;
145 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
147 * @return List of files and folders contained in the synchronized folder.
149 public List
<OCFile
> getChildren() {
154 * Performs the synchronization.
159 protected RemoteOperationResult
run(WebdavClient client
) {
160 RemoteOperationResult result
= null
;
161 mFailsInFavouritesFound
= 0;
163 mForgottenLocalFiles
.clear();
165 result
= checkForChanges(client
);
167 if (result
.isSuccess()) {
168 if (mRemoteFolderChanged
) {
169 result
= fetchAndSyncRemoteFolder(client
);
171 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
175 if (!mSyncFullAccount
) {
176 sendStickyBroadcast(false
, mLocalFolder
.getRemotePath(), result
);
184 private RemoteOperationResult
checkForChanges(WebdavClient client
) {
185 mRemoteFolderChanged
= false
;
186 RemoteOperationResult result
= null
;
187 String remotePath
= null
;
189 remotePath
= mLocalFolder
.getRemotePath();
190 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
193 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
194 result
= operation
.execute(client
);
195 if (result
.isSuccess()){
196 OCFile remoteFolder
= FileStorageUtils
.fillOCFile(result
.getData().get(0));
198 // check if remote and local folder are different
199 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
201 result
= new RemoteOperationResult(ResultCode
.OK
);
203 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
206 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
209 if (result
.isException()) {
210 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
212 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
220 private RemoteOperationResult
fetchAndSyncRemoteFolder(WebdavClient client
) {
221 String remotePath
= mLocalFolder
.getRemotePath();
222 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
223 RemoteOperationResult result
= operation
.execute(client
);
224 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
226 if (result
.isSuccess()) {
227 synchronizeData(result
.getData(), client
);
228 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
229 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
232 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
240 private void removeLocalFolder() {
241 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
242 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
243 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
249 * Synchronizes the data retrieved from the server about the contents of the target folder
250 * with the current data in the local database.
252 * Grants that mChildren is updated with fresh data after execution.
254 * @param folderAndFiles Remote folder and children files in Folder
256 * @param client Client instance to the remote server where the data were
258 * @return 'True' when any change was made in the local data, 'false' otherwise.
260 private void synchronizeData(ArrayList
<RemoteFile
> folderAndFiles
, WebdavClient client
) {
261 // get 'fresh data' from the database
262 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
264 // parse data from remote folder
265 OCFile remoteFolder
= fillOCFile(folderAndFiles
.get(0));
266 remoteFolder
.setParentId(mLocalFolder
.getParentId());
267 remoteFolder
.setFileId(mLocalFolder
.getFileId());
269 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
271 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
272 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
274 // get current data about local contents of the folder to synchronize
275 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
276 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
277 for (OCFile file
: localFiles
) {
278 localFilesMap
.put(file
.getRemotePath(), file
);
281 // loop to update every child
282 OCFile remoteFile
= null
, localFile
= null
;
283 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
284 /// new OCFile instance with the data from the server
285 remoteFile
= fillOCFile(folderAndFiles
.get(i
));
286 remoteFile
.setParentId(mLocalFolder
.getFileId());
288 /// retrieve local data for the read file
289 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
290 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
292 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
293 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
294 if (localFile
!= null
) {
295 // some properties of local state are kept unmodified
296 remoteFile
.setFileId(localFile
.getFileId());
297 remoteFile
.setKeepInSync(localFile
.keepInSync());
298 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
299 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
300 remoteFile
.setStoragePath(localFile
.getStoragePath());
301 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
302 if (remoteFile
.isFolder()) {
303 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
306 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
309 /// check and fix, if needed, local storage path
310 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
311 searchForLocalFileInDefaultPath(remoteFile
); // legacy
313 /// prepare content synchronization for kept-in-sync files
314 if (remoteFile
.keepInSync()) {
315 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
322 filesToSyncContents
.add(operation
);
325 updatedFiles
.add(remoteFile
);
328 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
329 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
331 // request for the synchronization of file contents AFTER saving current remote properties
332 startContentSynchronizations(filesToSyncContents
, client
);
334 // removal of obsolete files
335 //removeObsoleteFiles();
337 // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
338 //mStorageManager.saveFile(remoteFolder);
339 mChildren
= updatedFiles
;
344 * Performs a list of synchronization operations, determining if a download or upload is needed or
345 * if exists conflict due to changes both in local and remote contents of the each file.
347 * If download or upload is needed, request the operation to the corresponding service and goes on.
349 * @param filesToSyncContents Synchronization operations to execute.
350 * @param client Interface to the remote ownCloud server.
352 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, WebdavClient client
) {
353 RemoteOperationResult contentsResult
= null
;
354 for (SynchronizeFileOperation op
: filesToSyncContents
) {
355 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
356 if (!contentsResult
.isSuccess()) {
357 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
360 mFailsInFavouritesFound
++;
361 if (contentsResult
.getException() != null
) {
362 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
364 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
367 } // won't let these fails break the synchronization process
372 public boolean isMultiStatus(int status
) {
373 return (status
== HttpStatus
.SC_MULTI_STATUS
);
378 * Creates and populates a new {@link OCFile} object with the data read from the server.
380 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
381 * @return New OCFile instance representing the remote resource described by we.
383 private OCFile
fillOCFile(WebdavEntry we
) {
384 OCFile file
= new OCFile(we
.decodedPath());
385 file
.setCreationTimestamp(we
.createTimestamp());
386 file
.setFileLength(we
.contentLength());
387 file
.setMimetype(we
.contentType());
388 file
.setModificationTimestamp(we
.modifiedTimestamp());
389 file
.setEtag(we
.etag());
394 * Creates and populates a new {@link OCFile} object with the data read from the server.
396 * @param remote remote file read from the server (remote file or folder).
397 * @return New OCFile instance representing the remote resource described by we.
399 private OCFile
fillOCFile(RemoteFile remote
) {
400 OCFile file
= new OCFile(remote
.getRemotePath());
401 file
.setCreationTimestamp(remote
.getCreationTimestamp());
402 file
.setFileLength(remote
.getLength());
403 file
.setMimetype(remote
.getMimeType());
404 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
405 file
.setEtag(remote
.getEtag());
411 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
412 * tries to copy the file inside it.
414 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
415 * {@link #mForgottenLocalFiles}
417 * @param file File to check and fix.
419 private void checkAndFixForeignStoragePath(OCFile file
) {
420 String storagePath
= file
.getStoragePath();
421 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
422 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
423 /// fix storagePaths out of the local ownCloud folder
424 File originalFile
= new File(storagePath
);
425 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
426 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
427 file
.setStoragePath(null
);
430 InputStream
in = null
;
431 OutputStream out
= null
;
433 File expectedFile
= new File(expectedPath
);
434 File expectedParent
= expectedFile
.getParentFile();
435 expectedParent
.mkdirs();
436 if (!expectedParent
.isDirectory()) {
437 throw new IOException("Unexpected error: parent directory could not be created");
439 expectedFile
.createNewFile();
440 if (!expectedFile
.isFile()) {
441 throw new IOException("Unexpected error: target file could not be created");
443 in = new FileInputStream(originalFile
);
444 out
= new FileOutputStream(expectedFile
);
445 byte[] buf
= new byte[1024];
447 while ((len
= in.read(buf
)) > 0){
448 out
.write(buf
, 0, len
);
450 file
.setStoragePath(expectedPath
);
452 } catch (Exception e
) {
453 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
454 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
455 file
.setStoragePath(null
);
459 if (in != null
) in.close();
460 } catch (Exception e
) {
461 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
464 if (out
!= null
) out
.close();
465 } catch (Exception e
) {
466 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
474 * Scans the default location for saving local copies of files searching for
475 * a 'lost' file with the same full name as the {@link OCFile} received as
478 * @param file File to associate a possible 'lost' local file.
480 private void searchForLocalFileInDefaultPath(OCFile file
) {
481 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
482 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
484 file
.setStoragePath(f
.getAbsolutePath());
485 file
.setLastSyncDateForData(f
.lastModified());
492 * Sends a message to any application component interested in the progress of the synchronization.
494 * @param inProgress 'True' when the synchronization progress is not finished.
495 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
497 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
498 Intent i
= new Intent(FileSyncService
.getSyncMessage());
499 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
500 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, mAccount
.name
);
501 if (dirRemotePath
!= null
) {
502 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
504 if (result
!= null
) {
505 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
507 mContext
.sendStickyBroadcast(i
);
511 public boolean getRemoteFolderChanged() {
512 return mRemoteFolderChanged
;