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