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
.HashMap
;
27 import java
.util
.List
;
29 import java
.util
.Vector
;
31 import org
.apache
.http
.HttpStatus
;
32 import org
.apache
.jackrabbit
.webdav
.MultiStatus
;
33 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
35 import android
.accounts
.Account
;
36 import android
.content
.Context
;
38 import com
.owncloud
.android
.Log_OC
;
39 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
40 import com
.owncloud
.android
.datamodel
.OCFile
;
41 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
42 import com
.owncloud
.android
.utils
.FileStorageUtils
;
44 import eu
.alefzero
.webdav
.WebdavClient
;
45 import eu
.alefzero
.webdav
.WebdavEntry
;
46 import eu
.alefzero
.webdav
.WebdavUtils
;
50 * Remote operation performing the synchronization a the contents of a remote folder with the local database
52 * @author David A. Velasco
54 public class SynchronizeFolderOperation
extends RemoteOperation
{
56 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
58 /** Remote folder to synchronize */
59 private String mRemotePath
;
61 /** Timestamp for the synchronization in progress */
62 private long mCurrentSyncTime
;
64 /** Id of the folder to synchronize in the local database */
65 private long mParentId
;
67 public long getParentId() {
72 /** Access to the local database */
73 private DataStorageManager mStorageManager
;
75 /** Account where the file to synchronize belongs */
76 private Account mAccount
;
78 /** Android context; necessary to send requests to the download service; maybe something to refactor */
79 private Context mContext
;
81 /** Files and folders contained in the synchronized folder */
82 private List
<OCFile
> mChildren
;
84 private int mConflictsFound
;
86 private int mFailsInFavouritesFound
;
88 private Map
<String
, String
> mForgottenLocalFiles
;
91 public SynchronizeFolderOperation( String remotePath
,
94 DataStorageManager dataStorageManager
,
97 mRemotePath
= remotePath
;
98 mCurrentSyncTime
= currentSyncTime
;
100 mStorageManager
= dataStorageManager
;
103 mForgottenLocalFiles
= new HashMap
<String
, String
>();
107 public int getConflictsFound() {
108 return mConflictsFound
;
111 public int getFailsInFavouritesFound() {
112 return mFailsInFavouritesFound
;
115 public Map
<String
, String
> getForgottenLocalFiles() {
116 return mForgottenLocalFiles
;
120 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
122 * @return List of files and folders contained in the synchronized folder.
124 public List
<OCFile
> getChildren() {
130 protected RemoteOperationResult
run(WebdavClient client
) {
131 RemoteOperationResult result
= null
;
132 mFailsInFavouritesFound
= 0;
134 mForgottenLocalFiles
.clear();
136 // code before in FileSyncAdapter.fetchData
137 PropFindMethod query
= null
;
139 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ ", fetching files in " + mRemotePath
);
142 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mRemotePath
));
143 int status
= client
.executeMethod(query
);
145 // check and process response - /// TODO take into account all the possible status per child-resource
146 if (isMultiStatus(status
)) {
147 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
149 // synchronize properties of the parent folder, if necessary
150 if (mParentId
== DataStorageManager
.ROOT_PARENT_ID
) {
151 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], client
.getBaseUri().getPath());
152 OCFile parent
= fillOCFile(we
);
153 mStorageManager
.saveFile(parent
);
154 mParentId
= parent
.getFileId();
157 // read contents in folder
158 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
159 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
160 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
161 /// new OCFile instance with the data from the server
162 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], client
.getBaseUri().getPath());
163 OCFile file
= fillOCFile(we
);
165 /// set data about local state, keeping unchanged former data if existing
166 file
.setLastSyncDateForProperties(mCurrentSyncTime
);
167 OCFile oldFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
168 if (oldFile
!= null
) {
169 file
.setKeepInSync(oldFile
.keepInSync());
170 file
.setLastSyncDateForData(oldFile
.getLastSyncDateForData());
171 file
.setModificationTimestampAtLastSyncForData(oldFile
.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
172 checkAndFixForeignStoragePath(oldFile
);
173 file
.setStoragePath(oldFile
.getStoragePath());
176 /// scan default location if local copy of file is not linked in OCFile instance
177 if (file
.getStoragePath() == null
&& !file
.isDirectory()) {
178 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
180 file
.setStoragePath(f
.getAbsolutePath());
181 file
.setLastSyncDateForData(f
.lastModified());
185 /// prepare content synchronization for kept-in-sync files
186 if (file
.keepInSync()) {
187 SynchronizeFileOperation operation
= new SynchronizeFileOperation( oldFile
,
195 filesToSyncContents
.add(operation
);
198 updatedFiles
.add(file
);
201 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
202 mStorageManager
.saveFiles(updatedFiles
);
204 // request for the synchronization of files AFTER saving last properties
205 SynchronizeFileOperation op
= null
;
206 RemoteOperationResult contentsResult
= null
;
207 for (int i
=0; i
< filesToSyncContents
.size(); i
++) {
208 op
= filesToSyncContents
.get(i
);
209 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
210 if (!contentsResult
.isSuccess()) {
211 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
214 mFailsInFavouritesFound
++;
215 if (contentsResult
.getException() != null
) {
216 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
218 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
221 } // won't let these fails break the synchronization process
225 // removal of obsolete files
226 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
228 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
229 for (int i
=0; i
< mChildren
.size(); ) {
230 file
= mChildren
.get(i
);
231 if (file
.getLastSyncDateForProperties() != mCurrentSyncTime
) {
232 Log_OC
.d(TAG
, "removing file: " + file
);
233 mStorageManager
.removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
241 client
.exhaustResponse(query
.getResponseBodyAsStream());
244 // prepare result object
245 if (isMultiStatus(status
)) {
246 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
247 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
250 result
= new RemoteOperationResult(true
, status
);
253 result
= new RemoteOperationResult(false
, status
);
255 Log_OC
.i(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
258 } catch (Exception e
) {
259 result
= new RemoteOperationResult(e
);
260 Log_OC
.e(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage(), result
.getException());
264 query
.releaseConnection(); // let the connection available for other methods
271 public boolean isMultiStatus(int status
) {
272 return (status
== HttpStatus
.SC_MULTI_STATUS
);
277 * Creates and populates a new {@link OCFile} object with the data read from the server.
279 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
280 * @return New OCFile instance representing the remote resource described by we.
282 private OCFile
fillOCFile(WebdavEntry we
) {
283 OCFile file
= new OCFile(we
.decodedPath());
284 file
.setCreationTimestamp(we
.createTimestamp());
285 file
.setFileLength(we
.contentLength());
286 file
.setMimetype(we
.contentType());
287 file
.setModificationTimestamp(we
.modifiedTimestamp());
288 file
.setParentId(mParentId
);
294 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
295 * tries to copy the file inside it.
297 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
298 * {@link #mForgottenLocalFiles}
300 * @param file File to check and fix.
302 private void checkAndFixForeignStoragePath(OCFile file
) {
303 String storagePath
= file
.getStoragePath();
304 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
305 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
306 /// fix storagePaths out of the local ownCloud folder
307 File originalFile
= new File(storagePath
);
308 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
309 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
310 file
.setStoragePath(null
);
313 InputStream
in = null
;
314 OutputStream out
= null
;
316 File expectedFile
= new File(expectedPath
);
317 File expectedParent
= expectedFile
.getParentFile();
318 expectedParent
.mkdirs();
319 if (!expectedParent
.isDirectory()) {
320 throw new IOException("Unexpected error: parent directory could not be created");
322 expectedFile
.createNewFile();
323 if (!expectedFile
.isFile()) {
324 throw new IOException("Unexpected error: target file could not be created");
326 in = new FileInputStream(originalFile
);
327 out
= new FileOutputStream(expectedFile
);
328 byte[] buf
= new byte[1024];
330 while ((len
= in.read(buf
)) > 0){
331 out
.write(buf
, 0, len
);
333 file
.setStoragePath(expectedPath
);
335 } catch (Exception e
) {
336 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
337 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
338 file
.setStoragePath(null
);
342 if (in != null
) in.close();
343 } catch (Exception e
) {
344 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
347 if (out
!= null
) out
.close();
348 } catch (Exception e
) {
349 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);