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