SynchronizeFolderOperation.java 23 KB

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