Merge branch 'develop' into refresh_folder_contents_when_browsed_into
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
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.
7 *
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.
12 *
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/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import java.io.File;
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;
28 import java.util.Map;
29 import java.util.Vector;
30
31 import org.apache.http.HttpStatus;
32 import org.apache.jackrabbit.webdav.DavConstants;
33 import org.apache.jackrabbit.webdav.MultiStatus;
34 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
35
36 import android.accounts.Account;
37 import android.content.Context;
38 import android.content.Intent;
39
40 import com.owncloud.android.Log_OC;
41 import com.owncloud.android.datamodel.FileDataStorageManager;
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;
46
47 import eu.alefzero.webdav.WebdavClient;
48 import eu.alefzero.webdav.WebdavEntry;
49 import eu.alefzero.webdav.WebdavUtils;
50
51
52 /**
53 * Remote operation performing the synchronization of the list of files contained
54 * in a folder identified with its remote path.
55 *
56 * Fetches the list and properties of the files contained in the given folder, including their
57 * properties, and updates the local database with them.
58 *
59 * Does NOT enter in the child folders to synchronize their contents also.
60 *
61 * @author David A. Velasco
62 */
63 public class SynchronizeFolderOperation extends RemoteOperation {
64
65 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
66
67
68 /** Time stamp for the synchronization process in progress */
69 private long mCurrentSyncTime;
70
71 /** Remote folder to synchronize */
72 private OCFile mLocalFolder;
73
74 /** 'True' means that the properties of the folder should be updated also, not just its content */
75 private boolean mUpdateFolderProperties;
76
77 /** Access to the local database */
78 private FileDataStorageManager mStorageManager;
79
80 /** Account where the file to synchronize belongs */
81 private Account mAccount;
82
83 /** Android context; necessary to send requests to the download service */
84 private Context mContext;
85
86 /** Files and folders contained in the synchronized folder after a successful operation */
87 private List<OCFile> mChildren;
88
89 /** Counter of conflicts found between local and remote files */
90 private int mConflictsFound;
91
92 /** Counter of failed operations in synchronization of kept-in-sync files */
93 private int mFailsInFavouritesFound;
94
95 /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
96 private Map<String, String> mForgottenLocalFiles;
97
98 /** 'True' means that this operation is part of a full account synchronization */
99 private boolean mSyncFullAccount;
100
101
102 /**
103 * Creates a new instance of {@link SynchronizeFolderOperation}.
104 *
105 * @param remoteFolderPath Remote folder to synchronize.
106 * @param currentSyncTime Time stamp for the synchronization process in progress.
107 * @param localFolderId Identifier in the local database of the folder to synchronize.
108 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
109 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
110 * @param dataStorageManager Interface with the local database.
111 * @param account ownCloud account where the folder is located.
112 * @param context Application context.
113 */
114 public SynchronizeFolderOperation( OCFile folder,
115 long currentSyncTime,
116 boolean updateFolderProperties,
117 boolean syncFullAccount,
118 FileDataStorageManager dataStorageManager,
119 Account account,
120 Context context ) {
121 mLocalFolder = folder;
122 mCurrentSyncTime = currentSyncTime;
123 mUpdateFolderProperties = updateFolderProperties;
124 mSyncFullAccount = syncFullAccount;
125 mStorageManager = dataStorageManager;
126 mAccount = account;
127 mContext = context;
128 mForgottenLocalFiles = new HashMap<String, String>();
129 }
130
131
132 public int getConflictsFound() {
133 return mConflictsFound;
134 }
135
136 public int getFailsInFavouritesFound() {
137 return mFailsInFavouritesFound;
138 }
139
140 public Map<String, String> getForgottenLocalFiles() {
141 return mForgottenLocalFiles;
142 }
143
144 /**
145 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
146 *
147 * @return List of files and folders contained in the synchronized folder.
148 */
149 public List<OCFile> getChildren() {
150 return mChildren;
151 }
152
153 /**
154 * Performs the synchronization.
155 *
156 * {@inheritDoc}
157 */
158 @Override
159 protected RemoteOperationResult run(WebdavClient client) {
160 RemoteOperationResult result = null;
161 mFailsInFavouritesFound = 0;
162 mConflictsFound = 0;
163 mForgottenLocalFiles.clear();
164 String remotePath = null;
165 PropFindMethod query = null;
166 try {
167 remotePath = mLocalFolder.getRemotePath();
168 Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
169
170 // remote request
171 query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(remotePath),
172 DavConstants.PROPFIND_ALL_PROP,
173 DavConstants.DEPTH_1);
174 int status = client.executeMethod(query);
175
176 // check and process response
177 if (isMultiStatus(status)) {
178 boolean folderChanged = synchronizeData(query.getResponseBodyAsMultiStatus(), client);
179 if (folderChanged) {
180 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
181 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
182 } else {
183 result = new RemoteOperationResult(true, status, query.getResponseHeaders());
184 }
185 } else {
186 result = new RemoteOperationResult(ResultCode.OK_NO_CHANGES_ON_DIR);
187 }
188
189 } else {
190 // synchronization failed
191 client.exhaustResponse(query.getResponseBodyAsStream());
192 if (status == HttpStatus.SC_NOT_FOUND) {
193 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
194 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
195 mStorageManager.removeFolder(mLocalFolder, true, (mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)));
196 }
197 }
198 result = new RemoteOperationResult(false, status, query.getResponseHeaders());
199 }
200
201 } catch (Exception e) {
202 result = new RemoteOperationResult(e);
203
204
205 } finally {
206 if (query != null)
207 query.releaseConnection(); // let the connection available for other methods
208 if (result.isSuccess()) {
209 Log_OC.i(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage());
210 } else {
211 if (result.isException()) {
212 Log_OC.e(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage(), result.getException());
213 } else {
214 Log_OC.e(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage());
215 }
216 }
217
218 if (!mSyncFullAccount) {
219 sendStickyBroadcast(false, remotePath, result);
220 }
221 }
222
223 return result;
224 }
225
226
227 /**
228 * Synchronizes the data retrieved from the server about the contents of the target folder
229 * with the current data in the local database.
230 *
231 * Grants that mChildren is updated with fresh data after execution.
232 *
233 * @param dataInServer Full response got from the server with the data of the target
234 * folder and its direct children.
235 * @param client Client instance to the remote server where the data were
236 * retrieved.
237 * @return 'True' when any change was made in the local data, 'false' otherwise.
238 */
239 private boolean synchronizeData(MultiStatus dataInServer, WebdavClient client) {
240 // get 'fresh data' from the database
241 mLocalFolder = mStorageManager.getFileById(mLocalFolder.getFileId());
242
243 // parse data from remote folder
244 WebdavEntry we = new WebdavEntry(dataInServer.getResponses()[0], client.getBaseUri().getPath());
245 OCFile remoteFolder = fillOCFile(we);
246 remoteFolder.setParentId(mLocalFolder.getParentId());
247 remoteFolder.setFileId(mLocalFolder.getFileId());
248
249 // check if remote and local folder are different
250 boolean folderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
251
252 if (!folderChanged) {
253 if (mUpdateFolderProperties) { // TODO check if this is really necessary
254 mStorageManager.saveFile(remoteFolder);
255 }
256
257 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " didn't change");
258 mChildren = mStorageManager.getFolderContent(mLocalFolder);
259
260 } else {
261 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
262
263 List<OCFile> updatedFiles = new Vector<OCFile>(dataInServer.getResponses().length - 1);
264 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
265
266 // get current data about local contents of the folder to synchronize
267 List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
268 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
269 for (OCFile file : localFiles) {
270 localFilesMap.put(file.getRemotePath(), file);
271 }
272
273 // loop to update every child
274 OCFile remoteFile = null, localFile = null;
275 for (int i = 1; i < dataInServer.getResponses().length; ++i) {
276 /// new OCFile instance with the data from the server
277 we = new WebdavEntry(dataInServer.getResponses()[i], client.getBaseUri().getPath());
278 remoteFile = fillOCFile(we);
279 remoteFile.setParentId(mLocalFolder.getFileId());
280
281 /// retrieve local data for the read file
282 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
283 localFile = localFilesMap.remove(remoteFile.getRemotePath());
284
285 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
286 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
287 if (localFile != null) {
288 // some properties of local state are kept unmodified
289 remoteFile.setFileId(localFile.getFileId());
290 remoteFile.setKeepInSync(localFile.keepInSync());
291 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
292 remoteFile.setModificationTimestampAtLastSyncForData(localFile.getModificationTimestampAtLastSyncForData());
293 remoteFile.setStoragePath(localFile.getStoragePath());
294 remoteFile.setEtag(localFile.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
295 } else {
296 remoteFile.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
297 }
298
299 /// check and fix, if needed, local storage path
300 checkAndFixForeignStoragePath(remoteFile); // fixing old policy - now local files must be copied into the ownCloud local folder
301 searchForLocalFileInDefaultPath(remoteFile); // legacy
302
303 /// prepare content synchronization for kept-in-sync files
304 if (remoteFile.keepInSync()) {
305 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
306 remoteFile,
307 mStorageManager,
308 mAccount,
309 true,
310 false,
311 mContext
312 );
313 filesToSyncContents.add(operation);
314 }
315
316 updatedFiles.add(remoteFile);
317 }
318
319 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
320 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
321
322 // request for the synchronization of file contents AFTER saving current remote properties
323 startContentSynchronizations(filesToSyncContents, client);
324
325 // removal of obsolete files
326 //removeObsoleteFiles();
327
328 // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
329 //mStorageManager.saveFile(remoteFolder);
330 mChildren = updatedFiles;
331
332 }
333
334 return folderChanged;
335
336 }
337
338 /**
339 * Performs a list of synchronization operations, determining if a download or upload is needed or
340 * if exists conflict due to changes both in local and remote contents of the each file.
341 *
342 * If download or upload is needed, request the operation to the corresponding service and goes on.
343 *
344 * @param filesToSyncContents Synchronization operations to execute.
345 * @param client Interface to the remote ownCloud server.
346 */
347 private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents, WebdavClient client) {
348 RemoteOperationResult contentsResult = null;
349 for (SynchronizeFileOperation op: filesToSyncContents) {
350 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
351 if (!contentsResult.isSuccess()) {
352 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
353 mConflictsFound++;
354 } else {
355 mFailsInFavouritesFound++;
356 if (contentsResult.getException() != null) {
357 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
358 } else {
359 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
360 }
361 }
362 } // won't let these fails break the synchronization process
363 }
364 }
365
366
367 public boolean isMultiStatus(int status) {
368 return (status == HttpStatus.SC_MULTI_STATUS);
369 }
370
371
372 /**
373 * Creates and populates a new {@link OCFile} object with the data read from the server.
374 *
375 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
376 * @return New OCFile instance representing the remote resource described by we.
377 */
378 private OCFile fillOCFile(WebdavEntry we) {
379 OCFile file = new OCFile(we.decodedPath());
380 file.setCreationTimestamp(we.createTimestamp());
381 file.setFileLength(we.contentLength());
382 file.setMimetype(we.contentType());
383 file.setModificationTimestamp(we.modifiedTimestamp());
384 file.setEtag(we.etag());
385 return file;
386 }
387
388
389 /**
390 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
391 * tries to copy the file inside it.
392 *
393 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
394 * {@link #mForgottenLocalFiles}
395 *)
396 * @param file File to check and fix.
397 */
398 private void checkAndFixForeignStoragePath(OCFile file) {
399 String storagePath = file.getStoragePath();
400 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
401 if (storagePath != null && !storagePath.equals(expectedPath)) {
402 /// fix storagePaths out of the local ownCloud folder
403 File originalFile = new File(storagePath);
404 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
405 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
406 file.setStoragePath(null);
407
408 } else {
409 InputStream in = null;
410 OutputStream out = null;
411 try {
412 File expectedFile = new File(expectedPath);
413 File expectedParent = expectedFile.getParentFile();
414 expectedParent.mkdirs();
415 if (!expectedParent.isDirectory()) {
416 throw new IOException("Unexpected error: parent directory could not be created");
417 }
418 expectedFile.createNewFile();
419 if (!expectedFile.isFile()) {
420 throw new IOException("Unexpected error: target file could not be created");
421 }
422 in = new FileInputStream(originalFile);
423 out = new FileOutputStream(expectedFile);
424 byte[] buf = new byte[1024];
425 int len;
426 while ((len = in.read(buf)) > 0){
427 out.write(buf, 0, len);
428 }
429 file.setStoragePath(expectedPath);
430
431 } catch (Exception e) {
432 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
433 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
434 file.setStoragePath(null);
435
436 } finally {
437 try {
438 if (in != null) in.close();
439 } catch (Exception e) {
440 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
441 }
442 try {
443 if (out != null) out.close();
444 } catch (Exception e) {
445 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
446 }
447 }
448 }
449 }
450 }
451
452
453 /**
454 * Scans the default location for saving local copies of files searching for
455 * a 'lost' file with the same full name as the {@link OCFile} received as
456 * parameter.
457 *
458 * @param file File to associate a possible 'lost' local file.
459 */
460 private void searchForLocalFileInDefaultPath(OCFile file) {
461 if (file.getStoragePath() == null && !file.isFolder()) {
462 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
463 if (f.exists()) {
464 file.setStoragePath(f.getAbsolutePath());
465 file.setLastSyncDateForData(f.lastModified());
466 }
467 }
468 }
469
470
471 /**
472 * Sends a message to any application component interested in the progress of the synchronization.
473 *
474 * @param inProgress 'True' when the synchronization progress is not finished.
475 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
476 */
477 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
478 Intent i = new Intent(FileSyncService.SYNC_MESSAGE);
479 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
480 i.putExtra(FileSyncService.ACCOUNT_NAME, mAccount.name);
481 if (dirRemotePath != null) {
482 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
483 }
484 if (result != null) {
485 i.putExtra(FileSyncService.SYNC_RESULT, result);
486 }
487 mContext.sendStickyBroadcast(i);
488 }
489
490 }