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