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
;
40 import com
.owncloud
.android
.lib
.network
.OwnCloudClient
;
41 import com
.owncloud
.android
.lib
.operations
.common
.OCShare
;
42 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperation
;
43 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
;
44 import com
.owncloud
.android
.lib
.operations
.common
.RemoteOperationResult
.ResultCode
;
45 import com
.owncloud
.android
.lib
.operations
.remote
.GetSharesForFileRemoteOperation
;
46 import com
.owncloud
.android
.lib
.operations
.remote
.ReadRemoteFileOperation
;
47 import com
.owncloud
.android
.lib
.operations
.remote
.ReadRemoteFolderOperation
;
48 import com
.owncloud
.android
.lib
.operations
.common
.RemoteFile
;
49 import com
.owncloud
.android
.lib
.utils
.FileUtils
;
50 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
51 import com
.owncloud
.android
.utils
.FileStorageUtils
;
52 import com
.owncloud
.android
.utils
.Log_OC
;
57 * Remote operation performing the synchronization of the list of files contained
58 * in a folder identified with its remote path.
60 * Fetches the list and properties of the files contained in the given folder, including their
61 * properties, and updates the local database with them.
63 * Does NOT enter in the child folders to synchronize their contents also.
65 * @author David A. Velasco
67 public class SynchronizeFolderOperation
extends RemoteOperation
{
69 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
71 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
72 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
74 /** Time stamp for the synchronization process in progress */
75 private long mCurrentSyncTime
;
77 /** Remote folder to synchronize */
78 private OCFile mLocalFolder
;
80 /** Access to the local database */
81 private FileDataStorageManager mStorageManager
;
83 /** Account where the file to synchronize belongs */
84 private Account mAccount
;
86 /** Android context; necessary to send requests to the download service */
87 private Context mContext
;
89 /** Files and folders contained in the synchronized folder after a successful operation */
90 private List
<OCFile
> mChildren
;
92 /** Counter of conflicts found between local and remote files */
93 private int mConflictsFound
;
95 /** Counter of failed operations in synchronization of kept-in-sync files */
96 private int mFailsInFavouritesFound
;
98 /** 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 */
99 private Map
<String
, String
> mForgottenLocalFiles
;
101 /** 'True' means that this operation is part of a full account synchronization */
102 private boolean mSyncFullAccount
;
104 /** 'True' means that Share resources bound to the files into the folder should be refreshed also */
105 private boolean mIsShareSupported
;
107 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
108 private boolean mRemoteFolderChanged
;
112 * Creates a new instance of {@link SynchronizeFolderOperation}.
114 * @param remoteFolderPath Remote folder to synchronize.
115 * @param currentSyncTime Time stamp for the synchronization process in progress.
116 * @param localFolderId Identifier in the local database of the folder to synchronize.
117 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
118 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
119 * @param dataStorageManager Interface with the local database.
120 * @param account ownCloud account where the folder is located.
121 * @param context Application context.
123 public SynchronizeFolderOperation( OCFile folder
,
124 long currentSyncTime
,
125 boolean syncFullAccount
,
126 boolean isShareSupported
,
127 FileDataStorageManager dataStorageManager
,
130 mLocalFolder
= folder
;
131 mCurrentSyncTime
= currentSyncTime
;
132 mSyncFullAccount
= syncFullAccount
;
133 mIsShareSupported
= isShareSupported
;
134 mStorageManager
= dataStorageManager
;
137 mForgottenLocalFiles
= new HashMap
<String
, String
>();
138 mRemoteFolderChanged
= false
;
142 public int getConflictsFound() {
143 return mConflictsFound
;
146 public int getFailsInFavouritesFound() {
147 return mFailsInFavouritesFound
;
150 public Map
<String
, String
> getForgottenLocalFiles() {
151 return mForgottenLocalFiles
;
155 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
157 * @return List of files and folders contained in the synchronized folder.
159 public List
<OCFile
> getChildren() {
164 * Performs the synchronization.
169 protected RemoteOperationResult
run(OwnCloudClient client
) {
170 RemoteOperationResult result
= null
;
171 mFailsInFavouritesFound
= 0;
173 mForgottenLocalFiles
.clear();
175 if (FileUtils
.PATH_SEPARATOR
.equals(mLocalFolder
.getRemotePath()) && !mSyncFullAccount
) {
176 updateOCVersion(client
);
179 result
= checkForChanges(client
);
181 if (result
.isSuccess()) {
182 if (mRemoteFolderChanged
) {
183 result
= fetchAndSyncRemoteFolder(client
);
185 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
189 if (!mSyncFullAccount
) {
190 sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
);
193 if (result
.isSuccess() && mIsShareSupported
) {
194 RemoteOperationResult shareResult
= refreshSharesForFolder(client
);
195 if (shareResult
.getCode() != ResultCode
.FILE_NOT_FOUND
) {
196 result
= shareResult
;
197 } // else , keep the previous result ; being conservative for servers where Sharing API is supported, but disabled
200 if (!mSyncFullAccount
) {
201 sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
);
209 private void updateOCVersion(OwnCloudClient client
) {
210 UpdateOCVersionOperation update
= new UpdateOCVersionOperation(mAccount
, mContext
);
211 RemoteOperationResult result
= update
.execute(client
);
212 if (result
.isSuccess()) {
213 mIsShareSupported
= update
.getOCVersion().isSharedSupported();
218 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
219 mRemoteFolderChanged
= false
;
220 RemoteOperationResult result
= null
;
221 String remotePath
= null
;
223 remotePath
= mLocalFolder
.getRemotePath();
224 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
227 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
228 result
= operation
.execute(client
);
229 if (result
.isSuccess()){
230 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
232 // check if remote and local folder are different
233 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
235 result
= new RemoteOperationResult(ResultCode
.OK
);
237 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
241 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
244 if (result
.isException()) {
245 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
247 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
255 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
256 String remotePath
= mLocalFolder
.getRemotePath();
257 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
258 RemoteOperationResult result
= operation
.execute(client
);
259 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
261 if (result
.isSuccess()) {
262 synchronizeData(result
.getData(), client
);
263 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
264 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
267 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
275 private void removeLocalFolder() {
276 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
277 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
278 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
284 * Synchronizes the data retrieved from the server about the contents of the target folder
285 * with the current data in the local database.
287 * Grants that mChildren is updated with fresh data after execution.
289 * @param folderAndFiles Remote folder and children files in Folder
291 * @param client Client instance to the remote server where the data were
293 * @return 'True' when any change was made in the local data, 'false' otherwise.
295 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
296 // get 'fresh data' from the database
297 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
299 // parse data from remote folder
300 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
301 remoteFolder
.setParentId(mLocalFolder
.getParentId());
302 remoteFolder
.setFileId(mLocalFolder
.getFileId());
304 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
306 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
307 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
309 // get current data about local contents of the folder to synchronize
310 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
311 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
312 for (OCFile file
: localFiles
) {
313 localFilesMap
.put(file
.getRemotePath(), file
);
316 // loop to update every child
317 OCFile remoteFile
= null
, localFile
= null
;
318 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
319 /// new OCFile instance with the data from the server
320 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
321 remoteFile
.setParentId(mLocalFolder
.getFileId());
323 /// retrieve local data for the read file
324 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
325 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
327 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
328 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
329 if (localFile
!= null
) {
330 // some properties of local state are kept unmodified
331 remoteFile
.setFileId(localFile
.getFileId());
332 remoteFile
.setKeepInSync(localFile
.keepInSync());
333 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
334 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
335 remoteFile
.setStoragePath(localFile
.getStoragePath());
336 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
337 if (remoteFile
.isFolder()) {
338 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
341 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
344 /// check and fix, if needed, local storage path
345 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
346 searchForLocalFileInDefaultPath(remoteFile
); // legacy
348 /// prepare content synchronization for kept-in-sync files
349 if (remoteFile
.keepInSync()) {
350 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
357 filesToSyncContents
.add(operation
);
360 updatedFiles
.add(remoteFile
);
363 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
364 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
366 // request for the synchronization of file contents AFTER saving current remote properties
367 startContentSynchronizations(filesToSyncContents
, client
);
369 mChildren
= updatedFiles
;
373 * Performs a list of synchronization operations, determining if a download or upload is needed or
374 * if exists conflict due to changes both in local and remote contents of the each file.
376 * If download or upload is needed, request the operation to the corresponding service and goes on.
378 * @param filesToSyncContents Synchronization operations to execute.
379 * @param client Interface to the remote ownCloud server.
381 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
) {
382 RemoteOperationResult contentsResult
= null
;
383 for (SynchronizeFileOperation op
: filesToSyncContents
) {
384 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
385 if (!contentsResult
.isSuccess()) {
386 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
389 mFailsInFavouritesFound
++;
390 if (contentsResult
.getException() != null
) {
391 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
393 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
396 } // won't let these fails break the synchronization process
401 public boolean isMultiStatus(int status
) {
402 return (status
== HttpStatus
.SC_MULTI_STATUS
);
406 * Creates and populates a new {@link OCFile} object with the data read from the server.
408 * @param remote remote file read from the server (remote file or folder).
409 * @return New OCFile instance representing the remote resource described by we.
411 private OCFile
fillOCFile(RemoteFile remote
) {
412 OCFile file
= new OCFile(remote
.getRemotePath());
413 file
.setCreationTimestamp(remote
.getCreationTimestamp());
414 file
.setFileLength(remote
.getLength());
415 file
.setMimetype(remote
.getMimeType());
416 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
417 file
.setEtag(remote
.getEtag());
423 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
424 * tries to copy the file inside it.
426 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
427 * {@link #mForgottenLocalFiles}
429 * @param file File to check and fix.
431 private void checkAndFixForeignStoragePath(OCFile file
) {
432 String storagePath
= file
.getStoragePath();
433 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
434 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
435 /// fix storagePaths out of the local ownCloud folder
436 File originalFile
= new File(storagePath
);
437 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
438 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
439 file
.setStoragePath(null
);
442 InputStream
in = null
;
443 OutputStream out
= null
;
445 File expectedFile
= new File(expectedPath
);
446 File expectedParent
= expectedFile
.getParentFile();
447 expectedParent
.mkdirs();
448 if (!expectedParent
.isDirectory()) {
449 throw new IOException("Unexpected error: parent directory could not be created");
451 expectedFile
.createNewFile();
452 if (!expectedFile
.isFile()) {
453 throw new IOException("Unexpected error: target file could not be created");
455 in = new FileInputStream(originalFile
);
456 out
= new FileOutputStream(expectedFile
);
457 byte[] buf
= new byte[1024];
459 while ((len
= in.read(buf
)) > 0){
460 out
.write(buf
, 0, len
);
462 file
.setStoragePath(expectedPath
);
464 } catch (Exception e
) {
465 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
466 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
467 file
.setStoragePath(null
);
471 if (in != null
) in.close();
472 } catch (Exception e
) {
473 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
476 if (out
!= null
) out
.close();
477 } catch (Exception e
) {
478 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
486 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
487 RemoteOperationResult result
= null
;
490 GetSharesForFileRemoteOperation operation
= new GetSharesForFileRemoteOperation(mLocalFolder
.getRemotePath(), false
, true
);
491 result
= operation
.execute(client
);
493 if (result
.isSuccess()) {
494 // update local database
495 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
496 for(Object obj
: result
.getData()) {
497 shares
.add((OCShare
) obj
);
499 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
507 * Scans the default location for saving local copies of files searching for
508 * a 'lost' file with the same full name as the {@link OCFile} received as
511 * @param file File to associate a possible 'lost' local file.
513 private void searchForLocalFileInDefaultPath(OCFile file
) {
514 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
515 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
517 file
.setStoragePath(f
.getAbsolutePath());
518 file
.setLastSyncDateForData(f
.lastModified());
525 * Sends a message to any application component interested in the progress of the synchronization.
528 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
531 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
532 Log_OC
.d(TAG
, "Send broadcast " + event
);
533 Intent intent
= new Intent(event
);
534 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
535 if (dirRemotePath
!= null
) {
536 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
538 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
539 mContext
.sendStickyBroadcast(intent
);
540 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
544 public boolean getRemoteFolderChanged() {
545 return mRemoteFolderChanged
;