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 as published by
6 * the Free Software Foundation, either version 2 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
.io
.FileInputStream
;
23 import java
.io
.FileOutputStream
;
24 import java
.io
.IOException
;
25 import java
.io
.InputStream
;
26 import java
.io
.OutputStream
;
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
.MultiStatus
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import android
.accounts
.Account
;
37 import android
.content
.Context
;
38 import android
.util
.Log
;
40 import com
.owncloud
.android
.Log_OC
;
41 import com
.owncloud
.android
.datamodel
.DataStorageManager
;
42 import com
.owncloud
.android
.datamodel
.OCFile
;
43 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
44 import com
.owncloud
.android
.utils
.FileStorageUtils
;
46 import eu
.alefzero
.webdav
.WebdavClient
;
47 import eu
.alefzero
.webdav
.WebdavEntry
;
48 import eu
.alefzero
.webdav
.WebdavUtils
;
52 * Remote operation performing the synchronization a the contents of a remote folder with the local database
54 * @author David A. Velasco
56 public class SynchronizeFolderOperation
extends RemoteOperation
{
58 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
60 /** Remote folder to synchronize */
61 private String mRemotePath
;
63 /** Timestamp for the synchronization in progress */
64 private long mCurrentSyncTime
;
66 /** Id of the folder to synchronize in the local database */
67 private long mParentId
;
69 /** Access to the local database */
70 private DataStorageManager mStorageManager
;
72 /** Account where the file to synchronize belongs */
73 private Account mAccount
;
75 /** Android context; necessary to send requests to the download service; maybe something to refactor */
76 private Context mContext
;
78 /** Files and folders contained in the synchronized folder */
79 private List
<OCFile
> mChildren
;
81 private int mConflictsFound
;
83 private int mFailsInFavouritesFound
;
85 private Map
<String
, String
> mForgottenLocalFiles
;
88 public SynchronizeFolderOperation( String remotePath
,
91 DataStorageManager dataStorageManager
,
94 mRemotePath
= remotePath
;
95 mCurrentSyncTime
= currentSyncTime
;
97 mStorageManager
= dataStorageManager
;
100 mForgottenLocalFiles
= new HashMap
<String
, String
>();
104 public int getConflictsFound() {
105 return mConflictsFound
;
108 public int getFailsInFavouritesFound() {
109 return mFailsInFavouritesFound
;
112 public Map
<String
, String
> getForgottenLocalFiles() {
113 return mForgottenLocalFiles
;
117 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
119 * @return List of files and folders contained in the synchronized folder.
121 public List
<OCFile
> getChildren() {
127 protected RemoteOperationResult
run(WebdavClient client
) {
128 RemoteOperationResult result
= null
;
129 mFailsInFavouritesFound
= 0;
131 mForgottenLocalFiles
.clear();
133 // code before in FileSyncAdapter.fetchData
134 PropFindMethod query
= null
;
136 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ ", fetching files in " + mRemotePath
);
139 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mRemotePath
));
140 int status
= client
.executeMethod(query
);
142 // check and process response - /// TODO take into account all the possible status per child-resource
143 if (isMultiStatus(status
)) {
144 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
146 // synchronize properties of the parent folder, if necessary
147 if (mParentId
== DataStorageManager
.ROOT_PARENT_ID
) {
148 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], client
.getBaseUri().getPath());
149 OCFile parent
= fillOCFile(we
);
150 mStorageManager
.saveFile(parent
);
151 mParentId
= parent
.getFileId();
154 // read contents in folder
155 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
156 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
157 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
158 /// new OCFile instance with the data from the server
159 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], client
.getBaseUri().getPath());
160 OCFile file
= fillOCFile(we
);
162 /// set data about local state, keeping unchanged former data if existing
163 file
.setLastSyncDateForProperties(mCurrentSyncTime
);
164 OCFile oldFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
165 if (oldFile
!= null
) {
166 file
.setKeepInSync(oldFile
.keepInSync());
167 file
.setLastSyncDateForData(oldFile
.getLastSyncDateForData());
168 file
.setModificationTimestampAtLastSyncForData(oldFile
.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
169 checkAndFixForeignStoragePath(oldFile
);
170 file
.setStoragePath(oldFile
.getStoragePath());
173 /// scan default location if local copy of file is not linked in OCFile instance
174 if (file
.getStoragePath() == null
&& !file
.isDirectory()) {
175 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
177 file
.setStoragePath(f
.getAbsolutePath());
178 file
.setLastSyncDateForData(f
.lastModified());
182 /// prepare content synchronization for kept-in-sync files
183 if (file
.keepInSync()) {
184 SynchronizeFileOperation operation
= new SynchronizeFileOperation( oldFile
,
192 filesToSyncContents
.add(operation
);
195 updatedFiles
.add(file
);
198 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
199 mStorageManager
.saveFiles(updatedFiles
);
201 // request for the synchronization of files AFTER saving last properties
202 SynchronizeFileOperation op
= null
;
203 RemoteOperationResult contentsResult
= null
;
204 for (int i
=0; i
< filesToSyncContents
.size(); i
++) {
205 op
= filesToSyncContents
.get(i
);
206 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
207 if (!contentsResult
.isSuccess()) {
208 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
211 mFailsInFavouritesFound
++;
212 if (contentsResult
.getException() != null
) {
213 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
215 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
218 } // won't let these fails break the synchronization process
222 // removal of obsolete files
223 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
225 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
226 for (int i
=0; i
< mChildren
.size(); ) {
227 file
= mChildren
.get(i
);
228 if (file
.getLastSyncDateForProperties() != mCurrentSyncTime
) {
229 Log_OC
.d(TAG
, "removing file: " + file
);
230 mStorageManager
.removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
238 client
.exhaustResponse(query
.getResponseBodyAsStream());
241 // prepare result object
242 if (isMultiStatus(status
)) {
243 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
244 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
247 result
= new RemoteOperationResult(true
, status
);
250 result
= new RemoteOperationResult(false
, status
);
252 Log_OC
.i(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
255 } catch (Exception e
) {
256 result
= new RemoteOperationResult(e
);
257 Log_OC
.e(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage(), result
.getException());
261 query
.releaseConnection(); // let the connection available for other methods
268 public boolean isMultiStatus(int status
) {
269 return (status
== HttpStatus
.SC_MULTI_STATUS
);
274 * Creates and populates a new {@link OCFile} object with the data read from the server.
276 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
277 * @return New OCFile instance representing the remote resource described by we.
279 private OCFile
fillOCFile(WebdavEntry we
) {
280 OCFile file
= new OCFile(we
.decodedPath());
281 file
.setCreationTimestamp(we
.createTimestamp());
282 file
.setFileLength(we
.contentLength());
283 file
.setMimetype(we
.contentType());
284 file
.setModificationTimestamp(we
.modifiedTimestamp());
285 file
.setParentId(mParentId
);
291 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
292 * tries to copy the file inside it.
294 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
295 * {@link #mForgottenLocalFiles}
297 * @param file File to check and fix.
299 private void checkAndFixForeignStoragePath(OCFile file
) {
300 String storagePath
= file
.getStoragePath();
301 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
302 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
303 /// fix storagePaths out of the local ownCloud folder
304 File originalFile
= new File(storagePath
);
305 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
306 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
307 file
.setStoragePath(null
);
310 InputStream
in = null
;
311 OutputStream out
= null
;
313 File expectedFile
= new File(expectedPath
);
314 File expectedParent
= expectedFile
.getParentFile();
315 expectedParent
.mkdirs();
316 if (!expectedParent
.isDirectory()) {
317 throw new IOException("Unexpected error: parent directory could not be created");
319 expectedFile
.createNewFile();
320 if (!expectedFile
.isFile()) {
321 throw new IOException("Unexpected error: target file could not be created");
323 in = new FileInputStream(originalFile
);
324 out
= new FileOutputStream(expectedFile
);
325 byte[] buf
= new byte[1024];
327 while ((len
= in.read(buf
)) > 0){
328 out
.write(buf
, 0, len
);
330 file
.setStoragePath(expectedPath
);
332 } catch (Exception e
) {
333 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
334 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
335 file
.setStoragePath(null
);
339 if (in != null
) in.close();
340 } catch (Exception e
) {
341 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
344 if (out
!= null
) out
.close();
345 } catch (Exception e
) {
346 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);