Merge remote-tracking branch 'origin/develop' into develop
[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 synchronizeData(result.getData(), client);
253 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
254 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
255 }
256 } else {
257 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
258 removeLocalFolder();
259 }
260
261 return result;
262 }
263
264
265 private void removeLocalFolder() {
266 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
267 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
268 mStorageManager.removeFolder(mLocalFolder, true, (mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)));
269 }
270 }
271
272
273 /**
274 * Synchronizes the data retrieved from the server about the contents of the target folder
275 * with the current data in the local database.
276 *
277 * Grants that mChildren is updated with fresh data after execution.
278 *
279 * @param folderAndFiles Remote folder and children files in Folder
280 *
281 * @param client Client instance to the remote server where the data were
282 * retrieved.
283 * @return 'True' when any change was made in the local data, 'false' otherwise.
284 */
285 private void synchronizeData(ArrayList<RemoteFile> folderAndFiles, WebdavClient client) {
286 // get 'fresh data' from the database
287 mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
288
289 // parse data from remote folder
290 OCFile remoteFolder = fillOCFile(folderAndFiles.get(0));
291 remoteFolder.setParentId(mLocalFolder.getParentId());
292 remoteFolder.setFileId(mLocalFolder.getFileId());
293
294 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
295
296 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
297 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
298
299 // get current data about local contents of the folder to synchronize
300 List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
301 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
302 for (OCFile file : localFiles) {
303 localFilesMap.put(file.getRemotePath(), file);
304 }
305
306 // loop to update every child
307 OCFile remoteFile = null, localFile = null;
308 for (int i=1; i<folderAndFiles.size(); i++) {
309 /// new OCFile instance with the data from the server
310 remoteFile = fillOCFile(folderAndFiles.get(i));
311 remoteFile.setParentId(mLocalFolder.getFileId());
312
313 /// retrieve local data for the read file
314 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
315 localFile = localFilesMap.remove(remoteFile.getRemotePath());
316
317 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
318 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
319 if (localFile != null) {
320 // some properties of local state are kept unmodified
321 remoteFile.setFileId(localFile.getFileId());
322 remoteFile.setKeepInSync(localFile.keepInSync());
323 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
324 remoteFile.setModificationTimestampAtLastSyncForData(localFile.getModificationTimestampAtLastSyncForData());
325 remoteFile.setStoragePath(localFile.getStoragePath());
326 remoteFile.setEtag(localFile.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
327 if (remoteFile.isFolder()) {
328 remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider
329 }
330 } else {
331 remoteFile.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
332 }
333
334 /// check and fix, if needed, local storage path
335 checkAndFixForeignStoragePath(remoteFile); // fixing old policy - now local files must be copied into the ownCloud local folder
336 searchForLocalFileInDefaultPath(remoteFile); // legacy
337
338 /// prepare content synchronization for kept-in-sync files
339 if (remoteFile.keepInSync()) {
340 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
341 remoteFile,
342 mStorageManager,
343 mAccount,
344 true,
345 mContext
346 );
347 filesToSyncContents.add(operation);
348 }
349
350 updatedFiles.add(remoteFile);
351 }
352
353 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
354 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
355
356 // request for the synchronization of file contents AFTER saving current remote properties
357 startContentSynchronizations(filesToSyncContents, client);
358
359 // removal of obsolete files
360 //removeObsoleteFiles();
361
362 // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
363 //mStorageManager.saveFile(remoteFolder);
364 mChildren = updatedFiles;
365
366 }
367
368 /**
369 * Performs a list of synchronization operations, determining if a download or upload is needed or
370 * if exists conflict due to changes both in local and remote contents of the each file.
371 *
372 * If download or upload is needed, request the operation to the corresponding service and goes on.
373 *
374 * @param filesToSyncContents Synchronization operations to execute.
375 * @param client Interface to the remote ownCloud server.
376 */
377 private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents, WebdavClient client) {
378 RemoteOperationResult contentsResult = null;
379 for (SynchronizeFileOperation op: filesToSyncContents) {
380 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
381 if (!contentsResult.isSuccess()) {
382 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
383 mConflictsFound++;
384 } else {
385 mFailsInFavouritesFound++;
386 if (contentsResult.getException() != null) {
387 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
388 } else {
389 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
390 }
391 }
392 } // won't let these fails break the synchronization process
393 }
394 }
395
396
397 public boolean isMultiStatus(int status) {
398 return (status == HttpStatus.SC_MULTI_STATUS);
399 }
400
401
402 /**
403 * Creates and populates a new {@link OCFile} object with the data read from the server.
404 *
405 * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
406 * @return New OCFile instance representing the remote resource described by we.
407 */
408 private OCFile fillOCFile(WebdavEntry we) {
409 OCFile file = new OCFile(we.decodedPath());
410 file.setCreationTimestamp(we.createTimestamp());
411 file.setFileLength(we.contentLength());
412 file.setMimetype(we.contentType());
413 file.setModificationTimestamp(we.modifiedTimestamp());
414 file.setEtag(we.etag());
415 return file;
416 }
417
418 /**
419 * Creates and populates a new {@link OCFile} object with the data read from the server.
420 *
421 * @param remote remote file read from the server (remote file or folder).
422 * @return New OCFile instance representing the remote resource described by we.
423 */
424 private OCFile fillOCFile(RemoteFile remote) {
425 OCFile file = new OCFile(remote.getRemotePath());
426 file.setCreationTimestamp(remote.getCreationTimestamp());
427 file.setFileLength(remote.getLength());
428 file.setMimetype(remote.getMimeType());
429 file.setModificationTimestamp(remote.getModifiedTimestamp());
430 file.setEtag(remote.getEtag());
431 return file;
432 }
433
434
435 /**
436 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
437 * tries to copy the file inside it.
438 *
439 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
440 * {@link #mForgottenLocalFiles}
441 *)
442 * @param file File to check and fix.
443 */
444 private void checkAndFixForeignStoragePath(OCFile file) {
445 String storagePath = file.getStoragePath();
446 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
447 if (storagePath != null && !storagePath.equals(expectedPath)) {
448 /// fix storagePaths out of the local ownCloud folder
449 File originalFile = new File(storagePath);
450 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
451 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
452 file.setStoragePath(null);
453
454 } else {
455 InputStream in = null;
456 OutputStream out = null;
457 try {
458 File expectedFile = new File(expectedPath);
459 File expectedParent = expectedFile.getParentFile();
460 expectedParent.mkdirs();
461 if (!expectedParent.isDirectory()) {
462 throw new IOException("Unexpected error: parent directory could not be created");
463 }
464 expectedFile.createNewFile();
465 if (!expectedFile.isFile()) {
466 throw new IOException("Unexpected error: target file could not be created");
467 }
468 in = new FileInputStream(originalFile);
469 out = new FileOutputStream(expectedFile);
470 byte[] buf = new byte[1024];
471 int len;
472 while ((len = in.read(buf)) > 0){
473 out.write(buf, 0, len);
474 }
475 file.setStoragePath(expectedPath);
476
477 } catch (Exception e) {
478 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
479 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
480 file.setStoragePath(null);
481
482 } finally {
483 try {
484 if (in != null) in.close();
485 } catch (Exception e) {
486 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
487 }
488 try {
489 if (out != null) out.close();
490 } catch (Exception e) {
491 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
492 }
493 }
494 }
495 }
496 }
497
498 /**
499 * Scans the default location for saving local copies of files searching for
500 * a 'lost' file with the same full name as the {@link OCFile} received as
501 * parameter.
502 *
503 * @param file File to associate a possible 'lost' local file.
504 */
505 private void searchForLocalFileInDefaultPath(OCFile file) {
506 if (file.getStoragePath() == null && !file.isFolder()) {
507 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
508 if (f.exists()) {
509 file.setStoragePath(f.getAbsolutePath());
510 file.setLastSyncDateForData(f.lastModified());
511 }
512 }
513 }
514
515
516 /**
517 * Sends a message to any application component interested in the progress of the synchronization.
518 *
519 * @param inProgress 'True' when the synchronization progress is not finished.
520 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
521 */
522 private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
523 Intent i = new Intent(FileSyncService.getSyncMessage());
524 i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
525 i.putExtra(FileSyncService.ACCOUNT_NAME, mAccount.name);
526 if (dirRemotePath != null) {
527 i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
528 }
529 if (result != null) {
530 i.putExtra(FileSyncService.SYNC_RESULT, result);
531 }
532 mContext.sendStickyBroadcast(i);
533 }
534
535
536 public boolean getRemoteFolderChanged() {
537 return mRemoteFolderChanged;
538 }
539
540 }