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 org
.apache
.jackrabbit
.webdav
.DavConstants
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import android
.accounts
.Account
;
37 import android
.content
.Context
;
38 import android
.content
.Intent
;
40 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
41 import com
.owncloud
.android
.datamodel
.OCFile
;
42 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavClient
;
43 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavEntry
;
44 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavUtils
;
45 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
46 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
47 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
.ResultCode
;
48 import com
.owncloud
.android
.oc_framework
.operations
.remote
.ReadRemoteFolderOperation
;
49 import com
.owncloud
.android
.oc_framework
.operations
.RemoteFile
;
50 import com
.owncloud
.android
.syncadapter
.FileSyncService
;
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();
72 /** Time stamp for the synchronization process in progress */
73 private long mCurrentSyncTime
;
75 /** Remote folder to synchronize */
76 private OCFile mLocalFolder
;
78 /** Access to the local database */
79 private FileDataStorageManager mStorageManager
;
81 /** Account where the file to synchronize belongs */
82 private Account mAccount
;
84 /** Android context; necessary to send requests to the download service */
85 private Context mContext
;
87 /** Files and folders contained in the synchronized folder after a successful operation */
88 private List
<OCFile
> mChildren
;
90 /** Counter of conflicts found between local and remote files */
91 private int mConflictsFound
;
93 /** Counter of failed operations in synchronization of kept-in-sync files */
94 private int mFailsInFavouritesFound
;
96 /** 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 */
97 private Map
<String
, String
> mForgottenLocalFiles
;
99 /** 'True' means that this operation is part of a full account synchronization */
100 private boolean mSyncFullAccount
;
102 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
103 private boolean mRemoteFolderChanged
;
107 * Creates a new instance of {@link SynchronizeFolderOperation}.
109 * @param remoteFolderPath Remote folder to synchronize.
110 * @param currentSyncTime Time stamp for the synchronization process in progress.
111 * @param localFolderId Identifier in the local database of the folder to synchronize.
112 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
113 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
114 * @param dataStorageManager Interface with the local database.
115 * @param account ownCloud account where the folder is located.
116 * @param context Application context.
118 public SynchronizeFolderOperation( OCFile folder
,
119 long currentSyncTime
,
120 boolean syncFullAccount
,
121 FileDataStorageManager dataStorageManager
,
124 mLocalFolder
= folder
;
125 mCurrentSyncTime
= currentSyncTime
;
126 mSyncFullAccount
= syncFullAccount
;
127 mStorageManager
= dataStorageManager
;
130 mForgottenLocalFiles
= new HashMap
<String
, String
>();
131 mRemoteFolderChanged
= false
;
135 public int getConflictsFound() {
136 return mConflictsFound
;
139 public int getFailsInFavouritesFound() {
140 return mFailsInFavouritesFound
;
143 public Map
<String
, String
> getForgottenLocalFiles() {
144 return mForgottenLocalFiles
;
148 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
150 * @return List of files and folders contained in the synchronized folder.
152 public List
<OCFile
> getChildren() {
157 * Performs the synchronization.
162 protected RemoteOperationResult
run(WebdavClient client
) {
163 RemoteOperationResult result
= null
;
164 mFailsInFavouritesFound
= 0;
166 mForgottenLocalFiles
.clear();
168 result
= checkForChanges(client
);
170 if (result
.isSuccess()) {
171 if (mRemoteFolderChanged
) {
172 result
= fetchAndSyncRemoteFolder(client
);
174 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
178 if (!mSyncFullAccount
) {
179 sendStickyBroadcast(false
, mLocalFolder
.getRemotePath(), result
);
187 private RemoteOperationResult
checkForChanges(WebdavClient client
) {
188 mRemoteFolderChanged
= false
;
189 RemoteOperationResult result
= null
;
190 String remotePath
= null
;
191 PropFindMethod query
= null
;
194 remotePath
= mLocalFolder
.getRemotePath();
195 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
198 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(remotePath
),
199 DavConstants
.PROPFIND_ALL_PROP
,
200 DavConstants
.DEPTH_0
);
201 int status
= client
.executeMethod(query
);
203 // check and process response
204 if (isMultiStatus(status
)) {
205 // parse data from remote folder
206 WebdavEntry we
= new WebdavEntry(query
.getResponseBodyAsMultiStatus().getResponses()[0], client
.getBaseUri().getPath());
207 OCFile remoteFolder
= fillOCFile(we
);
209 // check if remote and local folder are different
210 mRemoteFolderChanged
= !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
212 result
= new RemoteOperationResult(ResultCode
.OK
);
216 client
.exhaustResponse(query
.getResponseBodyAsStream());
217 if (status
== HttpStatus
.SC_NOT_FOUND
) {
220 result
= new RemoteOperationResult(false
, status
, query
.getResponseHeaders());
223 } catch (Exception e
) {
224 result
= new RemoteOperationResult(e
);
229 query
.releaseConnection(); // let the connection available for other methods
230 if (result
.isSuccess()) {
231 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + (mRemoteFolderChanged ?
"changed" : "not changed"));
233 if (result
.isException()) {
234 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage(), result
.getException());
236 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " + result
.getLogMessage());
245 private RemoteOperationResult
fetchAndSyncRemoteFolder(WebdavClient client
) {
246 String remotePath
= mLocalFolder
.getRemotePath();
247 ReadRemoteFolderOperation operation
= new ReadRemoteFolderOperation(remotePath
);
248 RemoteOperationResult result
= operation
.execute(client
);
249 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ remotePath
);
251 if (result
.isSuccess()) {
252 RemoteFile folder
= result
.getFile();
253 ArrayList
<RemoteFile
> files
= result
.getData();
254 synchronizeData(folder
, files
, client
);
255 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
256 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
259 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
267 private void removeLocalFolder() {
268 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
269 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
270 mStorageManager
.removeFolder(mLocalFolder
, true
, (mLocalFolder
.isDown() && mLocalFolder
.getStoragePath().startsWith(currentSavePath
)));
276 * Synchronizes the data retrieved from the server about the contents of the target folder
277 * with the current data in the local database.
279 * Grants that mChildren is updated with fresh data after execution.
281 * @param folder Remote Folder to synchronize
283 * @param files Remote Files in Folder
285 * @param client Client instance to the remote server where the data were
287 * @return 'True' when any change was made in the local data, 'false' otherwise.
289 private void synchronizeData(RemoteFile folder
, ArrayList
<RemoteFile
> files
, WebdavClient client
) {
290 // get 'fresh data' from the database
291 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
293 // parse data from remote folder
294 OCFile remoteFolder
= fillOCFile(folder
);
295 remoteFolder
.setParentId(mLocalFolder
.getParentId());
296 remoteFolder
.setFileId(mLocalFolder
.getFileId());
298 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath() + " changed - starting update of local data ");
300 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(files
.size());
301 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
303 // get current data about local contents of the folder to synchronize
304 List
<OCFile
> localFiles
= mStorageManager
.getFolderContent(mLocalFolder
);
305 Map
<String
, OCFile
> localFilesMap
= new HashMap
<String
, OCFile
>(localFiles
.size());
306 for (OCFile file
: localFiles
) {
307 localFilesMap
.put(file
.getRemotePath(), file
);
310 // loop to update every child
311 OCFile remoteFile
= null
, localFile
= null
;
312 for (RemoteFile file
: files
) {
313 /// new OCFile instance with the data from the server
314 remoteFile
= fillOCFile(file
);
315 remoteFile
.setParentId(mLocalFolder
.getFileId());
317 /// retrieve local data for the read file
318 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
319 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
321 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
322 remoteFile
.setLastSyncDateForProperties(mCurrentSyncTime
);
323 if (localFile
!= null
) {
324 // some properties of local state are kept unmodified
325 remoteFile
.setFileId(localFile
.getFileId());
326 remoteFile
.setKeepInSync(localFile
.keepInSync());
327 remoteFile
.setLastSyncDateForData(localFile
.getLastSyncDateForData());
328 remoteFile
.setModificationTimestampAtLastSyncForData(localFile
.getModificationTimestampAtLastSyncForData());
329 remoteFile
.setStoragePath(localFile
.getStoragePath());
330 remoteFile
.setEtag(localFile
.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
331 if (remoteFile
.isFolder()) {
332 remoteFile
.setFileLength(localFile
.getFileLength()); // TODO move operations about size of folders to FileContentProvider
335 remoteFile
.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
338 /// check and fix, if needed, local storage path
339 checkAndFixForeignStoragePath(remoteFile
); // fixing old policy - now local files must be copied into the ownCloud local folder
340 searchForLocalFileInDefaultPath(remoteFile
); // legacy
342 /// prepare content synchronization for kept-in-sync files
343 if (remoteFile
.keepInSync()) {
344 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
351 filesToSyncContents
.add(operation
);
354 updatedFiles
.add(remoteFile
);
357 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
358 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
360 // request for the synchronization of file contents AFTER saving current remote properties
361 startContentSynchronizations(filesToSyncContents
, client
);
363 // removal of obsolete files
364 //removeObsoleteFiles();
366 // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
367 //mStorageManager.saveFile(remoteFolder);
368 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
, WebdavClient 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
);
407 * Creates and populates a new {@link OCFile} object with the data read from the server.
409 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
410 * @return New OCFile instance representing the remote resource described by we.
412 private OCFile
fillOCFile(WebdavEntry we
) {
413 OCFile file
= new OCFile(we
.decodedPath());
414 file
.setCreationTimestamp(we
.createTimestamp());
415 file
.setFileLength(we
.contentLength());
416 file
.setMimetype(we
.contentType());
417 file
.setModificationTimestamp(we
.modifiedTimestamp());
418 file
.setEtag(we
.etag());
423 * Creates and populates a new {@link OCFile} object with the data read from the server.
425 * @param remote remote file read from the server (remote file or folder).
426 * @return New OCFile instance representing the remote resource described by we.
428 private OCFile
fillOCFile(RemoteFile remote
) {
429 OCFile file
= new OCFile(remote
.getRemotePath());
430 file
.setCreationTimestamp(remote
.getCreationTimestamp());
431 file
.setFileLength(remote
.getLength());
432 file
.setMimetype(remote
.getMimeType());
433 file
.setModificationTimestamp(remote
.getModifiedTimestamp());
434 file
.setEtag(remote
.getEtag());
440 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
441 * tries to copy the file inside it.
443 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
444 * {@link #mForgottenLocalFiles}
446 * @param file File to check and fix.
448 private void checkAndFixForeignStoragePath(OCFile file
) {
449 String storagePath
= file
.getStoragePath();
450 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
451 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
452 /// fix storagePaths out of the local ownCloud folder
453 File originalFile
= new File(storagePath
);
454 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
455 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
456 file
.setStoragePath(null
);
459 InputStream
in = null
;
460 OutputStream out
= null
;
462 File expectedFile
= new File(expectedPath
);
463 File expectedParent
= expectedFile
.getParentFile();
464 expectedParent
.mkdirs();
465 if (!expectedParent
.isDirectory()) {
466 throw new IOException("Unexpected error: parent directory could not be created");
468 expectedFile
.createNewFile();
469 if (!expectedFile
.isFile()) {
470 throw new IOException("Unexpected error: target file could not be created");
472 in = new FileInputStream(originalFile
);
473 out
= new FileOutputStream(expectedFile
);
474 byte[] buf
= new byte[1024];
476 while ((len
= in.read(buf
)) > 0){
477 out
.write(buf
, 0, len
);
479 file
.setStoragePath(expectedPath
);
481 } catch (Exception e
) {
482 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
483 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
484 file
.setStoragePath(null
);
488 if (in != null
) in.close();
489 } catch (Exception e
) {
490 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
493 if (out
!= null
) out
.close();
494 } catch (Exception e
) {
495 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
503 * Scans the default location for saving local copies of files searching for
504 * a 'lost' file with the same full name as the {@link OCFile} received as
507 * @param file File to associate a possible 'lost' local file.
509 private void searchForLocalFileInDefaultPath(OCFile file
) {
510 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
511 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
513 file
.setStoragePath(f
.getAbsolutePath());
514 file
.setLastSyncDateForData(f
.lastModified());
521 * Sends a message to any application component interested in the progress of the synchronization.
523 * @param inProgress 'True' when the synchronization progress is not finished.
524 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
526 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
527 Intent i
= new Intent(FileSyncService
.getSyncMessage());
528 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
529 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, mAccount
.name
);
530 if (dirRemotePath
!= null
) {
531 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
533 if (result
!= null
) {
534 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
536 mContext
.sendStickyBroadcast(i
);
540 public boolean getRemoteFolderChanged() {
541 return mRemoteFolderChanged
;