RefreshFolderOperation.java 31 KB

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