fixed icon (+naming) to use resolution depended icon and don't scale
[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.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Vector;
34
35 import org.apache.http.HttpStatus;
36 import android.accounts.Account;
37 import android.content.Context;
38 import android.content.Intent;
39 import android.util.Log;
40 //import android.support.v4.content.LocalBroadcastManager;
41
42 import com.owncloud.android.MainApp;
43 import com.owncloud.android.datamodel.FileDataStorageManager;
44 import com.owncloud.android.datamodel.OCFile;
45
46 import com.owncloud.android.lib.common.OwnCloudClient;
47 import com.owncloud.android.lib.resources.shares.OCShare;
48 import com.owncloud.android.lib.common.operations.RemoteOperation;
49 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
50 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
51 import com.owncloud.android.lib.common.utils.Log_OC;
52 import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
53 import com.owncloud.android.lib.resources.files.FileUtils;
54 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
55 import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
56 import com.owncloud.android.lib.resources.files.RemoteFile;
57
58 import com.owncloud.android.syncadapter.FileSyncAdapter;
59 import com.owncloud.android.utils.FileStorageUtils;
60
61
62
63 /**
64 * Remote operation performing the synchronization of the list of files contained
65 * in a folder identified with its remote path.
66 *
67 * Fetches the list and properties of the files contained in the given folder, including their
68 * properties, and updates the local database with them.
69 *
70 * Does NOT enter in the child folders to synchronize their contents also.
71 */
72 public class RefreshFolderOperation extends RemoteOperation {
73
74 private static final String TAG = RefreshFolderOperation.class.getSimpleName();
75
76 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED =
77 RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
78 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
79 RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
80
81 /** Time stamp for the synchronization process in progress */
82 private long mCurrentSyncTime;
83
84 /** Remote folder to synchronize */
85 private OCFile mLocalFolder;
86
87 /** Access to the local database */
88 private FileDataStorageManager mStorageManager;
89
90 /** Account where the file to synchronize belongs */
91 private Account mAccount;
92
93 /** Android context; necessary to send requests to the download service */
94 private Context mContext;
95
96 /** Files and folders contained in the synchronized folder after a successful operation */
97 private List<OCFile> mChildren;
98
99 /** Counter of conflicts found between local and remote files */
100 private int mConflictsFound;
101
102 /** Counter of failed operations in synchronization of kept-in-sync files */
103 private int mFailsInFavouritesFound;
104
105 /**
106 * Map of remote and local paths to files that where locally stored in a location
107 * out of the ownCloud folder and couldn't be copied automatically into it
108 **/
109 private Map<String, String> mForgottenLocalFiles;
110
111 /** 'True' means that this operation is part of a full account synchronization */
112 private boolean mSyncFullAccount;
113
114 /** 'True' means that Share resources bound to the files into should be refreshed also */
115 private boolean mIsShareSupported;
116
117 /** 'True' means that the remote folder changed and should be fetched */
118 private boolean mRemoteFolderChanged;
119
120 /** 'True' means that Etag will be ignored */
121 private boolean mIgnoreETag;
122
123
124 /**
125 * Creates a new instance of {@link RefreshFolderOperation}.
126 *
127 * @param folder Folder to synchronize.
128 * @param currentSyncTime Time stamp for the synchronization process in progress.
129 * @param syncFullAccount 'True' means that this operation is part of a full account
130 * synchronization.
131 * @param isShareSupported 'True' means that the server supports the sharing API.
132 * @param ignoreETag 'True' means that the content of the remote folder should
133 * be fetched and updated even though the 'eTag' did not
134 * change.
135 * @param dataStorageManager Interface with the local database.
136 * @param account ownCloud account where the folder is located.
137 * @param context Application context.
138 */
139 public RefreshFolderOperation(OCFile folder,
140 long currentSyncTime,
141 boolean syncFullAccount,
142 boolean isShareSupported,
143 boolean ignoreETag,
144 FileDataStorageManager dataStorageManager,
145 Account account,
146 Context context) {
147 mLocalFolder = folder;
148 mCurrentSyncTime = currentSyncTime;
149 mSyncFullAccount = syncFullAccount;
150 mIsShareSupported = isShareSupported;
151 mStorageManager = dataStorageManager;
152 mAccount = account;
153 mContext = context;
154 mForgottenLocalFiles = new HashMap<String, String>();
155 mRemoteFolderChanged = false;
156 mIgnoreETag = ignoreETag;
157 }
158
159
160 public int getConflictsFound() {
161 return mConflictsFound;
162 }
163
164 public int getFailsInFavouritesFound() {
165 return mFailsInFavouritesFound;
166 }
167
168 public Map<String, String> getForgottenLocalFiles() {
169 return mForgottenLocalFiles;
170 }
171
172 /**
173 * Returns the list of files and folders contained in the synchronized folder,
174 * if called after synchronization is complete.
175 *
176 * @return List of files and folders contained in the synchronized folder.
177 */
178 public List<OCFile> getChildren() {
179 return mChildren;
180 }
181
182 /**
183 * Performs the synchronization.
184 *
185 * {@inheritDoc}
186 */
187 @Override
188 protected RemoteOperationResult run(OwnCloudClient client) {
189 RemoteOperationResult result = null;
190 mFailsInFavouritesFound = 0;
191 mConflictsFound = 0;
192 mForgottenLocalFiles.clear();
193
194 if (FileUtils.PATH_SEPARATOR.equals(mLocalFolder.getRemotePath()) && !mSyncFullAccount) {
195 updateOCVersion(client);
196 }
197
198 result = checkForChanges(client);
199
200 if (result.isSuccess()) {
201 if (mRemoteFolderChanged) {
202 result = fetchAndSyncRemoteFolder(client);
203 } else {
204 mChildren = mStorageManager.getFolderContent(mLocalFolder, false);
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 = null;
242
243 remotePath = mLocalFolder.getRemotePath();
244 Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
245
246 // remote request
247 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
248 result = operation.execute(client);
249 if (result.isSuccess()){
250 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
251
252 if (!mIgnoreETag) {
253 // check if remote and local folder are different
254 String remoteFolderETag = remoteFolder.getEtag();
255 if (remoteFolderETag != null) {
256 mRemoteFolderChanged =
257 !(remoteFolderETag.equalsIgnoreCase(mLocalFolder.getEtag()));
258 } else {
259 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
260 "No ETag received from server");
261 }
262 }
263
264 result = new RemoteOperationResult(ResultCode.OK);
265
266 Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
267 (mRemoteFolderChanged ? "changed" : "not changed"));
268
269 } else {
270 // check failed
271 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
272 removeLocalFolder();
273 }
274 if (result.isException()) {
275 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
276 result.getLogMessage(), result.getException());
277 } else {
278 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
279 result.getLogMessage());
280 }
281 }
282
283 return result;
284 }
285
286
287 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
288 String remotePath = mLocalFolder.getRemotePath();
289 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
290 RemoteOperationResult result = operation.execute(client);
291 Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
292
293 if (result.isSuccess()) {
294 synchronizeData(result.getData(), client);
295 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
296 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
297 // should be a different result code, but will do the job
298 }
299 } else {
300 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
301 removeLocalFolder();
302 }
303
304 return result;
305 }
306
307
308 private void removeLocalFolder() {
309 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
310 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
311 mStorageManager.removeFolder(
312 mLocalFolder,
313 true,
314 ( mLocalFolder.isDown() &&
315 mLocalFolder.getStoragePath().startsWith(currentSavePath)
316 )
317 );
318 }
319 }
320
321
322 /**
323 * Synchronizes the data retrieved from the server about the contents of the target folder
324 * with the current data in the local database.
325 *
326 * Grants that mChildren is updated with fresh data after execution.
327 *
328 * @param folderAndFiles Remote folder and children files in Folder
329 *
330 * @param client Client instance to the remote server where the data were
331 * retrieved.
332 * @return 'True' when any change was made in the local data, 'false' otherwise
333 */
334 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
335 // get 'fresh data' from the database
336 mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
337
338 // parse data from remote folder
339 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
340 remoteFolder.setParentId(mLocalFolder.getParentId());
341 remoteFolder.setFileId(mLocalFolder.getFileId());
342
343 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
344 + " changed - starting update of local data ");
345
346 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
347 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
348
349 // get current data about local contents of the folder to synchronize
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;
358 for (int i=1; i<folderAndFiles.size(); i++) {
359 /// new OCFile instance with the data from the server
360 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
361 remoteFile.setParentId(mLocalFolder.getFileId());
362
363 /// retrieve local data for the read file
364 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
365 localFile = localFilesMap.remove(remoteFile.getRemotePath());
366
367 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
368 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
369 if (localFile != null) {
370 // some properties of local state are kept unmodified
371 remoteFile.setFileId(localFile.getFileId());
372 remoteFile.setFavorite(localFile.isFavorite());
373 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
374 remoteFile.setModificationTimestampAtLastSyncForData(
375 localFile.getModificationTimestampAtLastSyncForData()
376 );
377 remoteFile.setStoragePath(localFile.getStoragePath());
378 // eTag will not be updated unless contents are synchronized
379 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
380 remoteFile.setEtag(localFile.getEtag());
381 if (remoteFile.isFolder()) {
382 remoteFile.setFileLength(localFile.getFileLength());
383 // TODO move operations about size of folders to FileContentProvider
384 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
385 remoteFile.getModificationTimestamp() !=
386 localFile.getModificationTimestamp()) {
387 remoteFile.setNeedsUpdateThumbnail(true);
388 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
389 }
390 remoteFile.setPublicLink(localFile.getPublicLink());
391 remoteFile.setShareByLink(localFile.isShareByLink());
392 } else {
393 // remote eTag will not be updated unless contents are synchronized
394 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
395 remoteFile.setEtag("");
396 }
397
398 /// check and fix, if needed, local storage path
399 checkAndFixForeignStoragePath(remoteFile); // policy - local files are COPIED
400 // into the ownCloud local folder;
401 searchForLocalFileInDefaultPath(remoteFile); // legacy
402
403 /// prepare content synchronization for kept-in-sync files
404 if (remoteFile.isFavorite()) {
405 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
406 remoteFile,
407 mAccount,
408 true,
409 mContext
410 );
411
412 filesToSyncContents.add(operation);
413 }
414
415 updatedFiles.add(remoteFile);
416 }
417
418 // save updated contents in local database
419 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
420
421 // request for the synchronization of file contents AFTER saving current remote properties
422 startContentSynchronizations(filesToSyncContents, client);
423
424 mChildren = updatedFiles;
425 }
426
427 /**
428 * Performs a list of synchronization operations, determining if a download or upload is needed
429 * or if exists conflict due to changes both in local and remote contents of the each file.
430 *
431 * If download or upload is needed, request the operation to the corresponding service and goes
432 * on.
433 *
434 * @param filesToSyncContents Synchronization operations to execute.
435 * @param client Interface to the remote ownCloud server.
436 */
437 private void startContentSynchronizations(
438 List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
439 ) {
440 RemoteOperationResult contentsResult = null;
441 for (SynchronizeFileOperation op: filesToSyncContents) {
442 contentsResult = op.execute(mStorageManager, mContext); // async
443 if (!contentsResult.isSuccess()) {
444 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
445 mConflictsFound++;
446 } else {
447 mFailsInFavouritesFound++;
448 if (contentsResult.getException() != null) {
449 Log_OC.e(TAG, "Error while synchronizing favourites : "
450 + contentsResult.getLogMessage(), contentsResult.getException());
451 } else {
452 Log_OC.e(TAG, "Error while synchronizing favourites : "
453 + contentsResult.getLogMessage());
454 }
455 }
456 } // won't let these fails break the synchronization process
457 }
458 }
459
460
461 public boolean isMultiStatus(int status) {
462 return (status == HttpStatus.SC_MULTI_STATUS);
463 }
464
465 /**
466 * Creates and populates a new {@link OCFile} object with the data read from the server.
467 *
468 * @param remote remote file read from the server (remote file or folder).
469 * @return New OCFile instance representing the remote resource described by we.
470 */
471 private OCFile fillOCFile(RemoteFile remote) {
472 OCFile file = new OCFile(remote.getRemotePath());
473 file.setCreationTimestamp(remote.getCreationTimestamp());
474 file.setFileLength(remote.getLength());
475 file.setMimetype(remote.getMimeType());
476 file.setModificationTimestamp(remote.getModifiedTimestamp());
477 file.setEtag(remote.getEtag());
478 file.setPermissions(remote.getPermissions());
479 file.setRemoteId(remote.getRemoteId());
480 return file;
481 }
482
483
484 /**
485 * Checks the storage path of the OCFile received as parameter.
486 * If it's out of the local ownCloud folder, tries to copy the file inside it.
487 *
488 * If the copy fails, the link to the local file is nullified. The account of forgotten
489 * files is kept in {@link #mForgottenLocalFiles}
490 *)
491 * @param file File to check and fix.
492 */
493 private void checkAndFixForeignStoragePath(OCFile file) {
494 String storagePath = file.getStoragePath();
495 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
496 if (storagePath != null && !storagePath.equals(expectedPath)) {
497 /// fix storagePaths out of the local ownCloud folder
498 File originalFile = new File(storagePath);
499 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
500 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
501 file.setStoragePath(null);
502
503 } else {
504 InputStream in = null;
505 OutputStream out = null;
506 try {
507 File expectedFile = new File(expectedPath);
508 File expectedParent = expectedFile.getParentFile();
509 expectedParent.mkdirs();
510 if (!expectedParent.isDirectory()) {
511 throw new IOException(
512 "Unexpected error: parent directory could not be created"
513 );
514 }
515 expectedFile.createNewFile();
516 if (!expectedFile.isFile()) {
517 throw new IOException("Unexpected error: target file could not be created");
518 }
519 in = new FileInputStream(originalFile);
520 out = new FileOutputStream(expectedFile);
521 byte[] buf = new byte[1024];
522 int len;
523 while ((len = in.read(buf)) > 0){
524 out.write(buf, 0, len);
525 }
526 file.setStoragePath(expectedPath);
527
528 } catch (Exception e) {
529 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
530 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
531 file.setStoragePath(null);
532
533 } finally {
534 try {
535 if (in != null) in.close();
536 } catch (Exception e) {
537 Log_OC.d(TAG, "Weird exception while closing input stream for "
538 + storagePath + " (ignoring)", e);
539 }
540 try {
541 if (out != null) out.close();
542 } catch (Exception e) {
543 Log_OC.d(TAG, "Weird exception while closing output stream for "
544 + expectedPath + " (ignoring)", e);
545 }
546 }
547 }
548 }
549 }
550
551
552 private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
553 RemoteOperationResult result = null;
554
555 // remote request
556 GetRemoteSharesForFileOperation operation =
557 new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
558 result = operation.execute(client);
559
560 if (result.isSuccess()) {
561 // update local database
562 ArrayList<OCShare> shares = new ArrayList<OCShare>();
563 for(Object obj: result.getData()) {
564 shares.add((OCShare) obj);
565 }
566 mStorageManager.saveSharesInFolder(shares, mLocalFolder);
567 }
568
569 return result;
570 }
571
572
573 /**
574 * Scans the default location for saving local copies of files searching for
575 * a 'lost' file with the same full name as the {@link OCFile} received as
576 * parameter.
577 *
578 * @param file File to associate a possible 'lost' local file.
579 */
580 private void searchForLocalFileInDefaultPath(OCFile file) {
581 if (file.getStoragePath() == null && !file.isFolder()) {
582 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
583 if (f.exists()) {
584 file.setStoragePath(f.getAbsolutePath());
585 file.setLastSyncDateForData(f.lastModified());
586 }
587 }
588 }
589
590
591 /**
592 * Sends a message to any application component interested in the progress
593 * of the synchronization.
594 *
595 * @param event
596 * @param dirRemotePath Remote path of a folder that was just synchronized
597 * (with or without success)
598 * @param result
599 */
600 private void sendLocalBroadcast(
601 String event, String dirRemotePath, RemoteOperationResult result
602 ) {
603 Log_OC.d(TAG, "Send broadcast " + event);
604 Intent intent = new Intent(event);
605 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
606 if (dirRemotePath != null) {
607 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
608 }
609 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
610 mContext.sendStickyBroadcast(intent);
611 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
612 }
613
614
615 public boolean getRemoteFolderChanged() {
616 return mRemoteFolderChanged;
617 }
618
619 }