RefreshFolderOperation.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. package com.owncloud.android.operations;
  20. import android.accounts.Account;
  21. import android.content.Context;
  22. import android.content.Intent;
  23. import android.util.Log;
  24. import com.google.gson.Gson;
  25. import com.nextcloud.android.lib.resources.directediting.DirectEditingObtainRemoteOperation;
  26. import com.nextcloud.common.NextcloudClient;
  27. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  28. import com.owncloud.android.datamodel.DecryptedFolderMetadata;
  29. import com.owncloud.android.datamodel.FileDataStorageManager;
  30. import com.owncloud.android.datamodel.OCFile;
  31. import com.owncloud.android.lib.common.DirectEditing;
  32. import com.owncloud.android.lib.common.OwnCloudClient;
  33. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  34. import com.owncloud.android.lib.common.accounts.AccountUtils;
  35. import com.owncloud.android.lib.common.operations.RemoteOperation;
  36. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  37. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  39. import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
  40. import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
  41. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  42. import com.owncloud.android.lib.resources.shares.GetSharesForFileRemoteOperation;
  43. import com.owncloud.android.lib.resources.shares.OCShare;
  44. import com.owncloud.android.lib.resources.shares.ShareType;
  45. import com.owncloud.android.lib.resources.users.GetPredefinedStatusesRemoteOperation;
  46. import com.owncloud.android.lib.resources.users.PredefinedStatus;
  47. import com.owncloud.android.syncadapter.FileSyncAdapter;
  48. import com.owncloud.android.utils.DataHolderUtil;
  49. import com.owncloud.android.utils.EncryptionUtils;
  50. import com.owncloud.android.utils.FileStorageUtils;
  51. import com.owncloud.android.utils.MimeType;
  52. import com.owncloud.android.utils.MimeTypeUtil;
  53. import java.util.ArrayList;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Vector;
  58. import androidx.annotation.NonNull;
  59. import androidx.annotation.Nullable;
  60. import androidx.localbroadcastmanager.content.LocalBroadcastManager;
  61. import static com.owncloud.android.datamodel.OCFile.PATH_SEPARATOR;
  62. /**
  63. * Remote operation performing the synchronization of the list of files contained
  64. * in a folder identified with its remote path.
  65. *
  66. * Fetches the list and properties of the files contained in the given folder, including their
  67. * properties, and updates the local database with them.
  68. *
  69. * Does NOT enter in the child folders to synchronize their contents also.
  70. */
  71. @SuppressWarnings("PMD.AvoidDuplicateLiterals")
  72. public class RefreshFolderOperation extends RemoteOperation {
  73. private static final String TAG = RefreshFolderOperation.class.getSimpleName();
  74. public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED =
  75. RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
  76. public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
  77. RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
  78. /** Time stamp for the synchronization process in progress */
  79. private long mCurrentSyncTime;
  80. /** Remote folder to synchronize */
  81. private OCFile mLocalFolder;
  82. /** Access to the local database */
  83. private FileDataStorageManager mStorageManager;
  84. /** Account where the file to synchronize belongs */
  85. private Account mAccount;
  86. /** Android context; necessary to send requests to the download service */
  87. private Context mContext;
  88. /** Files and folders contained in the synchronized folder after a successful operation */
  89. private List<OCFile> mChildren;
  90. /** Counter of conflicts found between local and remote files */
  91. private int mConflictsFound;
  92. /** Counter of failed operations in synchronization of kept-in-sync files */
  93. private int mFailsInKeptInSyncFound;
  94. /**
  95. * Map of remote and local paths to files that where locally stored in a location
  96. * out of the ownCloud folder and couldn't be copied automatically into it
  97. **/
  98. private Map<String, String> mForgottenLocalFiles;
  99. /**
  100. * 'True' means that this operation is part of a full account synchronization
  101. */
  102. private boolean mSyncFullAccount;
  103. /** 'True' means that the remote folder changed and should be fetched */
  104. private boolean mRemoteFolderChanged;
  105. /** 'True' means that Etag will be ignored */
  106. private boolean mIgnoreETag;
  107. /**
  108. * 'True' means that no share and no capabilities will be updated
  109. */
  110. private boolean mOnlyFileMetadata;
  111. private List<SynchronizeFileOperation> mFilesToSyncContents;
  112. // this will be used for every file when 'folder synchronization' replaces 'folder download'
  113. /**
  114. * Creates a new instance of {@link RefreshFolderOperation}.
  115. *
  116. * @param folder Folder to synchronize.
  117. * @param currentSyncTime Time stamp for the synchronization process in progress.
  118. * @param syncFullAccount 'True' means that this operation is part of a full account
  119. * synchronization.
  120. * @param ignoreETag 'True' means that the content of the remote folder should
  121. * be fetched and updated even though the 'eTag' did not
  122. * change.
  123. * @param dataStorageManager Interface with the local database.
  124. * @param account ownCloud account where the folder is located.
  125. * @param context Application context.
  126. */
  127. public RefreshFolderOperation(OCFile folder,
  128. long currentSyncTime,
  129. boolean syncFullAccount,
  130. boolean ignoreETag,
  131. FileDataStorageManager dataStorageManager,
  132. Account account,
  133. Context context) {
  134. mLocalFolder = folder;
  135. mCurrentSyncTime = currentSyncTime;
  136. mSyncFullAccount = syncFullAccount;
  137. mStorageManager = dataStorageManager;
  138. mAccount = account;
  139. mContext = context;
  140. mForgottenLocalFiles = new HashMap<>();
  141. mRemoteFolderChanged = false;
  142. mIgnoreETag = ignoreETag;
  143. mOnlyFileMetadata = false;
  144. mFilesToSyncContents = new Vector<>();
  145. }
  146. public RefreshFolderOperation(OCFile folder,
  147. long currentSyncTime,
  148. boolean syncFullAccount,
  149. boolean ignoreETag,
  150. boolean onlyFileMetadata,
  151. FileDataStorageManager dataStorageManager,
  152. Account account,
  153. Context context) {
  154. mLocalFolder = folder;
  155. mCurrentSyncTime = currentSyncTime;
  156. mSyncFullAccount = syncFullAccount;
  157. mStorageManager = dataStorageManager;
  158. mAccount = account;
  159. mContext = context;
  160. mForgottenLocalFiles = new HashMap<>();
  161. mRemoteFolderChanged = false;
  162. mIgnoreETag = ignoreETag;
  163. mOnlyFileMetadata = onlyFileMetadata;
  164. mFilesToSyncContents = new Vector<>();
  165. }
  166. public int getConflictsFound() {
  167. return mConflictsFound;
  168. }
  169. public int getFailsInKeptInSyncFound() {
  170. return mFailsInKeptInSyncFound;
  171. }
  172. public Map<String, String> getForgottenLocalFiles() {
  173. return mForgottenLocalFiles;
  174. }
  175. /**
  176. * Returns the list of files and folders contained in the synchronized folder,
  177. * if called after synchronization is complete.
  178. *
  179. * @return List of files and folders contained in the synchronized folder.
  180. */
  181. public List<OCFile> getChildren() {
  182. return mChildren;
  183. }
  184. /**
  185. * Performs the synchronization.
  186. *
  187. * {@inheritDoc}
  188. */
  189. @Override
  190. protected RemoteOperationResult run(OwnCloudClient client) {
  191. RemoteOperationResult result;
  192. mFailsInKeptInSyncFound = 0;
  193. mConflictsFound = 0;
  194. mForgottenLocalFiles.clear();
  195. if (OCFile.ROOT_PATH.equals(mLocalFolder.getRemotePath()) && !mSyncFullAccount && !mOnlyFileMetadata) {
  196. updateOCVersion(client);
  197. updateUserProfile();
  198. }
  199. result = checkForChanges(client);
  200. if (result.isSuccess()) {
  201. if (mRemoteFolderChanged) {
  202. result = fetchAndSyncRemoteFolder(client);
  203. } else {
  204. mChildren = mStorageManager.getFolderContent(mLocalFolder, false);
  205. }
  206. if (result.isSuccess()) {
  207. // request for the synchronization of KEPT-IN-SYNC file contents
  208. startContentSynchronizations(mFilesToSyncContents);
  209. }
  210. mLocalFolder.setLastSyncDateForData(System.currentTimeMillis());
  211. mStorageManager.saveFile(mLocalFolder);
  212. }
  213. if (!mSyncFullAccount) {
  214. sendLocalBroadcast(
  215. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result
  216. );
  217. }
  218. if (result.isSuccess() && !mSyncFullAccount && !mOnlyFileMetadata) {
  219. refreshSharesForFolder(client); // share result is ignored
  220. }
  221. if (!mSyncFullAccount) {
  222. sendLocalBroadcast(
  223. EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result
  224. );
  225. }
  226. return result;
  227. }
  228. private void updateOCVersion(OwnCloudClient client) {
  229. UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
  230. RemoteOperationResult result = update.execute(client);
  231. if (result.isSuccess()) {
  232. // Update Capabilities for this account
  233. updateCapabilities();
  234. }
  235. }
  236. private void updateUserProfile() {
  237. GetUserProfileOperation update = new GetUserProfileOperation();
  238. RemoteOperationResult result = update.execute(mStorageManager, mContext);
  239. if (!result.isSuccess()) {
  240. Log_OC.w(TAG, "Couldn't update user profile from server");
  241. } else {
  242. Log_OC.i(TAG, "Got display name: " + result.getData().get(0));
  243. }
  244. }
  245. private void updateCapabilities() {
  246. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(mContext.getContentResolver());
  247. String oldDirectEditingEtag = arbitraryDataProvider.getValue(mAccount,
  248. ArbitraryDataProvider.DIRECT_EDITING_ETAG);
  249. GetCapabilitiesOperation getCapabilities = new GetCapabilitiesOperation();
  250. RemoteOperationResult result = getCapabilities.execute(mStorageManager, mContext);
  251. if (result.isSuccess()) {
  252. String newDirectEditingEtag = mStorageManager.getCapability(mAccount.name).getDirectEditingEtag();
  253. if (!oldDirectEditingEtag.equalsIgnoreCase(newDirectEditingEtag)) {
  254. updateDirectEditing(arbitraryDataProvider, newDirectEditingEtag);
  255. }
  256. updatePredefinedStatus(arbitraryDataProvider);
  257. } else {
  258. Log_OC.w(TAG, "Update Capabilities unsuccessfully");
  259. }
  260. }
  261. private void updateDirectEditing(ArbitraryDataProvider arbitraryDataProvider, String newDirectEditingEtag) {
  262. RemoteOperationResult result = new DirectEditingObtainRemoteOperation().execute(mAccount, mContext);
  263. if (result.isSuccess()) {
  264. DirectEditing directEditing = (DirectEditing) result.getSingleData();
  265. String json = new Gson().toJson(directEditing);
  266. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name, ArbitraryDataProvider.DIRECT_EDITING, json);
  267. } else {
  268. arbitraryDataProvider.deleteKeyForAccount(mAccount.name, ArbitraryDataProvider.DIRECT_EDITING);
  269. }
  270. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name,
  271. ArbitraryDataProvider.DIRECT_EDITING_ETAG,
  272. newDirectEditingEtag);
  273. }
  274. private void updatePredefinedStatus(ArbitraryDataProvider arbitraryDataProvider) {
  275. NextcloudClient client;
  276. try {
  277. client = OwnCloudClientFactory.createNextcloudClient(mAccount, mContext);
  278. } catch (AccountUtils.AccountNotFoundException e) {
  279. Log_OC.e(this, "Update of predefined status not possible!");
  280. return;
  281. }
  282. RemoteOperationResult result = new GetPredefinedStatusesRemoteOperation().execute(client);
  283. if (result.isSuccess()) {
  284. ArrayList<PredefinedStatus> predefinedStatuses = (ArrayList<PredefinedStatus>) result.getSingleData();
  285. String json = new Gson().toJson(predefinedStatuses);
  286. arbitraryDataProvider.storeOrUpdateKeyValue(mAccount.name, ArbitraryDataProvider.PREDEFINED_STATUS, json);
  287. } else {
  288. arbitraryDataProvider.deleteKeyForAccount(mAccount.name, ArbitraryDataProvider.PREDEFINED_STATUS);
  289. }
  290. }
  291. private RemoteOperationResult checkForChanges(OwnCloudClient client) {
  292. mRemoteFolderChanged = true;
  293. RemoteOperationResult result;
  294. String remotePath = mLocalFolder.getRemotePath();
  295. Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
  296. // remote request
  297. result = new ReadFileRemoteOperation(remotePath).execute(client);
  298. if (result.isSuccess()) {
  299. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  300. if (!mIgnoreETag) {
  301. // check if remote and local folder are different
  302. String remoteFolderETag = remoteFolder.getEtag();
  303. if (remoteFolderETag != null) {
  304. mRemoteFolderChanged =
  305. !(remoteFolderETag.equalsIgnoreCase(mLocalFolder.getEtag()));
  306. } else {
  307. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  308. "No ETag received from server");
  309. }
  310. }
  311. result = new RemoteOperationResult(ResultCode.OK);
  312. Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
  313. (mRemoteFolderChanged ? "changed" : "not changed"));
  314. } else {
  315. // check failed
  316. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  317. removeLocalFolder();
  318. }
  319. if (result.isException()) {
  320. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  321. result.getLogMessage(), result.getException());
  322. } else {
  323. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  324. result.getLogMessage());
  325. }
  326. }
  327. return result;
  328. }
  329. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
  330. String remotePath = mLocalFolder.getRemotePath();
  331. RemoteOperationResult result = new ReadFolderRemoteOperation(remotePath).execute(client);
  332. Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
  333. if (result.isSuccess()) {
  334. synchronizeData(result.getData());
  335. if (mConflictsFound > 0 || mFailsInKeptInSyncFound > 0) {
  336. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  337. // should be a different result code, but will do the job
  338. }
  339. } else {
  340. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  341. removeLocalFolder();
  342. }
  343. }
  344. return result;
  345. }
  346. private void removeLocalFolder() {
  347. if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
  348. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  349. mStorageManager.removeFolder(
  350. mLocalFolder,
  351. true,
  352. mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)
  353. );
  354. }
  355. }
  356. /**
  357. * Synchronizes the data retrieved from the server about the contents of the target folder
  358. * with the current data in the local database.
  359. *
  360. * Grants that mChildren is updated with fresh data after execution.
  361. *
  362. * @param folderAndFiles Remote folder and children files in Folder
  363. */
  364. private void synchronizeData(List<Object> folderAndFiles) {
  365. // get 'fresh data' from the database
  366. mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
  367. // parse data from remote folder
  368. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  369. remoteFolder.setParentId(mLocalFolder.getParentId());
  370. remoteFolder.setFileId(mLocalFolder.getFileId());
  371. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
  372. List<OCFile> updatedFiles = new ArrayList<>(folderAndFiles.size() - 1);
  373. mFilesToSyncContents.clear();
  374. // if local folder is encrypted, download fresh metadata
  375. boolean encryptedAncestor = FileStorageUtils.checkEncryptionStatus(mLocalFolder, mStorageManager);
  376. mLocalFolder.setEncrypted(encryptedAncestor);
  377. // update permission
  378. mLocalFolder.setPermissions(remoteFolder.getPermissions());
  379. // update richWorkspace
  380. mLocalFolder.setRichWorkspace(remoteFolder.getRichWorkspace());
  381. DecryptedFolderMetadata metadata = getDecryptedFolderMetadata(encryptedAncestor,
  382. mLocalFolder,
  383. getClient(),
  384. mAccount,
  385. mContext);
  386. // get current data about local contents of the folder to synchronize
  387. Map<String, OCFile> localFilesMap = prefillLocalFilesMap(metadata,
  388. mStorageManager.getFolderContent(mLocalFolder, false));
  389. // loop to update every child
  390. OCFile remoteFile;
  391. OCFile localFile;
  392. OCFile updatedFile;
  393. RemoteFile remote;
  394. for (int i = 1; i < folderAndFiles.size(); i++) {
  395. /// new OCFile instance with the data from the server
  396. remote = (RemoteFile) folderAndFiles.get(i);
  397. remoteFile = FileStorageUtils.fillOCFile(remote);
  398. // new OCFile instance to merge fresh data from server with local state
  399. updatedFile = FileStorageUtils.fillOCFile(remote);
  400. updatedFile.setParentId(mLocalFolder.getFileId());
  401. // retrieve local data for the read file
  402. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  403. // TODO better implementation is needed
  404. if (localFile == null) {
  405. localFile = mStorageManager.getFileByPath(updatedFile.getRemotePath());
  406. }
  407. // add to updatedFile data about LOCAL STATE (not existing in server)
  408. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  409. // add to updatedFile data from local and remote file
  410. setLocalFileDataOnUpdatedFile(remoteFile, localFile, updatedFile, mRemoteFolderChanged);
  411. // check and fix, if needed, local storage path
  412. FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, mAccount);
  413. // update file name for encrypted files
  414. if (metadata != null) {
  415. updateFileNameForEncryptedFile(mStorageManager, metadata, updatedFile);
  416. }
  417. // we parse content, so either the folder itself or its direct parent (which we check) must be encrypted
  418. boolean encrypted = updatedFile.isEncrypted() || mLocalFolder.isEncrypted();
  419. updatedFile.setEncrypted(encrypted);
  420. updatedFiles.add(updatedFile);
  421. }
  422. // save updated contents in local database
  423. // update file name for encrypted files
  424. if (metadata != null) {
  425. updateFileNameForEncryptedFile(mStorageManager, metadata, mLocalFolder);
  426. }
  427. mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  428. mChildren = updatedFiles;
  429. }
  430. @Nullable
  431. public static DecryptedFolderMetadata getDecryptedFolderMetadata(boolean encryptedAncestor,
  432. OCFile localFolder,
  433. OwnCloudClient client,
  434. Account account,
  435. Context context) {
  436. DecryptedFolderMetadata metadata;
  437. if (encryptedAncestor) {
  438. metadata = EncryptionUtils.downloadFolderMetadata(localFolder, client, context, account);
  439. } else {
  440. metadata = null;
  441. }
  442. return metadata;
  443. }
  444. public static void updateFileNameForEncryptedFile(FileDataStorageManager storageManager,
  445. @NonNull DecryptedFolderMetadata metadata,
  446. OCFile updatedFile) {
  447. try {
  448. String decryptedFileName = metadata.getFiles().get(updatedFile.getFileName()).getEncrypted()
  449. .getFilename();
  450. String mimetype = metadata.getFiles().get(updatedFile.getFileName()).getEncrypted().getMimetype();
  451. OCFile parentFile = storageManager.getFileById(updatedFile.getParentId());
  452. String decryptedRemotePath = parentFile.getDecryptedRemotePath() + decryptedFileName;
  453. if (updatedFile.isFolder()) {
  454. decryptedRemotePath += "/";
  455. }
  456. updatedFile.setDecryptedRemotePath(decryptedRemotePath);
  457. if (mimetype == null || mimetype.isEmpty()) {
  458. if (updatedFile.isFolder()) {
  459. updatedFile.setMimeType(MimeType.DIRECTORY);
  460. } else {
  461. updatedFile.setMimeType("application/octet-stream");
  462. }
  463. } else {
  464. updatedFile.setMimeType(mimetype);
  465. }
  466. } catch (NullPointerException e) {
  467. Log_OC.e(TAG, "Metadata for file " + updatedFile.getFileId() + " not found!");
  468. }
  469. }
  470. private void setLocalFileDataOnUpdatedFile(OCFile remoteFile, OCFile localFile, OCFile updatedFile, boolean remoteFolderChanged) {
  471. if (localFile != null) {
  472. updatedFile.setFileId(localFile.getFileId());
  473. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  474. updatedFile.setModificationTimestampAtLastSyncForData(
  475. localFile.getModificationTimestampAtLastSyncForData()
  476. );
  477. if (localFile.isEncrypted()) {
  478. if (mLocalFolder.getStoragePath() == null) {
  479. updatedFile.setStoragePath(FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder) +
  480. localFile.getFileName());
  481. } else {
  482. updatedFile.setStoragePath(mLocalFolder.getStoragePath() +
  483. PATH_SEPARATOR +
  484. localFile.getFileName());
  485. }
  486. } else {
  487. updatedFile.setStoragePath(localFile.getStoragePath());
  488. }
  489. // eTag will not be updated unless file CONTENTS are synchronized
  490. if (!updatedFile.isFolder() && localFile.isDown() &&
  491. !updatedFile.getEtag().equals(localFile.getEtag())) {
  492. updatedFile.setEtagInConflict(updatedFile.getEtag());
  493. }
  494. updatedFile.setEtag(localFile.getEtag());
  495. if (updatedFile.isFolder()) {
  496. updatedFile.setFileLength(remoteFile.getFileLength());
  497. updatedFile.setMountType(remoteFile.getMountType());
  498. } else if (remoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
  499. remoteFile.getModificationTimestamp() !=
  500. localFile.getModificationTimestamp()) {
  501. updatedFile.setUpdateThumbnailNeeded(true);
  502. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  503. }
  504. updatedFile.setSharedViaLink(localFile.isSharedViaLink());
  505. updatedFile.setSharedWithSharee(localFile.isSharedWithSharee());
  506. } else {
  507. // remote eTag will not be updated unless file CONTENTS are synchronized
  508. updatedFile.setEtag("");
  509. }
  510. // eTag on Server is used for thumbnail validation
  511. updatedFile.setEtagOnServer(remoteFile.getEtag());
  512. }
  513. @NonNull
  514. public static Map<String, OCFile> prefillLocalFilesMap(DecryptedFolderMetadata metadata, List<OCFile> localFiles) {
  515. Map<String, OCFile> localFilesMap = new HashMap<>(localFiles.size());
  516. for (OCFile file : localFiles) {
  517. String remotePath = file.getRemotePath();
  518. if (metadata != null) {
  519. remotePath = file.getParentRemotePath() + file.getEncryptedFileName();
  520. if (file.isFolder() && !remotePath.endsWith(PATH_SEPARATOR)) {
  521. remotePath = remotePath + PATH_SEPARATOR;
  522. }
  523. }
  524. localFilesMap.put(remotePath, file);
  525. }
  526. return localFilesMap;
  527. }
  528. /**
  529. * Performs a list of synchronization operations, determining if a download or upload is needed
  530. * or if exists conflict due to changes both in local and remote contents of the each file.
  531. *
  532. * If download or upload is needed, request the operation to the corresponding service and goes
  533. * on.
  534. *
  535. * @param filesToSyncContents Synchronization operations to execute.
  536. */
  537. private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents) {
  538. RemoteOperationResult contentsResult;
  539. for (SynchronizeFileOperation op : filesToSyncContents) {
  540. contentsResult = op.execute(mStorageManager, mContext); // async
  541. if (!contentsResult.isSuccess()) {
  542. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  543. mConflictsFound++;
  544. } else {
  545. mFailsInKeptInSyncFound++;
  546. if (contentsResult.getException() != null) {
  547. Log_OC.e(TAG, "Error while synchronizing favourites : "
  548. + contentsResult.getLogMessage(), contentsResult.getException());
  549. } else {
  550. Log_OC.e(TAG, "Error while synchronizing favourites : "
  551. + contentsResult.getLogMessage());
  552. }
  553. }
  554. } // won't let these fails break the synchronization process
  555. }
  556. }
  557. /**
  558. * Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
  559. *
  560. * @param client Handler of a session with an OC server.
  561. * @return The result of the remote operation retrieving the Share resources in the folder refreshed by
  562. * the operation.
  563. */
  564. private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
  565. RemoteOperationResult result;
  566. // remote request
  567. GetSharesForFileRemoteOperation operation =
  568. new GetSharesForFileRemoteOperation(mLocalFolder.getRemotePath(), true, true);
  569. result = operation.execute(client);
  570. if (result.isSuccess()) {
  571. // update local database
  572. ArrayList<OCShare> shares = new ArrayList<>();
  573. OCShare share;
  574. for (Object obj : result.getData()) {
  575. share = (OCShare) obj;
  576. if (!ShareType.NO_SHARED.equals(share.getShareType())) {
  577. shares.add(share);
  578. }
  579. }
  580. mStorageManager.saveSharesInFolder(shares, mLocalFolder);
  581. }
  582. return result;
  583. }
  584. /**
  585. * Sends a message to any application component interested in the progress
  586. * of the synchronization.
  587. *
  588. * @param event broadcast event (Intent Action)
  589. * @param dirRemotePath Remote path of a folder that was just synchronized
  590. * (with or without success)
  591. * @param result remote operation result
  592. */
  593. private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
  594. Log_OC.d(TAG, "Send broadcast " + event);
  595. Intent intent = new Intent(event);
  596. intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
  597. if (dirRemotePath != null) {
  598. intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
  599. }
  600. DataHolderUtil dataHolderUtil = DataHolderUtil.getInstance();
  601. String dataHolderItemId = dataHolderUtil.nextItemId();
  602. dataHolderUtil.save(dataHolderItemId, result);
  603. intent.putExtra(FileSyncAdapter.EXTRA_RESULT, dataHolderItemId);
  604. intent.setPackage(mContext.getPackageName());
  605. LocalBroadcastManager.getInstance(mContext.getApplicationContext()).sendBroadcast(intent);
  606. }
  607. }