RefreshFolderOperation.java 27 KB

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