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