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
.content
.Intent
;
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
.syncadapter
.FileSyncService
;
45 import com
.owncloud
.android
.utils
.FileStorageUtils
;
47 import eu
.alefzero
.webdav
.WebdavClient
;
48 import eu
.alefzero
.webdav
.WebdavEntry
;
49 import eu
.alefzero
.webdav
.WebdavUtils
;
53 * Remote operation performing the synchronization a the contents of a remote folder with the local database
55 * @author David A. Velasco
57 public class SynchronizeFolderOperation
extends RemoteOperation
{
59 private static final String TAG
= SynchronizeFolderOperation
.class.getSimpleName();
61 /** Remote folder to synchronize */
62 private String mRemotePath
;
64 /** Timestamp for the synchronization in progress */
65 private long mCurrentSyncTime
;
67 /** Id of the folder to synchronize in the local database */
68 private long mParentId
;
70 /** Boolean to indicate if is mandatory to update the folder */
71 private boolean mEnforceMetadataUpdate
;
73 /** Access to the local database */
74 private DataStorageManager mStorageManager
;
76 /** Account where the file to synchronize belongs */
77 private Account mAccount
;
79 /** Android context; necessary to send requests to the download service; maybe something to refactor */
80 private Context mContext
;
82 /** Files and folders contained in the synchronized folder */
83 private List
<OCFile
> mChildren
;
85 private int mConflictsFound
;
87 private int mFailsInFavouritesFound
;
89 private Map
<String
, String
> mForgottenLocalFiles
;
91 private boolean mSyncFullAccount
;
94 public SynchronizeFolderOperation( String remotePath
,
97 boolean enforceMetadataUpdate
,
98 boolean syncFullAccount
,
99 DataStorageManager dataStorageManager
,
102 mRemotePath
= remotePath
;
103 mCurrentSyncTime
= currentSyncTime
;
104 mParentId
= parentId
;
105 mEnforceMetadataUpdate
= enforceMetadataUpdate
;
106 mSyncFullAccount
= syncFullAccount
;
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() {
135 public String
getRemotePath() {
139 public long getParentId() {
144 protected RemoteOperationResult
run(WebdavClient client
) {
145 RemoteOperationResult result
= null
;
146 mFailsInFavouritesFound
= 0;
148 mForgottenLocalFiles
.clear();
149 boolean dirChanged
= false
;
151 // code before in FileSyncAdapter.fetchData
152 PropFindMethod query
= null
;
154 Log_OC
.d(TAG
, "Synchronizing " + mAccount
.name
+ ", fetching files in " + mRemotePath
);
157 query
= new PropFindMethod(client
.getBaseUri() + WebdavUtils
.encodePath(mRemotePath
));
158 int status
= client
.executeMethod(query
);
160 // check and process response - /// TODO take into account all the possible status per child-resource
161 if (isMultiStatus(status
)) {
162 MultiStatus resp
= query
.getResponseBodyAsMultiStatus();
164 // synchronize properties of the parent folder, if necessary
165 WebdavEntry we
= new WebdavEntry(resp
.getResponses()[0], client
.getBaseUri().getPath());
167 // Properties of server folder
168 OCFile parent
= fillOCFile(we
);
169 // Properties of local folder
170 OCFile localParent
= mStorageManager
.getFileByPath(mRemotePath
);
171 if (localParent
== null
|| !(parent
.getEtag().equalsIgnoreCase(localParent
.getEtag())) || mEnforceMetadataUpdate
) {
172 if (localParent
!= null
) {
173 parent
.setParentId(localParent
.getParentId());
175 mStorageManager
.saveFile(parent
);
176 if (mParentId
== DataStorageManager
.ROOT_PARENT_ID
)
177 mParentId
= parent
.getFileId();
182 // read contents in folder
183 List
<String
> filesOnServer
= new ArrayList
<String
> (); // Contains the lists of files on server
184 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(resp
.getResponses().length
- 1);
185 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
186 for (int i
= 1; i
< resp
.getResponses().length
; ++i
) {
187 /// new OCFile instance with the data from the server
188 we
= new WebdavEntry(resp
.getResponses()[i
], client
.getBaseUri().getPath());
189 OCFile file
= fillOCFile(we
);
191 filesOnServer
.add(file
.getRemotePath()); // Registry the file in the list
193 /// set data about local state, keeping unchanged former data if existing
194 file
.setLastSyncDateForProperties(mCurrentSyncTime
);
195 OCFile oldFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
197 // Check if it is needed to synchronize the folder
198 if (oldFile
!= null
) {
199 if (!file
.getEtag().equalsIgnoreCase(oldFile
.getEtag())) {
203 if (oldFile
!= null
) {
204 file
.setKeepInSync(oldFile
.keepInSync());
205 file
.setLastSyncDateForData(oldFile
.getLastSyncDateForData());
206 file
.setModificationTimestampAtLastSyncForData(oldFile
.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
207 checkAndFixForeignStoragePath(oldFile
);
208 file
.setStoragePath(oldFile
.getStoragePath());
209 if (file
.isDirectory())
210 file
.setEtag(oldFile
.getEtag());
212 if (file
.isDirectory())
215 /// scan default location if local copy of file is not linked in OCFile instance
216 if (file
.getStoragePath() == null
&& !file
.isDirectory()) {
217 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
219 file
.setStoragePath(f
.getAbsolutePath());
220 file
.setLastSyncDateForData(f
.lastModified());
224 /// prepare content synchronization for kept-in-sync files
225 if (file
.keepInSync()) {
226 SynchronizeFileOperation operation
= new SynchronizeFileOperation( oldFile
,
234 filesToSyncContents
.add(operation
);
237 updatedFiles
.add(file
);
240 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
241 mStorageManager
.saveFiles(updatedFiles
);
243 // request for the synchronization of files AFTER saving last properties
244 RemoteOperationResult contentsResult
= null
;
245 for (SynchronizeFileOperation op
: filesToSyncContents
) {
246 contentsResult
= op
.execute(client
); // returns without waiting for upload or download finishes
247 if (!contentsResult
.isSuccess()) {
248 if (contentsResult
.getCode() == ResultCode
.SYNC_CONFLICT
) {
251 mFailsInFavouritesFound
++;
252 if (contentsResult
.getException() != null
) {
253 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage(), contentsResult
.getException());
255 Log_OC
.e(TAG
, "Error while synchronizing favourites : " + contentsResult
.getLogMessage());
258 } // won't let these fails break the synchronization process
261 // removal of obsolete files
262 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
264 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
265 for (int i
=0; i
< mChildren
.size(); ) {
266 file
= mChildren
.get(i
);
267 if (file
.getLastSyncDateForProperties() != mCurrentSyncTime
) {
268 Log_OC
.d(TAG
, "removing file: " + file
);
269 mStorageManager
.removeFile(file
, (file
.isDown() && file
.getStoragePath().startsWith(currentSavePath
)));
277 client
.exhaustResponse(query
.getResponseBodyAsStream());
281 // prepare result object
283 result
= new RemoteOperationResult(ResultCode
.OK_NO_CHANGES_ON_DIR
);
284 mChildren
= mStorageManager
.getDirectoryContent(mStorageManager
.getFileById(mParentId
));
287 if (mConflictsFound
> 0 || mFailsInFavouritesFound
> 0) {
288 result
= new RemoteOperationResult(ResultCode
.SYNC_CONFLICT
); // should be different result, but will do the job
291 result
= new RemoteOperationResult(true
, status
, query
.getResponseHeaders());
296 if (status
== HttpStatus
.SC_NOT_FOUND
) {
297 OCFile dir
= mStorageManager
.getFileByPath(mRemotePath
);
299 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
300 mStorageManager
.removeDirectory(dir
, true
, (dir
.isDown() && dir
.getStoragePath().startsWith(currentSavePath
)));
303 result
= new RemoteOperationResult(false
, status
, query
.getResponseHeaders());
306 } catch (Exception e
) {
307 result
= new RemoteOperationResult(e
);
312 query
.releaseConnection(); // let the connection available for other methods
313 if (result
.isSuccess()) {
314 Log_OC
.i(TAG
, "Synchroned " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
316 if (result
.isException()) {
317 Log_OC
.e(TAG
, "Synchroned " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage(), result
.getException());
319 Log_OC
.e(TAG
, "Synchroned " + mAccount
.name
+ ", folder " + mRemotePath
+ ": " + result
.getLogMessage());
323 if (!mSyncFullAccount
) {
324 sendStickyBroadcast(false
, mRemotePath
, result
);
332 public boolean isMultiStatus(int status
) {
333 return (status
== HttpStatus
.SC_MULTI_STATUS
);
338 * Creates and populates a new {@link OCFile} object with the data read from the server.
340 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
341 * @return New OCFile instance representing the remote resource described by we.
343 private OCFile
fillOCFile(WebdavEntry we
) {
344 OCFile file
= new OCFile(we
.decodedPath());
345 file
.setCreationTimestamp(we
.createTimestamp());
346 file
.setFileLength(we
.contentLength());
347 file
.setMimetype(we
.contentType());
348 file
.setModificationTimestamp(we
.modifiedTimestamp());
349 file
.setParentId(mParentId
);
350 file
.setEtag(we
.etag());
356 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
357 * tries to copy the file inside it.
359 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
360 * {@link #mForgottenLocalFiles}
362 * @param file File to check and fix.
364 private void checkAndFixForeignStoragePath(OCFile file
) {
365 String storagePath
= file
.getStoragePath();
366 String expectedPath
= FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
);
367 if (storagePath
!= null
&& !storagePath
.equals(expectedPath
)) {
368 /// fix storagePaths out of the local ownCloud folder
369 File originalFile
= new File(storagePath
);
370 if (FileStorageUtils
.getUsableSpace(mAccount
.name
) < originalFile
.length()) {
371 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
372 file
.setStoragePath(null
);
375 InputStream
in = null
;
376 OutputStream out
= null
;
378 File expectedFile
= new File(expectedPath
);
379 File expectedParent
= expectedFile
.getParentFile();
380 expectedParent
.mkdirs();
381 if (!expectedParent
.isDirectory()) {
382 throw new IOException("Unexpected error: parent directory could not be created");
384 expectedFile
.createNewFile();
385 if (!expectedFile
.isFile()) {
386 throw new IOException("Unexpected error: target file could not be created");
388 in = new FileInputStream(originalFile
);
389 out
= new FileOutputStream(expectedFile
);
390 byte[] buf
= new byte[1024];
392 while ((len
= in.read(buf
)) > 0){
393 out
.write(buf
, 0, len
);
395 file
.setStoragePath(expectedPath
);
397 } catch (Exception e
) {
398 Log_OC
.e(TAG
, "Exception while copying foreign file " + expectedPath
, e
);
399 mForgottenLocalFiles
.put(file
.getRemotePath(), storagePath
);
400 file
.setStoragePath(null
);
404 if (in != null
) in.close();
405 } catch (Exception e
) {
406 Log_OC
.d(TAG
, "Weird exception while closing input stream for " + storagePath
+ " (ignoring)", e
);
409 if (out
!= null
) out
.close();
410 } catch (Exception e
) {
411 Log_OC
.d(TAG
, "Weird exception while closing output stream for " + expectedPath
+ " (ignoring)", e
);
419 * Sends a message to any application component interested in the progress of the synchronization.
421 * @param inProgress 'True' when the synchronization progress is not finished.
422 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
424 private void sendStickyBroadcast(boolean inProgress
, String dirRemotePath
, RemoteOperationResult result
) {
425 Intent i
= new Intent(FileSyncService
.SYNC_MESSAGE
);
426 i
.putExtra(FileSyncService
.IN_PROGRESS
, inProgress
);
427 i
.putExtra(FileSyncService
.ACCOUNT_NAME
, mAccount
.name
);
428 if (dirRemotePath
!= null
) {
429 i
.putExtra(FileSyncService
.SYNC_FOLDER_REMOTE_PATH
, dirRemotePath
);
431 if (result
!= null
) {
432 i
.putExtra(FileSyncService
.SYNC_RESULT
, result
);
434 mContext
.sendStickyBroadcast(i
);