RefreshFolderOperation.java 30 KB

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