SynchronizeFolderOperation.java 22 KB

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