Fixed NullPointerExceptionS in upload cancelations
[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, BUT requests for a new operation instance
64 * doing so.
65 */
66 public class SynchronizeFolderOperation extends SyncOperation {
67
68 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
69
70 /** Time stamp for the synchronization process in progress */
71 private long mCurrentSyncTime;
72
73 /** Remote path of the folder to synchronize */
74 private String mRemotePath;
75
76 /** Account where the file to synchronize belongs */
77 private Account mAccount;
78
79 /** Android context; necessary to send requests to the download service */
80 private Context mContext;
81
82 /** Locally cached information about folder to synchronize */
83 private OCFile mLocalFolder;
84
85 /** Files and folders contained in the synchronized folder after a successful operation */
86 //private List<OCFile> mChildren;
87
88 /** Counter of conflicts found between local and remote files */
89 private int mConflictsFound;
90
91 /** Counter of failed operations in synchronization of kept-in-sync files */
92 private int mFailsInFileSyncsFound;
93
94 /** 'True' means that the remote folder changed and should be fetched */
95 private boolean mRemoteFolderChanged;
96
97 private List<OCFile> mFilesForDirectDownload;
98 // to avoid extra PROPFINDs when there was no change in the folder
99
100 private List<SyncOperation> mFilesToSyncContents;
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,
114 long currentSyncTime){
115 mRemotePath = remotePath;
116 mCurrentSyncTime = currentSyncTime;
117 mAccount = account;
118 mContext = context;
119 mRemoteFolderChanged = false;
120 mFilesForDirectDownload = new Vector<OCFile>();
121 mFilesToSyncContents = 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)
178 throws OperationCancelledException {
179 Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
180
181 mRemoteFolderChanged = true;
182 RemoteOperationResult result = null;
183
184 if (mCancellationRequested.get()) {
185 throw new OperationCancelledException();
186 }
187
188 // remote request
189 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
190 result = operation.execute(client);
191 if (result.isSuccess()){
192 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
193
194 // check if remote and local folder are different
195 mRemoteFolderChanged =
196 !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
197
198 result = new RemoteOperationResult(ResultCode.OK);
199
200 Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
201 (mRemoteFolderChanged ? "changed" : "not changed"));
202
203 } else {
204 // check failed
205 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
206 removeLocalFolder();
207 }
208 if (result.isException()) {
209 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
210 result.getLogMessage(), result.getException());
211 } else {
212 Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
213 result.getLogMessage());
214 }
215
216 }
217
218 return result;
219 }
220
221
222 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client)
223 throws OperationCancelledException {
224 if (mCancellationRequested.get()) {
225 throw new OperationCancelledException();
226 }
227
228 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
229 RemoteOperationResult result = operation.execute(client);
230 Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
231
232 if (result.isSuccess()) {
233 synchronizeData(result.getData(), client);
234 if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
235 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
236 // should be a different result code, but will do the job
237 }
238 } else {
239 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
240 removeLocalFolder();
241 }
242
243
244 return result;
245 }
246
247
248 private void removeLocalFolder() {
249 FileDataStorageManager storageManager = getStorageManager();
250 if (storageManager.fileExists(mLocalFolder.getFileId())) {
251 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
252 storageManager.removeFolder(
253 mLocalFolder,
254 true,
255 ( mLocalFolder.isDown() && // TODO: debug, I think this is
256 // always false for folders
257 mLocalFolder.getStoragePath().startsWith(currentSavePath)
258 )
259 );
260 }
261 }
262
263
264 /**
265 * Synchronizes the data retrieved from the server about the contents of the target folder
266 * with the current data in the local database.
267 *
268 * Grants that mChildren is updated with fresh data after execution.
269 *
270 * @param folderAndFiles Remote folder and children files in Folder
271 *
272 * @param client Client instance to the remote server where the data were
273 * retrieved.
274 * @return 'True' when any change was made in the local data, 'false' otherwise
275 */
276 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client)
277 throws OperationCancelledException {
278 FileDataStorageManager storageManager = getStorageManager();
279
280 // parse data from remote folder
281 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
282 remoteFolder.setParentId(mLocalFolder.getParentId());
283 remoteFolder.setFileId(mLocalFolder.getFileId());
284
285 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
286 + " changed - starting update of local data ");
287
288 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
289 mFilesForDirectDownload.clear();
290 mFilesToSyncContents.clear();
291
292 if (mCancellationRequested.get()) {
293 throw new OperationCancelledException();
294 }
295
296 // get current data about local contents of the folder to synchronize
297 // TODO Enable when "On Device" is recovered ?
298 List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder/*, false*/);
299 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
300 for (OCFile file : localFiles) {
301 localFilesMap.put(file.getRemotePath(), file);
302 }
303
304 // loop to synchronize every child
305 OCFile remoteFile = null, localFile = null;
306 for (int i=1; i<folderAndFiles.size(); i++) {
307 /// new OCFile instance with the data from the server
308 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
309 remoteFile.setParentId(mLocalFolder.getFileId());
310
311 /// retrieve local data for the read file
312 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
313 localFile = localFilesMap.remove(remoteFile.getRemotePath());
314
315 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
316 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
317 if (localFile != null) {
318 // some properties of local state are kept unmodified
319 remoteFile.setFileId(localFile.getFileId());
320 remoteFile.setFavorite(localFile.isFavorite());
321 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
322 remoteFile.setModificationTimestampAtLastSyncForData(
323 localFile.getModificationTimestampAtLastSyncForData()
324 );
325 remoteFile.setStoragePath(localFile.getStoragePath());
326 // eTag will not be updated unless contents are synchronized
327 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
328 remoteFile.setEtag(localFile.getEtag());
329 if (remoteFile.isFolder()) {
330 remoteFile.setFileLength(localFile.getFileLength());
331 // TODO move operations about size of folders to FileContentProvider
332 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
333 remoteFile.getModificationTimestamp() !=
334 localFile.getModificationTimestamp()) {
335 remoteFile.setNeedsUpdateThumbnail(true);
336 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
337 }
338 remoteFile.setPublicLink(localFile.getPublicLink());
339 remoteFile.setShareByLink(localFile.isShareByLink());
340 } else {
341 // remote eTag will not be updated unless contents are synchronized
342 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
343 remoteFile.setEtag("");
344 }
345
346 /// check and fix, if needed, local storage path
347 searchForLocalFileInDefaultPath(remoteFile);
348
349 /// classify file to sync/download contents later
350 if (remoteFile.isFolder()) {
351 /// to download children files recursively
352 synchronized (mCancellationRequested) {
353 if (mCancellationRequested.get()) {
354 throw new OperationCancelledException();
355 }
356 startSyncFolderOperation(remoteFile.getRemotePath());
357 }
358
359 //} else if (remoteFile.isFavorite()) {
360 } else {
361 /// prepare content synchronization for kept-in-sync files
362 SynchronizeFileOperation operation = new SynchronizeFileOperation(
363 localFile,
364 remoteFile,
365 mAccount,
366 true,
367 mContext
368 );
369 mFilesToSyncContents.add(operation);
370
371 /*} else {
372 /// prepare limited synchronization for regular files
373 SynchronizeFileOperation operation = new SynchronizeFileOperation(
374 localFile,
375 remoteFile,
376 mAccount,
377 true,
378 false,
379 mContext
380 );
381 mFilesToSyncContentsWithoutUpload.add(operation);*/
382 }
383
384 updatedFiles.add(remoteFile);
385 }
386
387 // save updated contents in local database
388 storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
389
390 }
391
392
393 private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
394 // TODO Enable when "On Device" is recovered ?
395 List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder/*, false*/);
396 for (OCFile child : children) {
397 /// classify file to sync/download contents later
398 if (child.isFolder()) {
399 /// to download children files recursively
400 synchronized(mCancellationRequested) {
401 if (mCancellationRequested.get()) {
402 throw new OperationCancelledException();
403 }
404 startSyncFolderOperation(child.getRemotePath());
405 }
406
407 } else {
408 /// prepare limited synchronization for regular files
409 if (!child.isDown()) {
410 mFilesForDirectDownload.add(child);
411
412 } else {
413 /// this should result in direct upload of files that were locally modified
414 SynchronizeFileOperation operation = new SynchronizeFileOperation(
415 child,
416 child, // cheating with the remote file to get an upadte to server; to refactor
417 mAccount,
418 true,
419 mContext
420 );
421 mFilesToSyncContents.add(operation);
422
423 }
424
425 }
426 }
427 }
428
429
430 private void syncContents(OwnCloudClient client) throws OperationCancelledException {
431 startDirectDownloads();
432 startContentSynchronizations(mFilesToSyncContents, client);
433 }
434
435
436 private void startDirectDownloads() throws OperationCancelledException {
437 for (OCFile file : mFilesForDirectDownload) {
438 synchronized(mCancellationRequested) {
439 if (mCancellationRequested.get()) {
440 throw new OperationCancelledException();
441 }
442 Intent i = new Intent(mContext, FileDownloader.class);
443 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
444 i.putExtra(FileDownloader.EXTRA_FILE, file);
445 mContext.startService(i);
446 }
447 }
448 }
449
450 /**
451 * Performs a list of synchronization operations, determining if a download or upload is needed
452 * or if exists conflict due to changes both in local and remote contents of the each file.
453 *
454 * If download or upload is needed, request the operation to the corresponding service and goes
455 * on.
456 *
457 * @param filesToSyncContents Synchronization operations to execute.
458 * @param client Interface to the remote ownCloud server.
459 */
460 private void startContentSynchronizations(List<SyncOperation> filesToSyncContents,
461 OwnCloudClient client)
462 throws OperationCancelledException {
463
464 Log_OC.v(TAG, "Starting content synchronization... ");
465 RemoteOperationResult contentsResult = null;
466 for (SyncOperation op: filesToSyncContents) {
467 if (mCancellationRequested.get()) {
468 throw new OperationCancelledException();
469 }
470 contentsResult = op.execute(getStorageManager(), mContext);
471 if (!contentsResult.isSuccess()) {
472 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
473 mConflictsFound++;
474 } else {
475 mFailsInFileSyncsFound++;
476 if (contentsResult.getException() != null) {
477 Log_OC.e(TAG, "Error while synchronizing file : "
478 + contentsResult.getLogMessage(), contentsResult.getException());
479 } else {
480 Log_OC.e(TAG, "Error while synchronizing file : "
481 + contentsResult.getLogMessage());
482 }
483 }
484 // TODO - use the errors count in notifications
485 } // won't let these fails break the synchronization process
486 }
487 }
488
489
490 /**
491 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
492 * object with the data read from the server.
493 *
494 * @param remote remote file read from the server (remote file or folder).
495 * @return New OCFile instance representing the remote resource described by we.
496 */
497 private OCFile fillOCFile(RemoteFile remote) {
498 OCFile file = new OCFile(remote.getRemotePath());
499 file.setCreationTimestamp(remote.getCreationTimestamp());
500 file.setFileLength(remote.getLength());
501 file.setMimetype(remote.getMimeType());
502 file.setModificationTimestamp(remote.getModifiedTimestamp());
503 file.setEtag(remote.getEtag());
504 file.setPermissions(remote.getPermissions());
505 file.setRemoteId(remote.getRemoteId());
506 return file;
507 }
508
509
510 /**
511 * Scans the default location for saving local copies of files searching for
512 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
513 * received as parameter.
514 *
515 * @param file File to associate a possible 'lost' local file.
516 */
517 private void searchForLocalFileInDefaultPath(OCFile file) {
518 if (file.getStoragePath() == null && !file.isFolder()) {
519 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
520 if (f.exists()) {
521 file.setStoragePath(f.getAbsolutePath());
522 file.setLastSyncDateForData(f.lastModified());
523 }
524 }
525 }
526
527
528 /**
529 * Cancel operation
530 */
531 public void cancel() {
532 mCancellationRequested.set(true);
533 }
534
535 public String getFolderPath() {
536 String path = mLocalFolder.getStoragePath();
537 if (path != null && path.length() > 0) {
538 return path;
539 }
540 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
541 }
542
543 private void startSyncFolderOperation(String path){
544 Intent intent = new Intent(mContext, OperationsService.class);
545 intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
546 intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
547 intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
548 mContext.startService(intent);
549 }
550
551 public String getRemotePath() {
552 return mRemotePath;
553 }
554 }