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
.MultiStatus
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import android
.accounts
.Account
;
37 import android
.content
.Context
;
38 import android
.os
.storage
.StorageManager
;
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 public String
getRemotePath() {
68 /** Timestamp for the synchronization in progress */
69 private long mCurrentSyncTime
;
71 /** Id of the folder to synchronize in the local database */
72 private long mParentId
;
74 public long getParentId() {
79 /** Access to the local database */
80 private DataStorageManager mStorageManager
;
82 /** Account where the file to synchronize belongs */
83 private Account mAccount
;
85 /** Android context; necessary to send requests to the download service; maybe something to refactor */
86 private Context mContext
;
88 /** Files and folders contained in the synchronized folder */
89 private List
<OCFile
> mChildren
;
91 private int mConflictsFound
;
93 private int mFailsInFavouritesFound
;
95 private Map
<String
, String
> mForgottenLocalFiles
;
98 public SynchronizeFolderOperation( String remotePath
,
101 DataStorageManager dataStorageManager
,
104 mRemotePath
= remotePath
;
105 mCurrentSyncTime
= currentSyncTime
;
106 mParentId
= parentId
;
107 mStorageManager
= dataStorageManager
;
110 mForgottenLocalFiles
= new HashMap
<String
, String
>();
114 public int getConflictsFound() {
115 return mConflictsFound
;
118 public int getFailsInFavouritesFound() {
119 return mFailsInFavouritesFound
;
122 public Map
<String
, String
> getForgottenLocalFiles() {
123 return mForgottenLocalFiles
;
127 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
129 * @return List of files and folders contained in the synchronized folder.
131 public List
<OCFile
> getChildren() {
137 protected RemoteOperationResult
run(WebdavClient client
) {
138 RemoteOperationResult result
= null
;
139 mFailsInFavouritesFound
= 0;
141 mForgottenLocalFiles
.clear();
143 // code before in FileSyncAdapter.fetchData
144 PropFindMethod query
= null
;
146 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ ", fetching files in " + mRemotePath
);
149 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mRemotePath
));
150 int status
= client
.executeMethod(query
);
152 // check and process response - /// TODO take into account all the possible status per child-resource
153 if (isMultiStatus(status
)) {
154 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
156 // synchronize properties of the parent folder, if necessary
157 if (mParentId
== DataStorageManager
.ROOT_PARENT_ID
) {
158 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], client
.getBaseUri().getPath());
160 // Properties of server folder
161 OCFile parent
= fillOCFile(we
);
162 // Properties of local folder
163 OCFile localParent
= mStorageManager
.getFileById(1);
164 if (parent
.getEtag() != localParent
.getEtag()) {
165 mStorageManager
.saveFile(parent
);
166 mParentId
= parent
.getFileId();
171 // read contents in folder
172 List
<String
> filesOnServer
= new ArrayList
<String
> (); // Contains the lists of files on server
173 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
174 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
175 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
176 /// new OCFile instance with the data from the server
177 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[i
], client
.getBaseUri().getPath());
178 OCFile file
= fillOCFile(we
);
180 filesOnServer
.add(file
.getRemotePath()); // Registry the file in the list
182 /// set data about local state, keeping unchanged former data if existing
183 file
.setLastSyncDateForProperties(mCurrentSyncTime
);
184 OCFile oldFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
186 // Check if it is needed to synchronize the folder
187 boolean fileChanged
= false
;
188 if (oldFile
!= null
) {
189 if (!file
.getEtag().equalsIgnoreCase(oldFile
.getEtag())) {
196 if (oldFile
!= null
) {
197 file
.setKeepInSync(oldFile
.keepInSync());
198 file
.setLastSyncDateForData(oldFile
.getLastSyncDateForData());
199 file
.setModificationTimestampAtLastSyncForData(oldFile
.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
200 checkAndFixForeignStoragePath(oldFile
);
201 file
.setStoragePath(oldFile
.getStoragePath());
203 /// scan default location if local copy of file is not linked in OCFile instance
204 if (file
.getStoragePath() == null
&& !file
.isDirectory()) {
205 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
207 file
.setStoragePath(f
.getAbsolutePath());
208 file
.setLastSyncDateForData(f
.lastModified());
212 /// prepare content synchronization for kept-in-sync files
213 if (file
.keepInSync()) {
214 SynchronizeFileOperation operation
= new SynchronizeFileOperation( oldFile
,
222 filesToSyncContents
.add(operation
);
225 updatedFiles
.add(file
);
229 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
230 mStorageManager
.saveFiles(updatedFiles
);
232 // request for the synchronization of files AFTER saving last properties
233 SynchronizeFileOperation op
= null
;
234 RemoteOperationResult contentsResult
= null
;
235 for (int i
=0; i
< filesToSyncContents
.size(); i
++) {
236 op
= filesToSyncContents
.get(i
);
237 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
238 if (!contentsResult
.isSuccess()) {
239 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
242 mFailsInFavouritesFound
++;
243 if (contentsResult
.getException() != null
) {
244 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
246 Log_OC
.d(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
249 } // won't let these fails break the synchronization process
253 // removal of obsolete files
254 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
256 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
257 for (int i
=0; i
< mChildren
.size(); ) {
258 file
= mChildren
.get(i
);
259 //if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
260 if (!filesOnServer
.contains(file
.getRemotePath())) {
261 Log_OC
.d(TAG
, "removing file: " + file
.getFileName());
262 mStorageManager
.removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
270 client
.exhaustResponse(query
.getResponseBodyAsStream());
273 // prepare result object
274 if (isMultiStatus(status
)) {
275 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
276 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
279 result
= new RemoteOperationResult(true
, status
);
282 result
= new RemoteOperationResult(false
, status
);
284 Log_OC
.i(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
287 } catch (Exception e
) {
288 result
= new RemoteOperationResult(e
);
289 Log_OC
.e(TAG
, "Synchronizing " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage(), result
.getException());
293 query
.releaseConnection(); // let the connection available for other methods
300 public boolean isMultiStatus(int status
) {
301 return (status
== HttpStatus
.SC_MULTI_STATUS
);
306 * Creates and populates a new {@link OCFile} object with the data read from the server.
308 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
309 * @return New OCFile instance representing the remote resource described by we.
311 private OCFile
fillOCFile(WebdavEntry we
) {
312 OCFile file
= new OCFile(we
.decodedPath());
313 file
.setCreationTimestamp(we
.createTimestamp());
314 file
.setFileLength(we
.contentLength());
315 file
.setMimetype(we
.contentType());
316 file
.setModificationTimestamp(we
.modifiedTimestamp());
317 file
.setParentId(mParentId
);
318 file
.setEtag(we
.etag());
324 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
325 * tries to copy the file inside it.
327 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
328 * {@link #mForgottenLocalFiles}
330 * @param file File to check and fix.
332 private void checkAndFixForeignStoragePath(OCFile file
) {
333 String storagePath
= file
.getStoragePath();
334 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
335 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
336 /// fix storagePaths out of the local ownCloud folder
337 File originalFile
= new File(storagePath
);
338 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
339 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
340 file
.setStoragePath(null
);
343 InputStream
in = null
;
344 OutputStream out
= null
;
346 File expectedFile
= new File(expectedPath
);
347 File expectedParent
= expectedFile
.getParentFile();
348 expectedParent
.mkdirs();
349 if (!expectedParent
.isDirectory()) {
350 throw new IOException("Unexpected error: parent directory could not be created");
352 expectedFile
.createNewFile();
353 if (!expectedFile
.isFile()) {
354 throw new IOException("Unexpected error: target file could not be created");
356 in = new FileInputStream(originalFile
);
357 out
= new FileOutputStream(expectedFile
);
358 byte[] buf
= new byte[1024];
360 while ((len
= in.read(buf
)) > 0){
361 out
.write(buf
, 0, len
);
363 file
.setStoragePath(expectedPath
);
365 } catch (Exception e
) {
366 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
367 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
368 file
.setStoragePath(null
);
372 if (in != null
) in.close();
373 } catch (Exception e
) {
374 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
377 if (out
!= null
) out
.close();
378 } catch (Exception e
) {
379 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);