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