78b6a7baacbbc4875e5ddb66172876dca4dc70f4
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20
21 package com.owncloud.android.operations;
22
23 import java.io.File;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Vector;
29
30 import android.accounts.Account;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.util.Log;
34
35
36 import com.owncloud.android.datamodel.FileDataStorageManager;
37 import com.owncloud.android.datamodel.OCFile;
38 import com.owncloud.android.files.services.FileDownloader;
39 import com.owncloud.android.lib.common.OwnCloudClient;
40 import com.owncloud.android.lib.common.operations.OperationCancelledException;
41 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
42 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
43 import com.owncloud.android.lib.common.utils.Log_OC;
44 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
45 import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
46 import com.owncloud.android.lib.resources.files.RemoteFile;
47 import com.owncloud.android.operations.common.SyncOperation;
48 import com.owncloud.android.services.OperationsService;
49 import com.owncloud.android.utils.FileStorageUtils;
50
51 import java.util.concurrent.atomic.AtomicBoolean;
52
53 //import android.support.v4.content.LocalBroadcastManager;
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 public class SynchronizeFolderOperation extends SyncOperation {
66
67 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
68
69 /** Time stamp for the synchronization process in progress */
70 private long mCurrentSyncTime;
71
72 /** Remote path of the folder to synchronize */
73 private String mRemotePath;
74
75 /** Account where the file to synchronize belongs */
76 private Account mAccount;
77
78 /** Android context; necessary to send requests to the download service */
79 private Context mContext;
80
81 /** Locally cached information about folder to synchronize */
82 private OCFile mLocalFolder;
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 mFailsInFileSyncsFound;
92
93 /** 'True' means that the remote folder changed and should be fetched */
94 private boolean mRemoteFolderChanged;
95
96 private List<OCFile> mFilesForDirectDownload;
97 // to avoid extra PROPFINDs when there was no change in the folder
98
99 private List<SyncOperation> mFilesToSyncContentsWithoutUpload;
100 // this will go out when 'folder synchronization' replaces 'folder download'; step by step
101
102 private List<SyncOperation> mFavouriteFilesToSyncContents;
103 // this will be used for every file when 'folder synchronization' replaces 'folder download'
104
105 private final AtomicBoolean mCancellationRequested;
106
107 /**
108 * Creates a new instance of {@link SynchronizeFolderOperation}.
109 *
110 * @param context Application context.
111 * @param remotePath Path to synchronize.
112 * @param account ownCloud account where the folder is located.
113 * @param currentSyncTime Time stamp for the synchronization process in progress.
114 */
115 public SynchronizeFolderOperation(Context context, String remotePath, Account account,
116 long currentSyncTime){
117 mRemotePath = remotePath;
118 mCurrentSyncTime = currentSyncTime;
119 mAccount = account;
120 mContext = context;
121 mRemoteFolderChanged = false;
122 mFilesForDirectDownload = new Vector<OCFile>();
123 mFilesToSyncContentsWithoutUpload = new Vector<SyncOperation>();
124 mFavouriteFilesToSyncContents = new Vector<SyncOperation>();
125 mCancellationRequested = new AtomicBoolean(false);
126 }
127
128
129 public int getConflictsFound() {
130 return mConflictsFound;
131 }
132
133 public int getFailsInFileSyncsFound() {
134 return mFailsInFileSyncsFound;
135 }
136
137 /**
138 * Performs the synchronization.
139 *
140 * {@inheritDoc}
141 */
142 @Override
143 protected RemoteOperationResult run(OwnCloudClient client) {
144 RemoteOperationResult result = null;
145 mFailsInFileSyncsFound = 0;
146 mConflictsFound = 0;
147
148 try {
149 // get locally cached information about folder
150 mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
151
152 result = checkForChanges(client);
153
154 if (result.isSuccess()) {
155 if (mRemoteFolderChanged) {
156 result = fetchAndSyncRemoteFolder(client);
157
158 } else {
159 prepareOpsFromLocalKnowledge();
160 }
161
162 if (result.isSuccess()) {
163 syncContents(client);
164 }
165
166 }
167
168 if (mCancellationRequested.get()) {
169 throw new OperationCancelledException();
170 }
171
172 } catch (OperationCancelledException e) {
173 result = new RemoteOperationResult(e);
174 }
175
176 return result;
177
178 }
179
180 private RemoteOperationResult checkForChanges(OwnCloudClient client)
181 throws OperationCancelledException {
182 Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
183
184 mRemoteFolderChanged = true;
185 RemoteOperationResult result = null;
186
187 if (mCancellationRequested.get()) {
188 throw new OperationCancelledException();
189 }
190
191 // remote request
192 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
193 result = operation.execute(client);
194 if (result.isSuccess()){
195 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
196
197 // check if remote and local folder are different
198 mRemoteFolderChanged =
199 !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
200
201 result = new RemoteOperationResult(ResultCode.OK);
202
203 Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
204 (mRemoteFolderChanged ? "changed" : "not changed"));
205
206 } else {
207 // check failed
208 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
209 removeLocalFolder();
210 }
211 if (result.isException()) {
212 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
213 result.getLogMessage(), result.getException());
214 } else {
215 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
216 result.getLogMessage());
217 }
218
219 }
220
221 return result;
222 }
223
224
225 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client)
226 throws OperationCancelledException {
227 if (mCancellationRequested.get()) {
228 throw new OperationCancelledException();
229 }
230
231 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
232 RemoteOperationResult result = operation.execute(client);
233 Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
234
235 if (result.isSuccess()) {
236 synchronizeData(result.getData(), client);
237 if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
238 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
239 // should be a different result code, but will do the job
240 }
241 } else {
242 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
243 removeLocalFolder();
244 }
245
246
247 return result;
248 }
249
250
251 private void removeLocalFolder() {
252 FileDataStorageManager storageManager = getStorageManager();
253 if (storageManager.fileExists(mLocalFolder.getFileId())) {
254 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
255 storageManager.removeFolder(
256 mLocalFolder,
257 true,
258 ( mLocalFolder.isDown() && // TODO: debug, I think this is
259 // always false for folders
260 mLocalFolder.getStoragePath().startsWith(currentSavePath)
261 )
262 );
263 }
264 }
265
266
267 /**
268 * Synchronizes the data retrieved from the server about the contents of the target folder
269 * with the current data in the local database.
270 *
271 * Grants that mChildren is updated with fresh data after execution.
272 *
273 * @param folderAndFiles Remote folder and children files in Folder
274 *
275 * @param client Client instance to the remote server where the data were
276 * retrieved.
277 * @return 'True' when any change was made in the local data, 'false' otherwise
278 */
279 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client)
280 throws OperationCancelledException {
281 FileDataStorageManager storageManager = getStorageManager();
282
283 // parse data from remote folder
284 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
285 remoteFolder.setParentId(mLocalFolder.getParentId());
286 remoteFolder.setFileId(mLocalFolder.getFileId());
287
288 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
289 + " changed - starting update of local data ");
290
291 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
292 mFilesForDirectDownload.clear();
293 mFilesToSyncContentsWithoutUpload.clear();
294 mFavouriteFilesToSyncContents.clear();
295
296 if (mCancellationRequested.get()) {
297 throw new OperationCancelledException();
298 }
299
300 // get current data about local contents of the folder to synchronize
301 // TODO Enable when "On Device" is recovered ?
302 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder/*, false*/);
303 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
304 for (OCFile file : localFiles) {
305 localFilesMap.put(file.getRemotePath(), file);
306 }
307
308 // loop to synchronize every child
309 OCFile remoteFile = null, localFile = null;
310 for (int i=1; i<folderAndFiles.size(); i++) {
311 /// new OCFile instance with the data from the server
312 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
313 remoteFile.setParentId(mLocalFolder.getFileId());
314
315 /// retrieve local data for the read file
316 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
317 localFile = localFilesMap.remove(remoteFile.getRemotePath());
318
319 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
320 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
321 if (localFile != null) {
322 // some properties of local state are kept unmodified
323 remoteFile.setFileId(localFile.getFileId());
324 remoteFile.setFavorite(localFile.isFavorite());
325 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
326 remoteFile.setModificationTimestampAtLastSyncForData(
327 localFile.getModificationTimestampAtLastSyncForData()
328 );
329 remoteFile.setStoragePath(localFile.getStoragePath());
330 // eTag will not be updated unless contents are synchronized
331 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
332 remoteFile.setEtag(localFile.getEtag());
333 if (remoteFile.isFolder()) {
334 remoteFile.setFileLength(localFile.getFileLength());
335 // TODO move operations about size of folders to FileContentProvider
336 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
337 remoteFile.getModificationTimestamp() !=
338 localFile.getModificationTimestamp()) {
339 remoteFile.setNeedsUpdateThumbnail(true);
340 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
341 }
342 remoteFile.setPublicLink(localFile.getPublicLink());
343 remoteFile.setShareByLink(localFile.isShareByLink());
344 } else {
345 // remote eTag will not be updated unless contents are synchronized
346 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
347 remoteFile.setEtag("");
348 }
349
350 /// check and fix, if needed, local storage path
351 searchForLocalFileInDefaultPath(remoteFile);
352
353 /// classify file to sync/download contents later
354 if (remoteFile.isFolder()) {
355 /// to download children files recursively
356 synchronized(mCancellationRequested) {
357 if (mCancellationRequested.get()) {
358 throw new OperationCancelledException();
359 }
360 startSyncFolderOperation(remoteFile.getRemotePath());
361 }
362
363 } else if (remoteFile.isFavorite()) {
364 /// prepare content synchronization for kept-in-sync files
365 SynchronizeFileOperation operation = new SynchronizeFileOperation(
366 localFile,
367 remoteFile,
368 mAccount,
369 true,
370 mContext
371 );
372 mFavouriteFilesToSyncContents.add(operation);
373
374 } else {
375 /// prepare limited synchronization for regular files
376 SynchronizeFileOperation operation = new SynchronizeFileOperation(
377 localFile,
378 remoteFile,
379 mAccount,
380 true,
381 false,
382 mContext
383 );
384 mFilesToSyncContentsWithoutUpload.add(operation);
385 }
386
387 updatedFiles.add(remoteFile);
388 }
389
390 // save updated contents in local database
391 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
392
393 }
394
395
396 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
397 // TODO Enable when "On Device" is recovered ?
398 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder/*, false*/);
399 for (OCFile child : children) {
400 /// classify file to sync/download contents later
401 if (child.isFolder()) {
402 /// to download children files recursively
403 synchronized(mCancellationRequested) {
404 if (mCancellationRequested.get()) {
405 throw new OperationCancelledException();
406 }
407 startSyncFolderOperation(child.getRemotePath());
408 }
409
410 } else {
411 /// prepare limited synchronization for regular files
412 if (!child.isDown()) {
413 mFilesForDirectDownload.add(child);
414 }
415 }
416 }
417 }
418
419
420 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
421 startDirectDownloads();
422 startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client);
423 startContentSynchronizations(mFavouriteFilesToSyncContents, client);
424 }
425
426
427 private void startDirectDownloads() throws OperationCancelledException {
428 for (OCFile file : mFilesForDirectDownload) {
429 synchronized(mCancellationRequested) {
430 if (mCancellationRequested.get()) {
431 throw new OperationCancelledException();
432 }
433 Intent i = new Intent(mContext, FileDownloader.class);
434 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
435 i.putExtra(FileDownloader.EXTRA_FILE, file);
436 mContext.startService(i);
437 }
438 }
439 }
440
441 /**
442 * Performs a list of synchronization operations, determining if a download or upload is needed
443 * or if exists conflict due to changes both in local and remote contents of the each file.
444 *
445 * If download or upload is needed, request the operation to the corresponding service and goes
446 * on.
447 *
448 * @param filesToSyncContents Synchronization operations to execute.
449 * @param client Interface to the remote ownCloud server.
450 */
451 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents,
452 OwnCloudClient client)
453 throws OperationCancelledException {
454
455 Log_OC.v(TAG, "Starting content synchronization... ");
456 RemoteOperationResult contentsResult = null;
457 for (SyncOperation op: filesToSyncContents) {
458 if (mCancellationRequested.get()) {
459 throw new OperationCancelledException();
460 }
461 contentsResult = op.execute(getStorageManager(), mContext);
462 if (!contentsResult.isSuccess()) {
463 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
464 mConflictsFound++;
465 } else {
466 mFailsInFileSyncsFound++;
467 if (contentsResult.getException() != null) {
468 Log_OC.e(TAG, "Error while synchronizing file : "
469 + contentsResult.getLogMessage(), contentsResult.getException());
470 } else {
471 Log_OC.e(TAG, "Error while synchronizing file : "
472 + contentsResult.getLogMessage());
473 }
474 }
475 // TODO - use the errors count in notifications
476 } // won't let these fails break the synchronization process
477 }
478 }
479
480
481 /**
482 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
483 * object with the data read from the server.
484 *
485 * @param remote remote file read from the server (remote file or folder).
486 * @return New OCFile instance representing the remote resource described by we.
487 */
488 private OCFile fillOCFile(RemoteFile remote) {
489 OCFile file = new OCFile(remote.getRemotePath());
490 file.setCreationTimestamp(remote.getCreationTimestamp());
491 file.setFileLength(remote.getLength());
492 file.setMimetype(remote.getMimeType());
493 file.setModificationTimestamp(remote.getModifiedTimestamp());
494 file.setEtag(remote.getEtag());
495 file.setPermissions(remote.getPermissions());
496 file.setRemoteId(remote.getRemoteId());
497 return file;
498 }
499
500
501 /**
502 * Scans the default location for saving local copies of files searching for
503 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
504 * received as parameter.
505 *
506 * @param file File to associate a possible 'lost' local file.
507 */
508 private void searchForLocalFileInDefaultPath(OCFile file) {
509 if (file.getStoragePath() == null && !file.isFolder()) {
510 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
511 if (f.exists()) {
512 file.setStoragePath(f.getAbsolutePath());
513 file.setLastSyncDateForData(f.lastModified());
514 }
515 }
516 }
517
518
519 /**
520 * Cancel operation
521 */
522 public void cancel() {
523 mCancellationRequested.set(true);
524 }
525
526 public String getFolderPath() {
527 String path = mLocalFolder.getStoragePath();
528 if (path != null && path.length() > 0) {
529 return path;
530 }
531 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
532 }
533
534 private void startSyncFolderOperation(String path){
535 Intent intent = new Intent(mContext, OperationsService.class);
536 intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
537 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
538 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
539 mContext.startService(intent);
540 }
541
542 public String getRemotePath() {
543 return mRemotePath;
544 }
545 }