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
.lib
.network
.OwnCloudClient
;
40 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
41 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
42 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
43 import com
.owncloud
.android
.lib
.operations
.remote
.ReadRemoteFileOperation
;
44 import com
.owncloud
.android
.lib
.operations
.remote
.ReadRemoteFolderOperation
;
45 import com
.owncloud
.android
.lib
.operations
.common
.RemoteFile
;
46 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
47 import com
.owncloud
.android
.utils
.FileStorageUtils
;
48 import com
.owncloud
.android
.utils
.Log_OC
;
53 * Remote operation performing the synchronization of the list of files contained
54 * in a folder identified with its remote path.
56 * Fetches the list and properties of the files contained in the given folder, including their
57 * properties, and updates the local database with them.
59 * Does NOT enter in the child folders to synchronize their contents also.
61 * @author David A. Velasco
63 public class SynchronizeFolderOperation
extends RemoteOperation
{
65 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
68 /** Time stamp for the synchronization process in progress */
69 private long mCurrentSyncTime
;
71 /** Remote folder to synchronize */
72 private OCFile mLocalFolder
;
74 /** Access to the local database */
75 private FileDataStorageManager mStorageManager
;
77 /** Account where the file to synchronize belongs */
78 private Account mAccount
;
80 /** Android context; necessary to send requests to the download service */
81 private Context mContext
;
83 /** Files and folders contained in the synchronized folder after a successful operation */
84 private List
<OCFile
> mChildren
;
86 /** Counter of conflicts found between local and remote files */
87 private int mConflictsFound
;
89 /** Counter of failed operations in synchronization of kept-in-sync files */
90 private int mFailsInFavouritesFound
;
92 /** 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 */
93 private Map
<String
, String
> mForgottenLocalFiles
;
95 /** 'True' means that this operation is part of a full account synchronization */
96 private boolean mSyncFullAccount
;
98 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
99 private boolean mRemoteFolderChanged
;
103 * Creates a new instance of {@link SynchronizeFolderOperation}.
105 * @param remoteFolderPath Remote folder to synchronize.
106 * @param currentSyncTime Time stamp for the synchronization process in progress.
107 * @param localFolderId Identifier in the local database of the folder to synchronize.
108 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
109 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
110 * @param dataStorageManager Interface with the local database.
111 * @param account ownCloud account where the folder is located.
112 * @param context Application context.
114 public SynchronizeFolderOperation( OCFile folder
,
115 long currentSyncTime
,
116 boolean syncFullAccount
,
117 FileDataStorageManager dataStorageManager
,
120 mLocalFolder
= folder
;
121 mCurrentSyncTime
= currentSyncTime
;
122 mSyncFullAccount
= syncFullAccount
;
123 mStorageManager
= dataStorageManager
;
126 mForgottenLocalFiles
= new HashMap
<String
, String
>();
127 mRemoteFolderChanged
= false
;
131 public int getConflictsFound() {
132 return mConflictsFound
;
135 public int getFailsInFavouritesFound() {
136 return mFailsInFavouritesFound
;
139 public Map
<String
, String
> getForgottenLocalFiles() {
140 return mForgottenLocalFiles
;
144 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
146 * @return List of files and folders contained in the synchronized folder.
148 public List
<OCFile
> getChildren() {
153 * Performs the synchronization.
158 protected RemoteOperationResult
run(OwnCloudClient client
) {
159 RemoteOperationResult result
= null
;
160 mFailsInFavouritesFound
= 0;
162 mForgottenLocalFiles
.clear();
164 result
= checkForChanges(client
);
166 if (result
.isSuccess()) {
167 if (mRemoteFolderChanged
) {
168 result
= fetchAndSyncRemoteFolder(client
);
170 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
174 if (!mSyncFullAccount
) {
175 sendStickyBroadcast(false
, mLocalFolder
.getRemotePath(), result
);
183 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
184 mRemoteFolderChanged
= false
;
185 RemoteOperationResult result
= null
;
186 String remotePath
= null
;
188 remotePath
= mLocalFolder
.getRemotePath();
189 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
192 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
193 result
= operation
.execute(client
);
194 if (result
.isSuccess()){
195 OCFile remoteFolder
= FileStorageUtils
.fillOCFile(result
.getData().get(0));
197 // check if remote and local folder are different
198 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
200 result
= new RemoteOperationResult(ResultCode
.OK
);
202 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
205 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
208 if (result
.isException()) {
209 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
211 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
219 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
220 String remotePath
= mLocalFolder
.getRemotePath();
221 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
222 RemoteOperationResult result
= operation
.execute(client
);
223 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
225 if (result
.isSuccess()) {
226 synchronizeData(result
.getData(), client
);
227 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
228 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
231 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
239 private void removeLocalFolder() {
240 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
241 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
242 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
248 * Synchronizes the data retrieved from the server about the contents of the target folder
249 * with the current data in the local database.
251 * Grants that mChildren is updated with fresh data after execution.
253 * @param folderAndFiles Remote folder and children files in Folder
255 * @param client Client instance to the remote server where the data were
257 * @return 'True' when any change was made in the local data, 'false' otherwise.
259 private void synchronizeData(ArrayList
<RemoteFile
> folderAndFiles
, OwnCloudClient client
) {
260 // get 'fresh data' from the database
261 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
263 // parse data from remote folder
264 OCFile remoteFolder
= fillOCFile(folderAndFiles
.get(0));
265 remoteFolder
.setParentId(mLocalFolder
.getParentId());
266 remoteFolder
.setFileId(mLocalFolder
.getFileId());
268 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
270 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
271 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
273 // get current data about local contents of the folder to synchronize
274 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
275 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
276 for (OCFile file
: localFiles
) {
277 localFilesMap
.put(file
.getRemotePath(), file
);
280 // loop to update every child
281 OCFile remoteFile
= null
, localFile
= null
;
282 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
283 /// new OCFile instance with the data from the server
284 remoteFile
= fillOCFile(folderAndFiles
.get(i
));
285 remoteFile
.setParentId(mLocalFolder
.getFileId());
287 /// retrieve local data for the read file
288 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
289 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
291 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
292 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
293 if (localFile
!= null
) {
294 // some properties of local state are kept unmodified
295 remoteFile
.setFileId(localFile
.getFileId());
296 remoteFile
.setKeepInSync(localFile
.keepInSync());
297 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
298 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
299 remoteFile
.setStoragePath(localFile
.getStoragePath());
300 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
301 if (remoteFile
.isFolder()) {
302 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
305 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
308 /// check and fix, if needed, local storage path
309 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
310 searchForLocalFileInDefaultPath(remoteFile
); // legacy
312 /// prepare content synchronization for kept-in-sync files
313 if (remoteFile
.keepInSync()) {
314 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
321 filesToSyncContents
.add(operation
);
324 updatedFiles
.add(remoteFile
);
327 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
328 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
330 // request for the synchronization of file contents AFTER saving current remote properties
331 startContentSynchronizations(filesToSyncContents
, client
);
333 // removal of obsolete files
334 //removeObsoleteFiles();
336 // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
337 //mStorageManager.saveFile(remoteFolder);
338 mChildren
= updatedFiles
;
343 * Performs a list of synchronization operations, determining if a download or upload is needed or
344 * if exists conflict due to changes both in local and remote contents of the each file.
346 * If download or upload is needed, request the operation to the corresponding service and goes on.
348 * @param filesToSyncContents Synchronization operations to execute.
349 * @param client Interface to the remote ownCloud server.
351 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
) {
352 RemoteOperationResult contentsResult
= null
;
353 for (SynchronizeFileOperation op
: filesToSyncContents
) {
354 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
355 if (!contentsResult
.isSuccess()) {
356 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
359 mFailsInFavouritesFound
++;
360 if (contentsResult
.getException() != null
) {
361 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
363 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
366 } // won't let these fails break the synchronization process
371 public boolean isMultiStatus(int status
) {
372 return (status
== HttpStatus
.SC_MULTI_STATUS
);
376 * Creates and populates a new {@link OCFile} object with the data read from the server.
378 * @param remote remote file read from the server (remote file or folder).
379 * @return New OCFile instance representing the remote resource described by we.
381 private OCFile
fillOCFile(RemoteFile remote
) {
382 OCFile file
= new OCFile(remote
.getRemotePath());
383 file
.setCreationTimestamp(remote
.getCreationTimestamp());
384 file
.setFileLength(remote
.getLength());
385 file
.setMimetype(remote
.getMimeType());
386 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
387 file
.setEtag(remote
.getEtag());
393 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
394 * tries to copy the file inside it.
396 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
397 * {@link #mForgottenLocalFiles}
399 * @param file File to check and fix.
401 private void checkAndFixForeignStoragePath(OCFile file
) {
402 String storagePath
= file
.getStoragePath();
403 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
404 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
405 /// fix storagePaths out of the local ownCloud folder
406 File originalFile
= new File(storagePath
);
407 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
408 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
409 file
.setStoragePath(null
);
412 InputStream
in = null
;
413 OutputStream out
= null
;
415 File expectedFile
= new File(expectedPath
);
416 File expectedParent
= expectedFile
.getParentFile();
417 expectedParent
.mkdirs();
418 if (!expectedParent
.isDirectory()) {
419 throw new IOException("Unexpected error: parent directory could not be created");
421 expectedFile
.createNewFile();
422 if (!expectedFile
.isFile()) {
423 throw new IOException("Unexpected error: target file could not be created");
425 in = new FileInputStream(originalFile
);
426 out
= new FileOutputStream(expectedFile
);
427 byte[] buf
= new byte[1024];
429 while ((len
= in.read(buf
)) > 0){
430 out
.write(buf
, 0, len
);
432 file
.setStoragePath(expectedPath
);
434 } catch (Exception e
) {
435 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
436 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
437 file
.setStoragePath(null
);
441 if (in != null
) in.close();
442 } catch (Exception e
) {
443 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
446 if (out
!= null
) out
.close();
447 } catch (Exception e
) {
448 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
456 * Scans the default location for saving local copies of files searching for
457 * a 'lost' file with the same full name as the {@link OCFile} received as
460 * @param file File to associate a possible 'lost' local file.
462 private void searchForLocalFileInDefaultPath(OCFile file
) {
463 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
464 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
466 file
.setStoragePath(f
.getAbsolutePath());
467 file
.setLastSyncDateForData(f
.lastModified());
474 * Sends a message to any application component interested in the progress of the synchronization.
476 * @param inProgress 'True' when the synchronization progress is not finished.
477 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
479 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
480 Intent i
= new Intent(FileSyncService
.getSyncMessage());
481 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
482 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, mAccount
.name
);
483 if (dirRemotePath
!= null
) {
484 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
486 if (result
!= null
) {
487 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
489 mContext
.sendStickyBroadcast(i
);
493 public boolean getRemoteFolderChanged() {
494 return mRemoteFolderChanged
;