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
;
36 //import android.support.v4.content.LocalBroadcastManager;
38 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
39 import com
.owncloud
.android
.datamodel
.OCFile
;
41 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
42 import com
.owncloud
.android
.lib
.resources
.shares
.OCShare
;
43 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
44 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
45 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
46 import com
.owncloud
.android
.lib
.resources
.shares
.GetRemoteSharesForFileOperation
;
47 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
48 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFileOperation
;
49 import com
.owncloud
.android
.lib
.resources
.files
.ReadRemoteFolderOperation
;
50 import com
.owncloud
.android
.lib
.resources
.files
.RemoteFile
;
52 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
53 import com
.owncloud
.android
.utils
.FileStorageUtils
;
54 import com
.owncloud
.android
.utils
.Log_OC
;
59 * Remote operation performing the synchronization of the list of files contained
60 * in a folder identified with its remote path.
62 * Fetches the list and properties of the files contained in the given folder, including their
63 * properties, and updates the local database with them.
65 * Does NOT enter in the child folders to synchronize their contents also.
67 * @author David A. Velasco
69 public class SynchronizeFolderOperation
extends RemoteOperation
{
71 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
73 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
74 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
76 /** Time stamp for the synchronization process in progress */
77 private long mCurrentSyncTime
;
79 /** Remote folder to synchronize */
80 private OCFile mLocalFolder
;
82 /** Access to the local database */
83 private FileDataStorageManager mStorageManager
;
85 /** Account where the file to synchronize belongs */
86 private Account mAccount
;
88 /** Android context; necessary to send requests to the download service */
89 private Context mContext
;
91 /** Files and folders contained in the synchronized folder after a successful operation */
92 private List
<OCFile
> mChildren
;
94 /** Counter of conflicts found between local and remote files */
95 private int mConflictsFound
;
97 /** Counter of failed operations in synchronization of kept-in-sync files */
98 private int mFailsInFavouritesFound
;
100 /** 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 */
101 private Map
<String
, String
> mForgottenLocalFiles
;
103 /** 'True' means that this operation is part of a full account synchronization */
104 private boolean mSyncFullAccount
;
106 /** 'True' means that Share resources bound to the files into the folder should be refreshed also */
107 private boolean mIsShareSupported
;
109 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
110 private boolean mRemoteFolderChanged
;
114 * Creates a new instance of {@link SynchronizeFolderOperation}.
116 * @param remoteFolderPath Remote folder to synchronize.
117 * @param currentSyncTime Time stamp for the synchronization process in progress.
118 * @param localFolderId Identifier in the local database of the folder to synchronize.
119 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
120 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
121 * @param dataStorageManager Interface with the local database.
122 * @param account ownCloud account where the folder is located.
123 * @param context Application context.
125 public SynchronizeFolderOperation( OCFile folder
,
126 long currentSyncTime
,
127 boolean syncFullAccount
,
128 boolean isShareSupported
,
129 FileDataStorageManager dataStorageManager
,
132 mLocalFolder
= folder
;
133 mCurrentSyncTime
= currentSyncTime
;
134 mSyncFullAccount
= syncFullAccount
;
135 mIsShareSupported
= isShareSupported
;
136 mStorageManager
= dataStorageManager
;
139 mForgottenLocalFiles
= new HashMap
<String
, String
>();
140 mRemoteFolderChanged
= false
;
144 public int getConflictsFound() {
145 return mConflictsFound
;
148 public int getFailsInFavouritesFound() {
149 return mFailsInFavouritesFound
;
152 public Map
<String
, String
> getForgottenLocalFiles() {
153 return mForgottenLocalFiles
;
157 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
159 * @return List of files and folders contained in the synchronized folder.
161 public List
<OCFile
> getChildren() {
166 * Performs the synchronization.
171 protected RemoteOperationResult
run(OwnCloudClient client
) {
172 RemoteOperationResult result
= null
;
173 mFailsInFavouritesFound
= 0;
175 mForgottenLocalFiles
.clear();
177 if (FileUtils
.PATH_SEPARATOR
.equals(mLocalFolder
.getRemotePath()) && !mSyncFullAccount
) {
178 updateOCVersion(client
);
181 result
= checkForChanges(client
);
183 if (result
.isSuccess()) {
184 if (mRemoteFolderChanged
) {
185 result
= fetchAndSyncRemoteFolder(client
);
187 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
191 if (!mSyncFullAccount
) {
192 sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
);
195 if (result
.isSuccess() && mIsShareSupported
&& !mSyncFullAccount
) {
196 refreshSharesForFolder(client
); // share result is ignored
199 if (!mSyncFullAccount
) {
200 sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
);
208 private void updateOCVersion(OwnCloudClient client
) {
209 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(mAccount
, mContext
);
210 RemoteOperationResult result
= update
.execute(client
);
211 if (result
.isSuccess()) {
212 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
217 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
218 mRemoteFolderChanged
= false
;
219 RemoteOperationResult result
= null
;
220 String remotePath
= null
;
222 remotePath
= mLocalFolder
.getRemotePath();
223 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
226 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
227 result
= operation
.execute(client
);
228 if (result
.isSuccess()){
229 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
231 // check if remote and local folder are different
232 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
234 result
= new RemoteOperationResult(ResultCode
.OK
);
236 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
240 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
243 if (result
.isException()) {
244 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
246 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
254 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
255 String remotePath
= mLocalFolder
.getRemotePath();
256 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
257 RemoteOperationResult result
= operation
.execute(client
);
258 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
260 if (result
.isSuccess()) {
261 synchronizeData(result
.getData(), client
);
262 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
263 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
266 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
274 private void removeLocalFolder() {
275 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
276 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
277 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
283 * Synchronizes the data retrieved from the server about the contents of the target folder
284 * with the current data in the local database.
286 * Grants that mChildren is updated with fresh data after execution.
288 * @param folderAndFiles Remote folder and children files in Folder
290 * @param client Client instance to the remote server where the data were
292 * @return 'True' when any change was made in the local data, 'false' otherwise.
294 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
295 // get 'fresh data' from the database
296 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
298 // parse data from remote folder
299 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
300 remoteFolder
.setParentId(mLocalFolder
.getParentId());
301 remoteFolder
.setFileId(mLocalFolder
.getFileId());
303 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
305 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
306 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
308 // get current data about local contents of the folder to synchronize
309 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
310 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
311 for (OCFile file
: localFiles
) {
312 localFilesMap
.put(file
.getRemotePath(), file
);
315 // loop to update every child
316 OCFile remoteFile
= null
, localFile
= null
;
317 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
318 /// new OCFile instance with the data from the server
319 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
320 remoteFile
.setParentId(mLocalFolder
.getFileId());
322 /// retrieve local data for the read file
323 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
324 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
326 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
327 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
328 if (localFile
!= null
) {
329 // some properties of local state are kept unmodified
330 remoteFile
.setFileId(localFile
.getFileId());
331 remoteFile
.setKeepInSync(localFile
.keepInSync());
332 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
333 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
334 remoteFile
.setStoragePath(localFile
.getStoragePath());
335 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
336 if (remoteFile
.isFolder()) {
337 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
340 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
343 /// check and fix, if needed, local storage path
344 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
345 searchForLocalFileInDefaultPath(remoteFile
); // legacy
347 /// prepare content synchronization for kept-in-sync files
348 if (remoteFile
.keepInSync()) {
349 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
356 filesToSyncContents
.add(operation
);
359 updatedFiles
.add(remoteFile
);
362 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
363 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
365 // request for the synchronization of file contents AFTER saving current remote properties
366 startContentSynchronizations(filesToSyncContents
, client
);
368 mChildren
= updatedFiles
;
372 * Performs a list of synchronization operations, determining if a download or upload is needed or
373 * if exists conflict due to changes both in local and remote contents of the each file.
375 * If download or upload is needed, request the operation to the corresponding service and goes on.
377 * @param filesToSyncContents Synchronization operations to execute.
378 * @param client Interface to the remote ownCloud server.
380 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
) {
381 RemoteOperationResult contentsResult
= null
;
382 for (SynchronizeFileOperation op
: filesToSyncContents
) {
383 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
384 if (!contentsResult
.isSuccess()) {
385 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
388 mFailsInFavouritesFound
++;
389 if (contentsResult
.getException() != null
) {
390 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
392 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
395 } // won't let these fails break the synchronization process
400 public boolean isMultiStatus(int status
) {
401 return (status
== HttpStatus
.SC_MULTI_STATUS
);
405 * Creates and populates a new {@link OCFile} object with the data read from the server.
407 * @param remote remote file read from the server (remote file or folder).
408 * @return New OCFile instance representing the remote resource described by we.
410 private OCFile
fillOCFile(RemoteFile remote
) {
411 OCFile file
= new OCFile(remote
.getRemotePath());
412 file
.setCreationTimestamp(remote
.getCreationTimestamp());
413 file
.setFileLength(remote
.getLength());
414 file
.setMimetype(remote
.getMimeType());
415 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
416 file
.setEtag(remote
.getEtag());
422 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
423 * tries to copy the file inside it.
425 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
426 * {@link #mForgottenLocalFiles}
428 * @param file File to check and fix.
430 private void checkAndFixForeignStoragePath(OCFile file
) {
431 String storagePath
= file
.getStoragePath();
432 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
433 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
434 /// fix storagePaths out of the local ownCloud folder
435 File originalFile
= new File(storagePath
);
436 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
437 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
438 file
.setStoragePath(null
);
441 InputStream
in = null
;
442 OutputStream out
= null
;
444 File expectedFile
= new File(expectedPath
);
445 File expectedParent
= expectedFile
.getParentFile();
446 expectedParent
.mkdirs();
447 if (!expectedParent
.isDirectory()) {
448 throw new IOException("Unexpected error: parent directory could not be created");
450 expectedFile
.createNewFile();
451 if (!expectedFile
.isFile()) {
452 throw new IOException("Unexpected error: target file could not be created");
454 in = new FileInputStream(originalFile
);
455 out
= new FileOutputStream(expectedFile
);
456 byte[] buf
= new byte[1024];
458 while ((len
= in.read(buf
)) > 0){
459 out
.write(buf
, 0, len
);
461 file
.setStoragePath(expectedPath
);
463 } catch (Exception e
) {
464 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
465 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
466 file
.setStoragePath(null
);
470 if (in != null
) in.close();
471 } catch (Exception e
) {
472 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
475 if (out
!= null
) out
.close();
476 } catch (Exception e
) {
477 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
485 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
486 RemoteOperationResult result
= null
;
489 GetRemoteSharesForFileOperation operation
= new GetRemoteSharesForFileOperation(mLocalFolder
.getRemotePath(), false
, true
);
490 result
= operation
.execute(client
);
492 if (result
.isSuccess()) {
493 // update local database
494 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
495 for(Object obj
: result
.getData()) {
496 shares
.add((OCShare
) obj
);
498 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
506 * Scans the default location for saving local copies of files searching for
507 * a 'lost' file with the same full name as the {@link OCFile} received as
510 * @param file File to associate a possible 'lost' local file.
512 private void searchForLocalFileInDefaultPath(OCFile file
) {
513 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
514 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
516 file
.setStoragePath(f
.getAbsolutePath());
517 file
.setLastSyncDateForData(f
.lastModified());
524 * Sends a message to any application component interested in the progress of the synchronization.
527 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
530 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
531 Log_OC
.d(TAG
, "Send broadcast " + event
);
532 Intent intent
= new Intent(event
);
533 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
534 if (dirRemotePath
!= null
) {
535 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
537 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
538 mContext
.sendStickyBroadcast(intent
);
539 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
543 public boolean getRemoteFolderChanged() {
544 return mRemoteFolderChanged
;