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