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