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 the remote folder changed from last synchronization and should be fetched */
104 private boolean mRemoteFolderChanged
;
108 * Creates a new instance of {@link SynchronizeFolderOperation}.
110 * @param remoteFolderPath Remote folder to synchronize.
111 * @param currentSyncTime Time stamp for the synchronization process in progress.
112 * @param localFolderId Identifier in the local database of the folder to synchronize.
113 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
114 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
115 * @param dataStorageManager Interface with the local database.
116 * @param account ownCloud account where the folder is located.
117 * @param context Application context.
119 public SynchronizeFolderOperation( OCFile folder
,
120 long currentSyncTime
,
121 boolean syncFullAccount
,
122 FileDataStorageManager dataStorageManager
,
125 mLocalFolder
= folder
;
126 mCurrentSyncTime
= currentSyncTime
;
127 mSyncFullAccount
= syncFullAccount
;
128 mStorageManager
= dataStorageManager
;
131 mForgottenLocalFiles
= new HashMap
<String
, String
>();
132 mRemoteFolderChanged
= false
;
136 public int getConflictsFound() {
137 return mConflictsFound
;
140 public int getFailsInFavouritesFound() {
141 return mFailsInFavouritesFound
;
144 public Map
<String
, String
> getForgottenLocalFiles() {
145 return mForgottenLocalFiles
;
149 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
151 * @return List of files and folders contained in the synchronized folder.
153 public List
<OCFile
> getChildren() {
158 * Performs the synchronization.
163 protected RemoteOperationResult
run(OwnCloudClient client
) {
164 RemoteOperationResult result
= null
;
165 mFailsInFavouritesFound
= 0;
167 mForgottenLocalFiles
.clear();
169 result
= checkForChanges(client
);
171 if (result
.isSuccess()) {
172 if (mRemoteFolderChanged
) {
173 result
= fetchAndSyncRemoteFolder(client
);
175 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
179 if (!mSyncFullAccount
) {
180 sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
, mLocalFolder
.getRemotePath(), result
);
183 if (result
.isSuccess()) {
184 result
= refreshSharesForFolder(client
);
187 if (!mSyncFullAccount
) {
188 sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED
, mLocalFolder
.getRemotePath(), result
);
195 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
196 mRemoteFolderChanged
= false
;
197 RemoteOperationResult result
= null
;
198 String remotePath
= null
;
200 remotePath
= mLocalFolder
.getRemotePath();
201 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
204 ReadRemoteFileOperation operation
= new ReadRemoteFileOperation(remotePath
);
205 result
= operation
.execute(client
);
206 if (result
.isSuccess()){
207 OCFile remoteFolder
= FileStorageUtils
.fillOCFile((RemoteFile
) result
.getData().get(0));
209 // check if remote and local folder are different
210 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
212 result
= new RemoteOperationResult(ResultCode
.OK
);
214 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
218 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
221 if (result
.isException()) {
222 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
224 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
232 private RemoteOperationResult
fetchAndSyncRemoteFolder(OwnCloudClient client
) {
233 String remotePath
= mLocalFolder
.getRemotePath();
234 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
235 RemoteOperationResult result
= operation
.execute(client
);
236 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
238 if (result
.isSuccess()) {
239 synchronizeData(result
.getData(), client
);
240 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
241 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
244 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
252 private void removeLocalFolder() {
253 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
254 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
255 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
261 * Synchronizes the data retrieved from the server about the contents of the target folder
262 * with the current data in the local database.
264 * Grants that mChildren is updated with fresh data after execution.
266 * @param folderAndFiles Remote folder and children files in Folder
268 * @param client Client instance to the remote server where the data were
270 * @return 'True' when any change was made in the local data, 'false' otherwise.
272 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
273 // get 'fresh data' from the database
274 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
276 // parse data from remote folder
277 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
278 remoteFolder
.setParentId(mLocalFolder
.getParentId());
279 remoteFolder
.setFileId(mLocalFolder
.getFileId());
281 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
283 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
284 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
286 // get current data about local contents of the folder to synchronize
287 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
288 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
289 for (OCFile file
: localFiles
) {
290 localFilesMap
.put(file
.getRemotePath(), file
);
293 // loop to update every child
294 OCFile remoteFile
= null
, localFile
= null
;
295 for (int i
=1; i
<folderAndFiles
.size(); i
++) {
296 /// new OCFile instance with the data from the server
297 remoteFile
= fillOCFile((RemoteFile
)folderAndFiles
.get(i
));
298 remoteFile
.setParentId(mLocalFolder
.getFileId());
300 /// retrieve local data for the read file
301 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
302 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
304 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
305 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
306 if (localFile
!= null
) {
307 // some properties of local state are kept unmodified
308 remoteFile
.setFileId(localFile
.getFileId());
309 remoteFile
.setKeepInSync(localFile
.keepInSync());
310 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
311 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
312 remoteFile
.setStoragePath(localFile
.getStoragePath());
313 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
314 if (remoteFile
.isFolder()) {
315 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
318 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
321 /// check and fix, if needed, local storage path
322 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
323 searchForLocalFileInDefaultPath(remoteFile
); // legacy
325 /// prepare content synchronization for kept-in-sync files
326 if (remoteFile
.keepInSync()) {
327 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
334 filesToSyncContents
.add(operation
);
337 updatedFiles
.add(remoteFile
);
340 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
341 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
343 // request for the synchronization of file contents AFTER saving current remote properties
344 startContentSynchronizations(filesToSyncContents
, client
);
346 mChildren
= updatedFiles
;
350 * Performs a list of synchronization operations, determining if a download or upload is needed or
351 * if exists conflict due to changes both in local and remote contents of the each file.
353 * If download or upload is needed, request the operation to the corresponding service and goes on.
355 * @param filesToSyncContents Synchronization operations to execute.
356 * @param client Interface to the remote ownCloud server.
358 private void startContentSynchronizations(List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
) {
359 RemoteOperationResult contentsResult
= null
;
360 for (SynchronizeFileOperation op
: filesToSyncContents
) {
361 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
362 if (!contentsResult
.isSuccess()) {
363 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
366 mFailsInFavouritesFound
++;
367 if (contentsResult
.getException() != null
) {
368 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
370 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
373 } // won't let these fails break the synchronization process
378 public boolean isMultiStatus(int status
) {
379 return (status
== HttpStatus
.SC_MULTI_STATUS
);
383 * Creates and populates a new {@link OCFile} object with the data read from the server.
385 * @param remote remote file read from the server (remote file or folder).
386 * @return New OCFile instance representing the remote resource described by we.
388 private OCFile
fillOCFile(RemoteFile remote
) {
389 OCFile file
= new OCFile(remote
.getRemotePath());
390 file
.setCreationTimestamp(remote
.getCreationTimestamp());
391 file
.setFileLength(remote
.getLength());
392 file
.setMimetype(remote
.getMimeType());
393 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
394 file
.setEtag(remote
.getEtag());
400 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
401 * tries to copy the file inside it.
403 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
404 * {@link #mForgottenLocalFiles}
406 * @param file File to check and fix.
408 private void checkAndFixForeignStoragePath(OCFile file
) {
409 String storagePath
= file
.getStoragePath();
410 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
411 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
412 /// fix storagePaths out of the local ownCloud folder
413 File originalFile
= new File(storagePath
);
414 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
415 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
416 file
.setStoragePath(null
);
419 InputStream
in = null
;
420 OutputStream out
= null
;
422 File expectedFile
= new File(expectedPath
);
423 File expectedParent
= expectedFile
.getParentFile();
424 expectedParent
.mkdirs();
425 if (!expectedParent
.isDirectory()) {
426 throw new IOException("Unexpected error: parent directory could not be created");
428 expectedFile
.createNewFile();
429 if (!expectedFile
.isFile()) {
430 throw new IOException("Unexpected error: target file could not be created");
432 in = new FileInputStream(originalFile
);
433 out
= new FileOutputStream(expectedFile
);
434 byte[] buf
= new byte[1024];
436 while ((len
= in.read(buf
)) > 0){
437 out
.write(buf
, 0, len
);
439 file
.setStoragePath(expectedPath
);
441 } catch (Exception e
) {
442 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
443 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
444 file
.setStoragePath(null
);
448 if (in != null
) in.close();
449 } catch (Exception e
) {
450 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
453 if (out
!= null
) out
.close();
454 } catch (Exception e
) {
455 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
463 private RemoteOperationResult
refreshSharesForFolder(OwnCloudClient client
) {
464 RemoteOperationResult result
= null
;
467 GetSharesForFileRemoteOperation operation
= new GetSharesForFileRemoteOperation(mLocalFolder
.getRemotePath(), false
, true
);
468 result
= operation
.execute(client
);
470 if (result
.isSuccess()) {
471 // update local database
472 ArrayList
<OCShare
> shares
= new ArrayList
<OCShare
>();
473 for(Object obj
: result
.getData()) {
474 shares
.add((OCShare
) obj
);
476 mStorageManager
.saveSharesInFolder(shares
, mLocalFolder
);
484 * Scans the default location for saving local copies of files searching for
485 * a 'lost' file with the same full name as the {@link OCFile} received as
488 * @param file File to associate a possible 'lost' local file.
490 private void searchForLocalFileInDefaultPath(OCFile file
) {
491 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
492 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
494 file
.setStoragePath(f
.getAbsolutePath());
495 file
.setLastSyncDateForData(f
.lastModified());
502 * Sends a message to any application component interested in the progress of the synchronization.
505 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
508 private void sendLocalBroadcast(String event
, String dirRemotePath
, RemoteOperationResult result
) {
509 Intent intent
= new Intent(event
);
510 intent
.putExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
, mAccount
.name
);
511 if (dirRemotePath
!= null
) {
512 intent
.putExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
, dirRemotePath
);
514 intent
.putExtra(FileSyncAdapter
.EXTRA_RESULT
, result
);
515 mContext
.sendStickyBroadcast(intent
);
516 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
520 public boolean getRemoteFolderChanged() {
521 return mRemoteFolderChanged
;