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