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
.syncadapter
.FileSyncAdapter
;
50 import com
.owncloud
.android
.utils
.FileStorageUtils
;
51 import com
.owncloud
.android
.utils
.Log_OC
;
56 * Remote operation performing the synchronization of the list of files contained
57 * in a folder identified with its remote path.
59 * Fetches the list and properties of the files contained in the given folder, including their
60 * properties, and updates the local database with them.
62 * Does NOT enter in the child folders to synchronize their contents also.
64 * @author David A. Velasco
66 public class SynchronizeFolderOperation
extends RemoteOperation
{
68 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
70 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
71 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED
= SynchronizeFolderOperation
.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
73 /** Time stamp for the synchronization process in progress */
74 private long mCurrentSyncTime
;
76 /** Remote folder to synchronize */
77 private OCFile mLocalFolder
;
79 /** Access to the local database */
80 private FileDataStorageManager mStorageManager
;
82 /** Account where the file to synchronize belongs */
83 private Account mAccount
;
85 /** Android context; necessary to send requests to the download service */
86 private Context mContext
;
88 /** Files and folders contained in the synchronized folder after a successful operation */
89 private List
<OCFile
> mChildren
;
91 /** Counter of conflicts found between local and remote files */
92 private int mConflictsFound
;
94 /** Counter of failed operations in synchronization of kept-in-sync files */
95 private int mFailsInFavouritesFound
;
97 /** 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 */
98 private Map
<String
, String
> mForgottenLocalFiles
;
100 /** 'True' means that this operation is part of a full account synchronization */
101 private boolean mSyncFullAccount
;
103 /** 'True' means that Share resources bound to the files into the folder should be refreshed also */
104 private boolean mRefreshShares
;
106 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
107 private boolean mRemoteFolderChanged
;
111 * Creates a new instance of {@link SynchronizeFolderOperation}.
113 * @param remoteFolderPath Remote folder to synchronize.
114 * @param currentSyncTime Time stamp for the synchronization process in progress.
115 * @param localFolderId Identifier in the local database of the folder to synchronize.
116 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
117 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
118 * @param dataStorageManager Interface with the local database.
119 * @param account ownCloud account where the folder is located.
120 * @param context Application context.
122 public SynchronizeFolderOperation( OCFile folder
,
123 long currentSyncTime
,
124 boolean syncFullAccount
,
125 boolean refreshShares
,
126 FileDataStorageManager dataStorageManager
,
129 mLocalFolder
= folder
;
130 mCurrentSyncTime
= currentSyncTime
;
131 mSyncFullAccount
= syncFullAccount
;
132 mRefreshShares
= refreshShares
;
133 mStorageManager
= dataStorageManager
;
136 mForgottenLocalFiles
= new HashMap
<String
, String
>();
137 mRemoteFolderChanged
= false
;
141 public int getConflictsFound() {
142 return mConflictsFound
;
145 public int getFailsInFavouritesFound() {
146 return mFailsInFavouritesFound
;
149 public Map
<String
, String
> getForgottenLocalFiles() {
150 return mForgottenLocalFiles
;
154 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
156 * @return List of files and folders contained in the synchronized folder.
158 public List
<OCFile
> getChildren() {
163 * Performs the synchronization.
168 protected RemoteOperationResult
run(OwnCloudClient client
) {
169 RemoteOperationResult result
= null
;
170 mFailsInFavouritesFound
= 0;
172 mForgottenLocalFiles
.clear();
174 result
= checkForChanges(client
);
176 if (result
.isSuccess()) {
177 if (mRemoteFolderChanged
) {
178 result
= fetchAndSyncRemoteFolder(client
);
180 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
184 if (!mSyncFullAccount
) {
185 sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
);
188 if (result
.isSuccess() && mRefreshShares
) {
189 RemoteOperationResult shareResult
= refreshSharesForFolder(client
);
190 if (shareResult
.getCode() != ResultCode
.FILE_NOT_FOUND
) {
191 result
= shareResult
;
192 } // else , keep the previous result ; being conservative for servers where Sharing API is supported, but disabled
195 if (!mSyncFullAccount
) {
196 sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
);
203 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
204 mRemoteFolderChanged
= false
;
205 RemoteOperationResult result
= null
;
206 String remotePath
= null
;
208 remotePath
= mLocalFolder
.getRemotePath();
209 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
212 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
213 result
= operation
.execute(client
);
214 if (result
.isSuccess()){
215 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
217 // check if remote and local folder are different
218 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
220 result
= new RemoteOperationResult(ResultCode
.OK
);
222 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
226 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
229 if (result
.isException()) {
230 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
232 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
240 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
241 String remotePath
= mLocalFolder
.getRemotePath();
242 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
243 RemoteOperationResult result
= operation
.execute(client
);
244 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
246 if (result
.isSuccess()) {
247 synchronizeData(result
.getData(), client
);
248 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
249 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
252 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
260 private void removeLocalFolder() {
261 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
262 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
263 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
269 * Synchronizes the data retrieved from the server about the contents of the target folder
270 * with the current data in the local database.
272 * Grants that mChildren is updated with fresh data after execution.
274 * @param folderAndFiles Remote folder and children files in Folder
276 * @param client Client instance to the remote server where the data were
278 * @return 'True' when any change was made in the local data, 'false' otherwise.
280 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
281 // get 'fresh data' from the database
282 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
284 // parse data from remote folder
285 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
286 remoteFolder
.setParentId(mLocalFolder
.getParentId());
287 remoteFolder
.setFileId(mLocalFolder
.getFileId());
289 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
291 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
292 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
294 // get current data about local contents of the folder to synchronize
295 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
296 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
297 for (OCFile file
: localFiles
) {
298 localFilesMap
.put(file
.getRemotePath(), file
);
301 // loop to update every child
302 OCFile remoteFile
= null
, localFile
= null
;
303 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
304 /// new OCFile instance with the data from the server
305 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
306 remoteFile
.setParentId(mLocalFolder
.getFileId());
308 /// retrieve local data for the read file
309 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
310 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
312 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
313 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
314 if (localFile
!= null
) {
315 // some properties of local state are kept unmodified
316 remoteFile
.setFileId(localFile
.getFileId());
317 remoteFile
.setKeepInSync(localFile
.keepInSync());
318 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
319 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
320 remoteFile
.setStoragePath(localFile
.getStoragePath());
321 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
322 if (remoteFile
.isFolder()) {
323 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
326 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
329 /// check and fix, if needed, local storage path
330 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
331 searchForLocalFileInDefaultPath(remoteFile
); // legacy
333 /// prepare content synchronization for kept-in-sync files
334 if (remoteFile
.keepInSync()) {
335 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
342 filesToSyncContents
.add(operation
);
345 updatedFiles
.add(remoteFile
);
348 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
349 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
351 // request for the synchronization of file contents AFTER saving current remote properties
352 startContentSynchronizations(filesToSyncContents
, client
);
354 mChildren
= updatedFiles
;
358 * Performs a list of synchronization operations, determining if a download or upload is needed or
359 * if exists conflict due to changes both in local and remote contents of the each file.
361 * If download or upload is needed, request the operation to the corresponding service and goes on.
363 * @param filesToSyncContents Synchronization operations to execute.
364 * @param client Interface to the remote ownCloud server.
366 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
) {
367 RemoteOperationResult contentsResult
= null
;
368 for (SynchronizeFileOperation op
: filesToSyncContents
) {
369 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
370 if (!contentsResult
.isSuccess()) {
371 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
374 mFailsInFavouritesFound
++;
375 if (contentsResult
.getException() != null
) {
376 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
378 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
381 } // won't let these fails break the synchronization process
386 public boolean isMultiStatus(int status
) {
387 return (status
== HttpStatus
.SC_MULTI_STATUS
);
391 * Creates and populates a new {@link OCFile} object with the data read from the server.
393 * @param remote remote file read from the server (remote file or folder).
394 * @return New OCFile instance representing the remote resource described by we.
396 private OCFile
fillOCFile(RemoteFile remote
) {
397 OCFile file
= new OCFile(remote
.getRemotePath());
398 file
.setCreationTimestamp(remote
.getCreationTimestamp());
399 file
.setFileLength(remote
.getLength());
400 file
.setMimetype(remote
.getMimeType());
401 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
402 file
.setEtag(remote
.getEtag());
408 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
409 * tries to copy the file inside it.
411 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
412 * {@link #mForgottenLocalFiles}
414 * @param file File to check and fix.
416 private void checkAndFixForeignStoragePath(OCFile file
) {
417 String storagePath
= file
.getStoragePath();
418 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
419 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
420 /// fix storagePaths out of the local ownCloud folder
421 File originalFile
= new File(storagePath
);
422 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
423 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
424 file
.setStoragePath(null
);
427 InputStream
in = null
;
428 OutputStream out
= null
;
430 File expectedFile
= new File(expectedPath
);
431 File expectedParent
= expectedFile
.getParentFile();
432 expectedParent
.mkdirs();
433 if (!expectedParent
.isDirectory()) {
434 throw new IOException("Unexpected error: parent directory could not be created");
436 expectedFile
.createNewFile();
437 if (!expectedFile
.isFile()) {
438 throw new IOException("Unexpected error: target file could not be created");
440 in = new FileInputStream(originalFile
);
441 out
= new FileOutputStream(expectedFile
);
442 byte[] buf
= new byte[1024];
444 while ((len
= in.read(buf
)) > 0){
445 out
.write(buf
, 0, len
);
447 file
.setStoragePath(expectedPath
);
449 } catch (Exception e
) {
450 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
451 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
452 file
.setStoragePath(null
);
456 if (in != null
) in.close();
457 } catch (Exception e
) {
458 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
461 if (out
!= null
) out
.close();
462 } catch (Exception e
) {
463 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
471 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
472 RemoteOperationResult result
= null
;
475 GetSharesForFileRemoteOperation operation
= new GetSharesForFileRemoteOperation(mLocalFolder
.getRemotePath(), false
, true
);
476 result
= operation
.execute(client
);
478 if (result
.isSuccess()) {
479 // update local database
480 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
481 for(Object obj
: result
.getData()) {
482 shares
.add((OCShare
) obj
);
484 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
492 * Scans the default location for saving local copies of files searching for
493 * a 'lost' file with the same full name as the {@link OCFile} received as
496 * @param file File to associate a possible 'lost' local file.
498 private void searchForLocalFileInDefaultPath(OCFile file
) {
499 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
500 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
502 file
.setStoragePath(f
.getAbsolutePath());
503 file
.setLastSyncDateForData(f
.lastModified());
510 * Sends a message to any application component interested in the progress of the synchronization.
513 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
516 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
517 Log_OC
.d(TAG
, "Send broadcast " + event
);
518 Intent intent
= new Intent(event
);
519 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
520 if (dirRemotePath
!= null
) {
521 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
523 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
524 mContext
.sendStickyBroadcast(intent
);
525 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
529 public boolean getRemoteFolderChanged() {
530 return mRemoteFolderChanged
;