1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.operations
;
22 import java
.util
.List
;
23 import java
.util
.Vector
;
25 import org
.apache
.http
.HttpStatus
;
26 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
27 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
29 import android
.accounts
.Account
;
30 import android
.content
.Context
;
31 import android
.util
.Log
;
33 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
34 import com
.owncloud
.android
.datamodel
.OCFile
;
35 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
36 import com
.owncloud
.android
.utils
.FileStorageUtils
;
38 import eu
.alefzero
.webdav
.WebdavClient
;
39 import eu
.alefzero
.webdav
.WebdavEntry
;
40 import eu
.alefzero
.webdav
.WebdavUtils
;
44 * Remote operation performing the synchronization a the contents of a remote folder with the local database
46 * @author David A. Velasco
48 public class SynchronizeFolderOperation
extends RemoteOperation
{
50 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
52 /** Remote folder to synchronize */
53 private String mRemotePath
;
55 /** Timestamp for the synchronization in progress */
56 private long mCurrentSyncTime
;
58 /** Id of the folder to synchronize in the local database */
59 private long mParentId
;
61 /** Access to the local database */
62 private DataStorageManager mStorageManager
;
64 /** Account where the file to synchronize belongs */
65 private Account mAccount
;
67 /** Android context; necessary to send requests to the download service; maybe something to refactor */
68 private Context mContext
;
70 /** Files and folders contained in the synchronized folder */
71 private List
<OCFile
> mChildren
;
73 private int mConflictsFound
;
75 private int mFailsInFavouritesFound
;
78 public SynchronizeFolderOperation( String remotePath
,
81 DataStorageManager dataStorageManager
,
84 mRemotePath
= remotePath
;
85 mCurrentSyncTime
= currentSyncTime
;
87 mStorageManager
= dataStorageManager
;
93 public int getConflictsFound() {
94 return mConflictsFound
;
97 public int getFailsInFavouritesFound() {
98 return mFailsInFavouritesFound
;
102 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
104 * @return List of files and folders contained in the synchronized folder.
106 public List
<OCFile
> getChildren() {
112 protected RemoteOperationResult
run(WebdavClient client
) {
113 RemoteOperationResult result
= null
;
114 mFailsInFavouritesFound
= 0;
117 // code before in FileSyncAdapter.fetchData
118 PropFindMethod query
= null
;
120 Log
.d(TAG
, "Synchronizing " + mAccount
.name
+ ", fetching files in " + mRemotePath
);
123 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mRemotePath
));
124 int status
= client
.executeMethod(query
);
126 // check and process response - /// TODO take into account all the possible status per child-resource
127 if (isMultiStatus(status
)) {
128 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
130 // synchronize properties of the parent folder, if necessary
131 if (mParentId
== DataStorageManager
.ROOT_PARENT_ID
) {
132 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], client
.getBaseUri().getPath());
133 OCFile parent
= fillOCFile(we
);
134 mStorageManager
.saveFile(parent
);
135 mParentId
= parent
.getFileId();
138 // read contents in folder
139 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
140 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
141 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
142 /// new OCFile instance with the data from the server
143 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], client
.getBaseUri().getPath());
144 OCFile file
= fillOCFile(we
);
146 /// set data about local state, keeping unchanged former data if existing
147 file
.setLastSyncDateForProperties(mCurrentSyncTime
);
148 OCFile oldFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
149 if (oldFile
!= null
) {
150 file
.setKeepInSync(oldFile
.keepInSync());
151 file
.setLastSyncDateForData(oldFile
.getLastSyncDateForData());
152 file
.setStoragePath(oldFile
.getStoragePath());
155 /// scan default location if local copy of file is not linked in OCFile instance
156 if (file
.getStoragePath() == null
&& !file
.isDirectory()) {
157 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
159 file
.setStoragePath(f
.getAbsolutePath());
160 file
.setLastSyncDateForData(f
.lastModified());
164 /// prepare content synchronization for kept-in-sync files
165 if (file
.keepInSync()) {
166 SynchronizeFileOperation operation
= new SynchronizeFileOperation( oldFile
,
174 filesToSyncContents
.add(operation
);
177 updatedFiles
.add(file
);
180 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
181 mStorageManager
.saveFiles(updatedFiles
);
183 // request for the synchronization of files AFTER saving last properties
184 SynchronizeFileOperation op
= null
;
185 RemoteOperationResult contentsResult
= null
;
186 for (int i
=0; i
< filesToSyncContents
.size(); i
++) {
187 op
= filesToSyncContents
.get(i
);
188 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
189 if (!contentsResult
.isSuccess()) {
190 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
193 mFailsInFavouritesFound
++;
194 if (contentsResult
.getException() != null
) {
195 Log
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
197 Log
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
200 } // won't let these fails break the synchronization process
204 // removal of obsolete files
205 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
207 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
208 for (int i
=0; i
< mChildren
.size(); ) {
209 file
= mChildren
.get(i
);
210 if (file
.getLastSyncDateForProperties() != mCurrentSyncTime
) {
211 Log
.d(TAG
, "removing file: " + file
);
212 mStorageManager
.removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
220 client
.exhaustResponse(query
.getResponseBodyAsStream());
223 // prepare result object
224 if (isMultiStatus(status
)) {
225 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
226 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
229 result
= new RemoteOperationResult(true
, status
);
232 result
= new RemoteOperationResult(false
, status
);
234 Log
.i(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
237 } catch (Exception e
) {
238 result
= new RemoteOperationResult(e
);
239 Log
.e(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage(), result
.getException());
243 query
.releaseConnection(); // let the connection available for other methods
250 public boolean isMultiStatus(int status
) {
251 return (status
== HttpStatus
.SC_MULTI_STATUS
);
256 * Creates and populates a new {@link OCFile} object with the data read from the server.
258 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
259 * @return New OCFile instance representing the remote resource described by we.
261 private OCFile
fillOCFile(WebdavEntry we
) {
262 OCFile file
= new OCFile(we
.decodedPath());
263 file
.setCreationTimestamp(we
.createTimestamp());
264 file
.setFileLength(we
.contentLength());
265 file
.setMimetype(we
.contentType());
266 file
.setModificationTimestamp(we
.modifiedTimesamp());
267 file
.setParentId(mParentId
);