cf5bccd67e6595269fa568cdb3a3b549756bf184
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / RefreshFolderOperation.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.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Vector;
28
29 import android.accounts.Account;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.util.Log;
33
34 import com.owncloud.android.datamodel.FileDataStorageManager;
35 import com.owncloud.android.datamodel.OCFile;
36
37 import com.owncloud.android.lib.common.OwnCloudClient;
38 import com.owncloud.android.lib.resources.shares.OCShare;
39 import com.owncloud.android.lib.common.operations.RemoteOperation;
40 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
41 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
42 import com.owncloud.android.lib.common.utils.Log_OC;
43 import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
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
48 import com.owncloud.android.syncadapter.FileSyncAdapter;
49 import com.owncloud.android.utils.FileStorageUtils;
50
51
52
53 /**
54 * Remote operation performing the synchronization of the list of files contained
55 * in a folder identified with its remote path.
56 *
57 * Fetches the list and properties of the files contained in the given folder, including their
58 * properties, and updates the local database with them.
59 *
60 * Does NOT enter in the child folders to synchronize their contents also.
61 */
62 public class RefreshFolderOperation extends RemoteOperation {
63
64 private static final String TAG = RefreshFolderOperation.class.getSimpleName();
65
66 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED =
67 RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
68 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
69 RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
70
71 /** Time stamp for the synchronization process in progress */
72 private long mCurrentSyncTime;
73
74 /** Remote folder to synchronize */
75 private OCFile mLocalFolder;
76
77 /** Access to the local database */
78 private FileDataStorageManager mStorageManager;
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 /** Files and folders contained in the synchronized folder after a successful operation */
87 private List<OCFile> mChildren;
88
89 /** Counter of conflicts found between local and remote files */
90 private int mConflictsFound;
91
92 /** Counter of failed operations in synchronization of kept-in-sync files */
93 private int mFailsInFavouritesFound;
94
95 /**
96 * Map of remote and local paths to files that where locally stored in a location
97 * out of the ownCloud folder and couldn't be copied automatically into it
98 **/
99 private Map<String, String> mForgottenLocalFiles;
100
101 /** 'True' means that this operation is part of a full account synchronization */
102 private boolean mSyncFullAccount;
103
104 /** 'True' means that Share resources bound to the files into should be refreshed also */
105 private boolean mIsShareSupported;
106
107 /** 'True' means that the remote folder changed and should be fetched */
108 private boolean mRemoteFolderChanged;
109
110 /** 'True' means that Etag will be ignored */
111 private boolean mIgnoreETag;
112
113 private List<SynchronizeFileOperation> mFilesToSyncContents;
114 // this will be used for every file when 'folder synchronization' replaces 'folder download'
115
116
117 /**
118 * Creates a new instance of {@link RefreshFolderOperation}.
119 *
120 * @param folder Folder to synchronize.
121 * @param currentSyncTime Time stamp for the synchronization process in progress.
122 * @param syncFullAccount 'True' means that this operation is part of a full account
123 * synchronization.
124 * @param isShareSupported 'True' means that the server supports the sharing API.
125 * @param ignoreETag 'True' means that the content of the remote folder should
126 * be fetched and updated even though the 'eTag' did not
127 * change.
128 * @param dataStorageManager Interface with the local database.
129 * @param account ownCloud account where the folder is located.
130 * @param context Application context.
131 */
132 public RefreshFolderOperation(OCFile folder,
133 long currentSyncTime,
134 boolean syncFullAccount,
135 boolean isShareSupported,
136 boolean ignoreETag,
137 FileDataStorageManager dataStorageManager,
138 Account account,
139 Context context) {
140 mLocalFolder = folder;
141 mCurrentSyncTime = currentSyncTime;
142 mSyncFullAccount = syncFullAccount;
143 mIsShareSupported = isShareSupported;
144 mStorageManager = dataStorageManager;
145 mAccount = account;
146 mContext = context;
147 mForgottenLocalFiles = new HashMap<String, String>();
148 mRemoteFolderChanged = false;
149 mIgnoreETag = ignoreETag;
150 mFilesToSyncContents = new Vector<SynchronizeFileOperation>();
151 }
152
153
154 public int getConflictsFound() {
155 return mConflictsFound;
156 }
157
158 public int getFailsInFavouritesFound() {
159 return mFailsInFavouritesFound;
160 }
161
162 public Map<String, String> getForgottenLocalFiles() {
163 return mForgottenLocalFiles;
164 }
165
166 /**
167 * Returns the list of files and folders contained in the synchronized folder,
168 * if called after synchronization is complete.
169 *
170 * @return List of files and folders contained in the synchronized folder.
171 */
172 public List<OCFile> getChildren() {
173 return mChildren;
174 }
175
176 /**
177 * Performs the synchronization.
178 *
179 * {@inheritDoc}
180 */
181 @Override
182 protected RemoteOperationResult run(OwnCloudClient client) {
183 RemoteOperationResult result = null;
184 mFailsInFavouritesFound = 0;
185 mConflictsFound = 0;
186 mForgottenLocalFiles.clear();
187
188 if (OCFile.ROOT_PATH.equals(mLocalFolder.getRemotePath()) && !mSyncFullAccount) {
189 updateOCVersion(client);
190 }
191
192 result = checkForChanges(client);
193
194 if (result.isSuccess()) {
195 if (mRemoteFolderChanged) {
196 result = fetchAndSyncRemoteFolder(client);
197 } else {
198 fetchFavoritesToSyncFromLocalData();
199 mChildren = mStorageManager.getFolderContent(mLocalFolder/*, false*/);
200 }
201
202 if (result.isSuccess()) {
203 // request for the synchronization of KEPT-IN-SYNC file contents
204 startContentSynchronizations(mFilesToSyncContents, client);
205 }
206 }
207
208 if (!mSyncFullAccount) {
209 sendLocalBroadcast(
210 EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result
211 );
212 }
213
214 if (result.isSuccess() && mIsShareSupported && !mSyncFullAccount) {
215 refreshSharesForFolder(client); // share result is ignored
216 }
217
218 if (!mSyncFullAccount) {
219 sendLocalBroadcast(
220 EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result
221 );
222 }
223
224 return result;
225
226 }
227
228
229 private void updateOCVersion(OwnCloudClient client) {
230 UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
231 RemoteOperationResult result = update.execute(client);
232 if (result.isSuccess()) {
233 mIsShareSupported = update.getOCVersion().isSharedSupported();
234 }
235 }
236
237
238 private RemoteOperationResult checkForChanges(OwnCloudClient client) {
239 mRemoteFolderChanged = true;
240 RemoteOperationResult result = null;
241 String remotePath = mLocalFolder.getRemotePath();
242
243 Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
244
245 // remote request
246 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
247 result = operation.execute(client);
248 if (result.isSuccess()){
249 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
250
251 if (!mIgnoreETag) {
252 // check if remote and local folder are different
253 String remoteFolderETag = remoteFolder.getEtag();
254 if (remoteFolderETag != null) {
255 mRemoteFolderChanged =
256 !(remoteFolderETag.equalsIgnoreCase(mLocalFolder.getEtag()));
257 } else {
258 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
259 "No ETag received from server");
260 }
261 }
262
263 result = new RemoteOperationResult(ResultCode.OK);
264
265 Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
266 (mRemoteFolderChanged ? "changed" : "not changed"));
267
268 } else {
269 // check failed
270 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
271 removeLocalFolder();
272 }
273 if (result.isException()) {
274 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
275 result.getLogMessage(), result.getException());
276 } else {
277 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
278 result.getLogMessage());
279 }
280 }
281
282 return result;
283 }
284
285
286 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
287 String remotePath = mLocalFolder.getRemotePath();
288 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
289 RemoteOperationResult result = operation.execute(client);
290 Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
291
292 if (result.isSuccess()) {
293 synchronizeData(result.getData(), client);
294 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
295 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
296 // should be a different result code, but will do the job
297 }
298 } else {
299 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
300 removeLocalFolder();
301 }
302
303 return result;
304 }
305
306
307 private void removeLocalFolder() {
308 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
309 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
310 mStorageManager.removeFolder(
311 mLocalFolder,
312 true,
313 ( mLocalFolder.isDown() &&
314 mLocalFolder.getStoragePath().startsWith(currentSavePath)
315 )
316 );
317 }
318 }
319
320
321 /**
322 * Synchronizes the data retrieved from the server about the contents of the target folder
323 * with the current data in the local database.
324 *
325 * Grants that mChildren is updated with fresh data after execution.
326 *
327 * @param folderAndFiles Remote folder and children files in Folder
328 *
329 * @param client Client instance to the remote server where the data were
330 * retrieved.
331 * @return 'True' when any change was made in the local data, 'false' otherwise
332 */
333 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
334 // get 'fresh data' from the database
335 mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
336
337 // parse data from remote folder
338 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
339 remoteFolder.setParentId(mLocalFolder.getParentId());
340 remoteFolder.setFileId(mLocalFolder.getFileId());
341
342 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
343 + " changed - starting update of local data ");
344
345 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
346 mFilesToSyncContents.clear();
347
348 // get current data about local contents of the folder to synchronize
349 // TODO Enable when "On Device" is recovered ?
350 List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder/*, false*/);
351 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
352 for (OCFile file : localFiles) {
353 localFilesMap.put(file.getRemotePath(), file);
354 }
355
356 // loop to update every child
357 OCFile remoteFile = null, localFile = null, updatedFile = null;
358 RemoteFile r;
359 for (int i=1; i<folderAndFiles.size(); i++) {
360 /// new OCFile instance with the data from the server
361 r = (RemoteFile) folderAndFiles.get(i);
362 remoteFile = FileStorageUtils.fillOCFile(r);
363
364 /// new OCFile instance to merge fresh data from server with local state
365 updatedFile = FileStorageUtils.fillOCFile(r);
366 updatedFile.setParentId(mLocalFolder.getFileId());
367
368 /// retrieve local data for the read file
369 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
370 localFile = localFilesMap.remove(remoteFile.getRemotePath());
371
372 /// add to updatedFile data about LOCAL STATE (not existing in server)
373 updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
374 if (localFile != null) {
375 updatedFile.setFileId(localFile.getFileId());
376 updatedFile.setFavorite(localFile.isFavorite());
377 updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
378 updatedFile.setModificationTimestampAtLastSyncForData(
379 localFile.getModificationTimestampAtLastSyncForData()
380 );
381 updatedFile.setStoragePath(localFile.getStoragePath());
382 // eTag will not be updated unless file CONTENTS are synchronized
383 updatedFile.setEtag(localFile.getEtag());
384 if (updatedFile.isFolder()) {
385 updatedFile.setFileLength(localFile.getFileLength());
386 // TODO move operations about size of folders to FileContentProvider
387 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
388 remoteFile.getModificationTimestamp() !=
389 localFile.getModificationTimestamp()) {
390 updatedFile.setNeedsUpdateThumbnail(true);
391 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
392 }
393 updatedFile.setPublicLink(localFile.getPublicLink());
394 updatedFile.setShareByLink(localFile.isShareByLink());
395 updatedFile.setInConflict(localFile.isInConflict());
396 } else {
397 // remote eTag will not be updated unless file CONTENTS are synchronized
398 updatedFile.setEtag("");
399 }
400
401 /// check and fix, if needed, local storage path
402 FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, mAccount);
403
404 /// prepare content synchronization for kept-in-sync files
405 if (updatedFile.isFavorite()) {
406 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
407 remoteFile,
408 mAccount,
409 true,
410 mContext
411 );
412
413 mFilesToSyncContents.add(operation);
414 }
415
416 updatedFiles.add(updatedFile);
417 }
418
419 // save updated contents in local database
420 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
421
422 mChildren = updatedFiles;
423 }
424
425 /**
426 * Performs a list of synchronization operations, determining if a download or upload is needed
427 * or if exists conflict due to changes both in local and remote contents of the each file.
428 *
429 * If download or upload is needed, request the operation to the corresponding service and goes
430 * on.
431 *
432 * @param filesToSyncContents Synchronization operations to execute.
433 * @param client Interface to the remote ownCloud server.
434 */
435 private void startContentSynchronizations(
436 List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
437 ) {
438 RemoteOperationResult contentsResult = null;
439 for (SynchronizeFileOperation op: filesToSyncContents) {
440 contentsResult = op.execute(mStorageManager, mContext); // async
441 if (!contentsResult.isSuccess()) {
442 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
443 mConflictsFound++;
444 } else {
445 mFailsInFavouritesFound++;
446 if (contentsResult.getException() != null) {
447 Log_OC.e(TAG, "Error while synchronizing favourites : "
448 + contentsResult.getLogMessage(), contentsResult.getException());
449 } else {
450 Log_OC.e(TAG, "Error while synchronizing favourites : "
451 + contentsResult.getLogMessage());
452 }
453 }
454 } // won't let these fails break the synchronization process
455 }
456 }
457
458
459 private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
460 RemoteOperationResult result = null;
461
462 // remote request
463 GetRemoteSharesForFileOperation operation =
464 new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
465 result = operation.execute(client);
466
467 if (result.isSuccess()) {
468 // update local database
469 ArrayList<OCShare> shares = new ArrayList<OCShare>();
470 for(Object obj: result.getData()) {
471 shares.add((OCShare) obj);
472 }
473 mStorageManager.saveSharesInFolder(shares, mLocalFolder);
474 }
475
476 return result;
477 }
478
479
480 /**
481 * Sends a message to any application component interested in the progress
482 * of the synchronization.
483 *
484 * @param event
485 * @param dirRemotePath Remote path of a folder that was just synchronized
486 * (with or without success)
487 * @param result
488 */
489 private void sendLocalBroadcast(
490 String event, String dirRemotePath, RemoteOperationResult result
491 ) {
492 Log_OC.d(TAG, "Send broadcast " + event);
493 Intent intent = new Intent(event);
494 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
495 if (dirRemotePath != null) {
496 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
497 }
498 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
499 mContext.sendStickyBroadcast(intent);
500 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
501 }
502
503
504 private void fetchFavoritesToSyncFromLocalData() {
505 List<OCFile> children = mStorageManager.getFolderContent(mLocalFolder);
506 for (OCFile child : children) {
507 if (!child.isFolder() && child.isFavorite()) {
508 SynchronizeFileOperation operation = new SynchronizeFileOperation(
509 child,
510 child, // cheating with the remote file to get an update to server; to refactor
511 mAccount,
512 true,
513 mContext
514 );
515 mFilesToSyncContents.add(operation);
516 }
517 }
518 }
519
520 }