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