enabled all occurrences.
[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 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder, false);
302 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
303 for (OCFile file : localFiles) {
304 localFilesMap.put(file.getRemotePath(), file);
305 }
306
307 // loop to synchronize every child
308 OCFile remoteFile = null, localFile = null;
309 for (int i=1; i<folderAndFiles.size(); i++) {
310 /// new OCFile instance with the data from the server
311 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
312 remoteFile.setParentId(mLocalFolder.getFileId());
313
314 /// retrieve local data for the read file
315 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
316 localFile = localFilesMap.remove(remoteFile.getRemotePath());
317
318 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
319 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
320 if (localFile != null) {
321 // some properties of local state are kept unmodified
322 remoteFile.setFileId(localFile.getFileId());
323 remoteFile.setFavorite(localFile.isFavorite());
324 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
325 remoteFile.setModificationTimestampAtLastSyncForData(
326 localFile.getModificationTimestampAtLastSyncForData()
327 );
328 remoteFile.setStoragePath(localFile.getStoragePath());
329 // eTag will not be updated unless contents are synchronized
330 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
331 remoteFile.setEtag(localFile.getEtag());
332 if (remoteFile.isFolder()) {
333 remoteFile.setFileLength(localFile.getFileLength());
334 // TODO move operations about size of folders to FileContentProvider
335 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
336 remoteFile.getModificationTimestamp() !=
337 localFile.getModificationTimestamp()) {
338 remoteFile.setNeedsUpdateThumbnail(true);
339 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
340 }
341 remoteFile.setPublicLink(localFile.getPublicLink());
342 remoteFile.setShareByLink(localFile.isShareByLink());
343 } else {
344 // remote eTag will not be updated unless contents are synchronized
345 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
346 remoteFile.setEtag("");
347 }
348
349 /// check and fix, if needed, local storage path
350 searchForLocalFileInDefaultPath(remoteFile);
351
352 /// classify file to sync/download contents later
353 if (remoteFile.isFolder()) {
354 /// to download children files recursively
355 synchronized(mCancellationRequested) {
356 if (mCancellationRequested.get()) {
357 throw new OperationCancelledException();
358 }
359 startSyncFolderOperation(remoteFile.getRemotePath());
360 }
361
362 } else if (remoteFile.isFavorite()) {
363 /// prepare content synchronization for kept-in-sync files
364 SynchronizeFileOperation operation = new SynchronizeFileOperation(
365 localFile,
366 remoteFile,
367 mAccount,
368 true,
369 mContext
370 );
371 mFavouriteFilesToSyncContents.add(operation);
372
373 } else {
374 /// prepare limited synchronization for regular files
375 SynchronizeFileOperation operation = new SynchronizeFileOperation(
376 localFile,
377 remoteFile,
378 mAccount,
379 true,
380 false,
381 mContext
382 );
383 mFilesToSyncContentsWithoutUpload.add(operation);
384 }
385
386 updatedFiles.add(remoteFile);
387 }
388
389 // save updated contents in local database
390 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
391
392 }
393
394
395 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
396 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder, false);
397 for (OCFile child : children) {
398 /// classify file to sync/download contents later
399 if (child.isFolder()) {
400 /// to download children files recursively
401 synchronized(mCancellationRequested) {
402 if (mCancellationRequested.get()) {
403 throw new OperationCancelledException();
404 }
405 startSyncFolderOperation(child.getRemotePath());
406 }
407
408 } else {
409 /// prepare limited synchronization for regular files
410 if (!child.isDown()) {
411 mFilesForDirectDownload.add(child);
412 }
413 }
414 }
415 }
416
417
418 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
419 startDirectDownloads();
420 startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client);
421 startContentSynchronizations(mFavouriteFilesToSyncContents, client);
422 }
423
424
425 private void startDirectDownloads() throws OperationCancelledException {
426 for (OCFile file : mFilesForDirectDownload) {
427 synchronized(mCancellationRequested) {
428 if (mCancellationRequested.get()) {
429 throw new OperationCancelledException();
430 }
431 Intent i = new Intent(mContext, FileDownloader.class);
432 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
433 i.putExtra(FileDownloader.EXTRA_FILE, file);
434 mContext.startService(i);
435 }
436 }
437 }
438
439 /**
440 * Performs a list of synchronization operations, determining if a download or upload is needed
441 * or if exists conflict due to changes both in local and remote contents of the each file.
442 *
443 * If download or upload is needed, request the operation to the corresponding service and goes
444 * on.
445 *
446 * @param filesToSyncContents Synchronization operations to execute.
447 * @param client Interface to the remote ownCloud server.
448 */
449 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents,
450 OwnCloudClient client)
451 throws OperationCancelledException {
452
453 Log_OC.v(TAG, "Starting content synchronization... ");
454 RemoteOperationResult contentsResult = null;
455 for (SyncOperation op: filesToSyncContents) {
456 if (mCancellationRequested.get()) {
457 throw new OperationCancelledException();
458 }
459 contentsResult = op.execute(getStorageManager(), mContext);
460 if (!contentsResult.isSuccess()) {
461 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
462 mConflictsFound++;
463 } else {
464 mFailsInFileSyncsFound++;
465 if (contentsResult.getException() != null) {
466 Log_OC.e(TAG, "Error while synchronizing file : "
467 + contentsResult.getLogMessage(), contentsResult.getException());
468 } else {
469 Log_OC.e(TAG, "Error while synchronizing file : "
470 + contentsResult.getLogMessage());
471 }
472 }
473 // TODO - use the errors count in notifications
474 } // won't let these fails break the synchronization process
475 }
476 }
477
478
479 /**
480 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
481 * object with the data read from the server.
482 *
483 * @param remote remote file read from the server (remote file or folder).
484 * @return New OCFile instance representing the remote resource described by we.
485 */
486 private OCFile fillOCFile(RemoteFile remote) {
487 OCFile file = new OCFile(remote.getRemotePath());
488 file.setCreationTimestamp(remote.getCreationTimestamp());
489 file.setFileLength(remote.getLength());
490 file.setMimetype(remote.getMimeType());
491 file.setModificationTimestamp(remote.getModifiedTimestamp());
492 file.setEtag(remote.getEtag());
493 file.setPermissions(remote.getPermissions());
494 file.setRemoteId(remote.getRemoteId());
495 return file;
496 }
497
498
499 /**
500 * Scans the default location for saving local copies of files searching for
501 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
502 * received as parameter.
503 *
504 * @param file File to associate a possible 'lost' local file.
505 */
506 private void searchForLocalFileInDefaultPath(OCFile file) {
507 if (file.getStoragePath() == null && !file.isFolder()) {
508 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
509 if (f.exists()) {
510 file.setStoragePath(f.getAbsolutePath());
511 file.setLastSyncDateForData(f.lastModified());
512 }
513 }
514 }
515
516
517 /**
518 * Cancel operation
519 */
520 public void cancel() {
521 mCancellationRequested.set(true);
522 }
523
524 public String getFolderPath() {
525 String path = mLocalFolder.getStoragePath();
526 if (path != null && path.length() > 0) {
527 return path;
528 }
529 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
530 }
531
532 private void startSyncFolderOperation(String path){
533 Intent intent = new Intent(mContext, OperationsService.class);
534 intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
535 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
536 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
537 mContext.startService(intent);
538 }
539
540 public String getRemotePath() {
541 return mRemotePath;
542 }
543 }