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