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