SynchronizeFolderOperation.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2016 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. package com.owncloud.android.operations;
  21. import android.content.Context;
  22. import android.content.Intent;
  23. import android.text.TextUtils;
  24. import android.util.Log;
  25. import com.nextcloud.client.account.User;
  26. import com.owncloud.android.datamodel.DecryptedFolderMetadata;
  27. import com.owncloud.android.datamodel.FileDataStorageManager;
  28. import com.owncloud.android.datamodel.OCFile;
  29. import com.owncloud.android.files.services.FileDownloader;
  30. import com.owncloud.android.lib.common.OwnCloudClient;
  31. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  32. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  33. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  34. import com.owncloud.android.lib.common.utils.Log_OC;
  35. import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
  36. import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
  37. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  38. import com.owncloud.android.operations.common.SyncOperation;
  39. import com.owncloud.android.services.OperationsService;
  40. import com.owncloud.android.utils.FileStorageUtils;
  41. import com.owncloud.android.utils.MimeTypeUtil;
  42. import java.io.File;
  43. import java.util.ArrayList;
  44. import java.util.List;
  45. import java.util.Map;
  46. import java.util.Vector;
  47. import java.util.concurrent.atomic.AtomicBoolean;
  48. /**
  49. * Remote operation performing the synchronization of the list of files contained
  50. * in a folder identified with its remote path.
  51. *
  52. * Fetches the list and properties of the files contained in the given folder, including their
  53. * properties, and updates the local database with them.
  54. *
  55. * Does NOT enter in the child folders to synchronize their contents also, BUT requests for a new operation instance
  56. * doing so.
  57. */
  58. public class SynchronizeFolderOperation extends SyncOperation {
  59. private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
  60. /** Time stamp for the synchronization process in progress */
  61. private long mCurrentSyncTime;
  62. /** Remote path of the folder to synchronize */
  63. private String mRemotePath;
  64. /** Account where the file to synchronize belongs */
  65. private User user;
  66. /** Android context; necessary to send requests to the download service */
  67. private Context mContext;
  68. /** Locally cached information about folder to synchronize */
  69. private OCFile mLocalFolder;
  70. /** Counter of conflicts found between local and remote files */
  71. private int mConflictsFound;
  72. /** Counter of failed operations in synchronization of kept-in-sync files */
  73. private int mFailsInFileSyncsFound;
  74. /** 'True' means that the remote folder changed and should be fetched */
  75. private boolean mRemoteFolderChanged;
  76. private List<OCFile> mFilesForDirectDownload;
  77. // to avoid extra PROPFINDs when there was no change in the folder
  78. private List<SyncOperation> mFilesToSyncContents;
  79. // this will be used for every file when 'folder synchronization' replaces 'folder download'
  80. private final AtomicBoolean mCancellationRequested;
  81. /**
  82. * Creates a new instance of {@link SynchronizeFolderOperation}.
  83. *
  84. * @param context Application context.
  85. * @param remotePath Path to synchronize.
  86. * @param user Nextcloud account where the folder is located.
  87. * @param currentSyncTime Time stamp for the synchronization process in progress.
  88. */
  89. public SynchronizeFolderOperation(Context context,
  90. String remotePath,
  91. User user,
  92. long currentSyncTime,
  93. FileDataStorageManager storageManager) {
  94. super(storageManager);
  95. mRemotePath = remotePath;
  96. mCurrentSyncTime = currentSyncTime;
  97. this.user = user;
  98. mContext = context;
  99. mRemoteFolderChanged = false;
  100. mFilesForDirectDownload = new Vector<>();
  101. mFilesToSyncContents = new Vector<>();
  102. mCancellationRequested = new AtomicBoolean(false);
  103. }
  104. /**
  105. * Performs the synchronization.
  106. *
  107. * {@inheritDoc}
  108. */
  109. @Override
  110. protected RemoteOperationResult run(OwnCloudClient client) {
  111. RemoteOperationResult result;
  112. mFailsInFileSyncsFound = 0;
  113. mConflictsFound = 0;
  114. try {
  115. // get locally cached information about folder
  116. mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
  117. result = checkForChanges(client);
  118. if (result.isSuccess()) {
  119. if (mRemoteFolderChanged) {
  120. result = fetchAndSyncRemoteFolder(client);
  121. } else {
  122. prepareOpsFromLocalKnowledge();
  123. }
  124. if (result.isSuccess()) {
  125. syncContents();
  126. }
  127. }
  128. if (mCancellationRequested.get()) {
  129. throw new OperationCancelledException();
  130. }
  131. } catch (OperationCancelledException e) {
  132. result = new RemoteOperationResult(e);
  133. }
  134. return result;
  135. }
  136. private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException {
  137. Log_OC.d(TAG, "Checking changes in " + user.getAccountName() + mRemotePath);
  138. mRemoteFolderChanged = true;
  139. if (mCancellationRequested.get()) {
  140. throw new OperationCancelledException();
  141. }
  142. // remote request
  143. ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
  144. RemoteOperationResult result = operation.execute(client);
  145. if (result.isSuccess()) {
  146. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  147. // check if remote and local folder are different
  148. mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
  149. result = new RemoteOperationResult(ResultCode.OK);
  150. Log_OC.i(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
  151. (mRemoteFolderChanged ? "changed" : "not changed"));
  152. } else {
  153. // check failed
  154. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  155. removeLocalFolder();
  156. }
  157. if (result.isException()) {
  158. Log_OC.e(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
  159. result.getLogMessage(), result.getException());
  160. } else {
  161. Log_OC.e(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
  162. result.getLogMessage());
  163. }
  164. }
  165. return result;
  166. }
  167. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
  168. if (mCancellationRequested.get()) {
  169. throw new OperationCancelledException();
  170. }
  171. ReadFolderRemoteOperation operation = new ReadFolderRemoteOperation(mRemotePath);
  172. RemoteOperationResult result = operation.execute(client);
  173. Log_OC.d(TAG, "Synchronizing " + user.getAccountName() + mRemotePath);
  174. if (result.isSuccess()) {
  175. synchronizeData(result.getData());
  176. if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
  177. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  178. // should be a different result code, but will do the job
  179. }
  180. } else {
  181. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  182. removeLocalFolder();
  183. }
  184. }
  185. return result;
  186. }
  187. private void removeLocalFolder() {
  188. FileDataStorageManager storageManager = getStorageManager();
  189. if (storageManager.fileExists(mLocalFolder.getFileId())) {
  190. String currentSavePath = FileStorageUtils.getSavePath(user.getAccountName());
  191. storageManager.removeFolder(
  192. mLocalFolder,
  193. true,
  194. mLocalFolder.isDown() // TODO: debug, I think this is always false for folders
  195. && mLocalFolder.getStoragePath().startsWith(currentSavePath)
  196. );
  197. }
  198. }
  199. /**
  200. * Synchronizes the data retrieved from the server about the contents of the target folder
  201. * with the current data in the local database.
  202. *
  203. * @param folderAndFiles Remote folder and children files in Folder
  204. */
  205. private void synchronizeData(List<Object> folderAndFiles) throws OperationCancelledException {
  206. // parse data from remote folder
  207. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  208. remoteFolder.setParentId(mLocalFolder.getParentId());
  209. remoteFolder.setFileId(mLocalFolder.getFileId());
  210. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
  211. mFilesForDirectDownload.clear();
  212. mFilesToSyncContents.clear();
  213. if (mCancellationRequested.get()) {
  214. throw new OperationCancelledException();
  215. }
  216. FileDataStorageManager storageManager = getStorageManager();
  217. // if local folder is encrypted, download fresh metadata
  218. boolean encryptedAncestor = FileStorageUtils.checkEncryptionStatus(remoteFolder, storageManager);
  219. mLocalFolder.setEncrypted(encryptedAncestor);
  220. // update permission
  221. mLocalFolder.setPermissions(remoteFolder.getPermissions());
  222. // update richWorkspace
  223. mLocalFolder.setRichWorkspace(remoteFolder.getRichWorkspace());
  224. DecryptedFolderMetadata metadata = RefreshFolderOperation.getDecryptedFolderMetadata(encryptedAncestor,
  225. mLocalFolder,
  226. getClient(),
  227. user,
  228. mContext);
  229. // get current data about local contents of the folder to synchronize
  230. Map<String, OCFile> localFilesMap =
  231. RefreshFolderOperation.prefillLocalFilesMap(metadata,
  232. storageManager.getFolderContent(mLocalFolder, false));
  233. // loop to synchronize every child
  234. List<OCFile> updatedFiles = new ArrayList<>(folderAndFiles.size() - 1);
  235. OCFile remoteFile;
  236. OCFile localFile;
  237. OCFile updatedFile;
  238. RemoteFile remote;
  239. for (int i = 1; i < folderAndFiles.size(); i++) {
  240. /// new OCFile instance with the data from the server
  241. remote = (RemoteFile) folderAndFiles.get(i);
  242. remoteFile = FileStorageUtils.fillOCFile(remote);
  243. /// new OCFile instance to merge fresh data from server with local state
  244. updatedFile = FileStorageUtils.fillOCFile(remote);
  245. updatedFile.setParentId(mLocalFolder.getFileId());
  246. /// retrieve local data for the read file
  247. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  248. // TODO better implementation is needed
  249. if (localFile == null) {
  250. localFile = storageManager.getFileByPath(updatedFile.getRemotePath());
  251. }
  252. /// add to updatedFile data about LOCAL STATE (not existing in server)
  253. updateLocalStateData(remoteFile, localFile, updatedFile);
  254. /// check and fix, if needed, local storage path
  255. FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, user.getAccountName());
  256. // update file name for encrypted files
  257. if (metadata != null) {
  258. RefreshFolderOperation.updateFileNameForEncryptedFile(storageManager, metadata, updatedFile);
  259. }
  260. // we parse content, so either the folder itself or its direct parent (which we check) must be encrypted
  261. boolean encrypted = updatedFile.isEncrypted() || mLocalFolder.isEncrypted();
  262. updatedFile.setEncrypted(encrypted);
  263. /// classify file to sync/download contents later
  264. classifyFileForLaterSyncOrDownload(remoteFile, localFile);
  265. updatedFiles.add(updatedFile);
  266. }
  267. if (metadata != null) {
  268. RefreshFolderOperation.updateFileNameForEncryptedFile(storageManager, metadata, mLocalFolder);
  269. }
  270. // save updated contents in local database
  271. storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  272. mLocalFolder.setLastSyncDateForData(System.currentTimeMillis());
  273. storageManager.saveFile(mLocalFolder);
  274. }
  275. private void updateLocalStateData(OCFile remoteFile, OCFile localFile, OCFile updatedFile) {
  276. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  277. if (localFile != null) {
  278. updatedFile.setFileId(localFile.getFileId());
  279. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  280. updatedFile.setModificationTimestampAtLastSyncForData(
  281. localFile.getModificationTimestampAtLastSyncForData()
  282. );
  283. updatedFile.setStoragePath(localFile.getStoragePath());
  284. // eTag will not be updated unless file CONTENTS are synchronized
  285. updatedFile.setEtag(localFile.getEtag());
  286. if (updatedFile.isFolder()) {
  287. updatedFile.setFileLength(localFile.getFileLength());
  288. // TODO move operations about size of folders to FileContentProvider
  289. } else if (mRemoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
  290. remoteFile.getModificationTimestamp() !=
  291. localFile.getModificationTimestamp()) {
  292. updatedFile.setUpdateThumbnailNeeded(true);
  293. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  294. }
  295. updatedFile.setSharedViaLink(localFile.isSharedViaLink());
  296. updatedFile.setSharedWithSharee(localFile.isSharedWithSharee());
  297. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  298. } else {
  299. // remote eTag will not be updated unless file CONTENTS are synchronized
  300. updatedFile.setEtag("");
  301. }
  302. }
  303. private void classifyFileForLaterSyncOrDownload(OCFile remoteFile, OCFile localFile)
  304. throws OperationCancelledException {
  305. if (remoteFile.isFolder()) {
  306. /// to download children files recursively
  307. synchronized (mCancellationRequested) {
  308. if (mCancellationRequested.get()) {
  309. throw new OperationCancelledException();
  310. }
  311. startSyncFolderOperation(remoteFile.getRemotePath());
  312. }
  313. } else {
  314. /// prepare content synchronization for files (any file, not just favorites)
  315. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  316. localFile,
  317. remoteFile,
  318. user,
  319. true,
  320. mContext,
  321. getStorageManager()
  322. );
  323. mFilesToSyncContents.add(operation);
  324. }
  325. }
  326. private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
  327. List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder, false);
  328. for (OCFile child : children) {
  329. /// classify file to sync/download contents later
  330. if (child.isFolder()) {
  331. /// to download children files recursively
  332. synchronized(mCancellationRequested) {
  333. if (mCancellationRequested.get()) {
  334. throw new OperationCancelledException();
  335. }
  336. startSyncFolderOperation(child.getRemotePath());
  337. }
  338. } else {
  339. /// synchronization for regular files
  340. if (!child.isDown()) {
  341. mFilesForDirectDownload.add(child);
  342. } else {
  343. /// this should result in direct upload of files that were locally modified
  344. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  345. child,
  346. child.getEtagInConflict() != null ? child : null,
  347. user,
  348. true,
  349. mContext,
  350. getStorageManager()
  351. );
  352. mFilesToSyncContents.add(operation);
  353. }
  354. }
  355. }
  356. }
  357. private void syncContents() throws OperationCancelledException {
  358. startDirectDownloads();
  359. startContentSynchronizations(mFilesToSyncContents);
  360. }
  361. private void startDirectDownloads() throws OperationCancelledException {
  362. for (OCFile file : mFilesForDirectDownload) {
  363. synchronized(mCancellationRequested) {
  364. if (mCancellationRequested.get()) {
  365. throw new OperationCancelledException();
  366. }
  367. Intent i = new Intent(mContext, FileDownloader.class);
  368. i.putExtra(FileDownloader.EXTRA_USER, user);
  369. i.putExtra(FileDownloader.EXTRA_FILE, file);
  370. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  371. mContext.startForegroundService(i);
  372. } else {
  373. mContext.startService(i);
  374. }
  375. }
  376. }
  377. }
  378. /**
  379. * Performs a list of synchronization operations, determining if a download or upload is needed
  380. * or if exists conflict due to changes both in local and remote contents of the each file.
  381. *
  382. * If download or upload is needed, request the operation to the corresponding service and goes on.
  383. *
  384. * @param filesToSyncContents Synchronization operations to execute.
  385. */
  386. private void startContentSynchronizations(List<SyncOperation> filesToSyncContents)
  387. throws OperationCancelledException {
  388. Log_OC.v(TAG, "Starting content synchronization... ");
  389. RemoteOperationResult contentsResult;
  390. for (SyncOperation op: filesToSyncContents) {
  391. if (mCancellationRequested.get()) {
  392. throw new OperationCancelledException();
  393. }
  394. contentsResult = op.execute(mContext);
  395. if (!contentsResult.isSuccess()) {
  396. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  397. mConflictsFound++;
  398. } else {
  399. mFailsInFileSyncsFound++;
  400. if (contentsResult.getException() != null) {
  401. Log_OC.e(TAG, "Error while synchronizing file : "
  402. + contentsResult.getLogMessage(), contentsResult.getException());
  403. } else {
  404. Log_OC.e(TAG, "Error while synchronizing file : "
  405. + contentsResult.getLogMessage());
  406. }
  407. }
  408. // TODO - use the errors count in notifications
  409. } // won't let these fails break the synchronization process
  410. }
  411. }
  412. /**
  413. * Scans the default location for saving local copies of files searching for
  414. * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
  415. * received as parameter.
  416. *
  417. * @param file File to associate a possible 'lost' local file.
  418. */
  419. private void searchForLocalFileInDefaultPath(OCFile file) {
  420. if (file.getStoragePath() == null && !file.isFolder()) {
  421. File f = new File(FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), file));
  422. if (f.exists()) {
  423. file.setStoragePath(f.getAbsolutePath());
  424. file.setLastSyncDateForData(f.lastModified());
  425. }
  426. }
  427. }
  428. /**
  429. * Cancel operation
  430. */
  431. public void cancel() {
  432. mCancellationRequested.set(true);
  433. }
  434. public String getFolderPath() {
  435. String path = mLocalFolder.getStoragePath();
  436. if (!TextUtils.isEmpty(path)) {
  437. return path;
  438. }
  439. return FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mLocalFolder);
  440. }
  441. private void startSyncFolderOperation(String path){
  442. Intent intent = new Intent(mContext, OperationsService.class);
  443. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  444. intent.putExtra(OperationsService.EXTRA_ACCOUNT, user.toPlatformAccount());
  445. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
  446. mContext.startService(intent);
  447. }
  448. public String getRemotePath() {
  449. return mRemotePath;
  450. }
  451. }