RefreshFolderOperation.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. */
  20. package com.owncloud.android.operations;
  21. import android.accounts.Account;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.util.Log;
  25. import com.owncloud.android.datamodel.FileDataStorageManager;
  26. import com.owncloud.android.datamodel.OCFile;
  27. import com.owncloud.android.lib.common.OwnCloudClient;
  28. import com.owncloud.android.lib.common.operations.RemoteOperation;
  29. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  30. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  31. import com.owncloud.android.lib.common.utils.Log_OC;
  32. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  33. import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
  34. import com.owncloud.android.lib.resources.files.RemoteFile;
  35. import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
  36. import com.owncloud.android.lib.resources.shares.OCShare;
  37. import com.owncloud.android.syncadapter.FileSyncAdapter;
  38. import com.owncloud.android.utils.DataHolderUtil;
  39. import com.owncloud.android.utils.FileStorageUtils;
  40. import com.owncloud.android.utils.MimeTypeUtil;
  41. import java.util.ArrayList;
  42. import java.util.HashMap;
  43. import java.util.List;
  44. import java.util.Map;
  45. import java.util.Vector;
  46. /**
  47. * Remote operation performing the synchronization of the list of files contained
  48. * in a folder identified with its remote path.
  49. *
  50. * Fetches the list and properties of the files contained in the given folder, including their
  51. * properties, and updates the local database with them.
  52. *
  53. * Does NOT enter in the child folders to synchronize their contents also.
  54. */
  55. @SuppressWarnings("PMD.AvoidDuplicateLiterals")
  56. public class RefreshFolderOperation extends RemoteOperation {
  57. private static final String TAG = RefreshFolderOperation.class.getSimpleName();
  58. public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED =
  59. RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
  60. public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
  61. RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
  62. /** Time stamp for the synchronization process in progress */
  63. private long mCurrentSyncTime;
  64. /** Remote folder to synchronize */
  65. private OCFile mLocalFolder;
  66. /** Access to the local database */
  67. private FileDataStorageManager mStorageManager;
  68. /** Account where the file to synchronize belongs */
  69. private Account mAccount;
  70. /** Android context; necessary to send requests to the download service */
  71. private Context mContext;
  72. /** Files and folders contained in the synchronized folder after a successful operation */
  73. private List<OCFile> mChildren;
  74. /** Counter of conflicts found between local and remote files */
  75. private int mConflictsFound;
  76. /** Counter of failed operations in synchronization of kept-in-sync files */
  77. private int mFailsInKeptInSyncFound;
  78. /**
  79. * Map of remote and local paths to files that where locally stored in a location
  80. * out of the ownCloud folder and couldn't be copied automatically into it
  81. **/
  82. private Map<String, String> mForgottenLocalFiles;
  83. /** 'True' means that this operation is part of a full account synchronization */
  84. private boolean mSyncFullAccount;
  85. /** 'True' means that Share resources bound to the files into should be refreshed also */
  86. private boolean mIsShareSupported;
  87. /** 'True' means that the remote folder changed and should be fetched */
  88. private boolean mRemoteFolderChanged;
  89. /** 'True' means that Etag will be ignored */
  90. private boolean mIgnoreETag;
  91. private List<SynchronizeFileOperation> mFilesToSyncContents;
  92. // this will be used for every file when 'folder synchronization' replaces 'folder download'
  93. /**
  94. * Creates a new instance of {@link RefreshFolderOperation}.
  95. *
  96. * @param folder Folder to synchronize.
  97. * @param currentSyncTime Time stamp for the synchronization process in progress.
  98. * @param syncFullAccount 'True' means that this operation is part of a full account
  99. * synchronization.
  100. * @param isShareSupported 'True' means that the server supports the sharing API.
  101. * @param ignoreETag 'True' means that the content of the remote folder should
  102. * be fetched and updated even though the 'eTag' did not
  103. * change.
  104. * @param dataStorageManager Interface with the local database.
  105. * @param account ownCloud account where the folder is located.
  106. * @param context Application context.
  107. */
  108. public RefreshFolderOperation(OCFile folder,
  109. long currentSyncTime,
  110. boolean syncFullAccount,
  111. boolean isShareSupported,
  112. boolean ignoreETag,
  113. FileDataStorageManager dataStorageManager,
  114. Account account,
  115. Context context) {
  116. mLocalFolder = folder;
  117. mCurrentSyncTime = currentSyncTime;
  118. mSyncFullAccount = syncFullAccount;
  119. mIsShareSupported = isShareSupported;
  120. mStorageManager = dataStorageManager;
  121. mAccount = account;
  122. mContext = context;
  123. mForgottenLocalFiles = new HashMap<String, String>();
  124. mRemoteFolderChanged = false;
  125. mIgnoreETag = ignoreETag;
  126. mFilesToSyncContents = new Vector<SynchronizeFileOperation>();
  127. }
  128. public int getConflictsFound() {
  129. return mConflictsFound;
  130. }
  131. public int getFailsInKeptInSyncFound() {
  132. return mFailsInKeptInSyncFound;
  133. }
  134. public Map<String, String> getForgottenLocalFiles() {
  135. return mForgottenLocalFiles;
  136. }
  137. /**
  138. * Returns the list of files and folders contained in the synchronized folder,
  139. * if called after synchronization is complete.
  140. *
  141. * @return List of files and folders contained in the synchronized folder.
  142. */
  143. public List<OCFile> getChildren() {
  144. return mChildren;
  145. }
  146. /**
  147. * Performs the synchronization.
  148. *
  149. * {@inheritDoc}
  150. */
  151. @Override
  152. protected RemoteOperationResult run(OwnCloudClient client) {
  153. RemoteOperationResult result = null;
  154. mFailsInKeptInSyncFound = 0;
  155. mConflictsFound = 0;
  156. mForgottenLocalFiles.clear();
  157. if (OCFile.ROOT_PATH.equals(mLocalFolder.getRemotePath()) && !mSyncFullAccount) {
  158. updateOCVersion(client);
  159. updateUserProfile();
  160. }
  161. result = checkForChanges(client);
  162. if (result.isSuccess()) {
  163. if (mRemoteFolderChanged) {
  164. result = fetchAndSyncRemoteFolder(client);
  165. } else {
  166. fetchKeptInSyncFilesToSyncFromLocalData();
  167. mChildren = mStorageManager.getFolderContent(mLocalFolder, false);
  168. }
  169. if (result.isSuccess()) {
  170. // request for the synchronization of KEPT-IN-SYNC file contents
  171. startContentSynchronizations(mFilesToSyncContents, client);
  172. }
  173. }
  174. if (!mSyncFullAccount) {
  175. sendLocalBroadcast(
  176. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result
  177. );
  178. }
  179. if (result.isSuccess() && mIsShareSupported && !mSyncFullAccount) {
  180. refreshSharesForFolder(client); // share result is ignored
  181. }
  182. if (!mSyncFullAccount) {
  183. sendLocalBroadcast(
  184. EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result
  185. );
  186. }
  187. return result;
  188. }
  189. private void updateOCVersion(OwnCloudClient client) {
  190. UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
  191. RemoteOperationResult result = update.execute(client);
  192. if (result.isSuccess()) {
  193. mIsShareSupported = update.getOCVersion().isSharedSupported();
  194. // Update Capabilities for this account
  195. if (update.getOCVersion().isVersionWithCapabilitiesAPI()) {
  196. updateCapabilities();
  197. } else {
  198. Log_OC.d(TAG, "Capabilities API disabled");
  199. }
  200. }
  201. }
  202. private void updateUserProfile() {
  203. GetUserProfileOperation update = new GetUserProfileOperation();
  204. RemoteOperationResult result = update.execute(mStorageManager, mContext);
  205. if (!result.isSuccess()) {
  206. Log_OC.w(TAG, "Couldn't update user profile from server");
  207. } else {
  208. Log_OC.i(TAG, "Got display name: " + result.getData().get(0));
  209. }
  210. }
  211. private void updateCapabilities(){
  212. GetCapabilitiesOperarion getCapabilities = new GetCapabilitiesOperarion();
  213. RemoteOperationResult result = getCapabilities.execute(mStorageManager,mContext);
  214. if (!result.isSuccess()){
  215. Log_OC.w(TAG, "Update Capabilities unsuccessfully");
  216. }
  217. }
  218. private RemoteOperationResult checkForChanges(OwnCloudClient client) {
  219. mRemoteFolderChanged = true;
  220. RemoteOperationResult result = null;
  221. String remotePath = mLocalFolder.getRemotePath();
  222. Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
  223. // remote request
  224. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
  225. result = operation.execute(client);
  226. if (result.isSuccess()){
  227. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  228. if (!mIgnoreETag) {
  229. // check if remote and local folder are different
  230. String remoteFolderETag = remoteFolder.getEtag();
  231. if (remoteFolderETag != null) {
  232. mRemoteFolderChanged =
  233. !(remoteFolderETag.equalsIgnoreCase(mLocalFolder.getEtag()));
  234. } else {
  235. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  236. "No ETag received from server");
  237. }
  238. }
  239. result = new RemoteOperationResult(ResultCode.OK);
  240. Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
  241. (mRemoteFolderChanged ? "changed" : "not changed"));
  242. } else {
  243. // check failed
  244. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  245. removeLocalFolder();
  246. }
  247. if (result.isException()) {
  248. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  249. result.getLogMessage(), result.getException());
  250. } else {
  251. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  252. result.getLogMessage());
  253. }
  254. }
  255. return result;
  256. }
  257. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
  258. String remotePath = mLocalFolder.getRemotePath();
  259. ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
  260. RemoteOperationResult result = operation.execute(client);
  261. Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
  262. if (result.isSuccess()) {
  263. synchronizeData(result.getData());
  264. if (mConflictsFound > 0 || mFailsInKeptInSyncFound > 0) {
  265. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  266. // should be a different result code, but will do the job
  267. }
  268. } else {
  269. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  270. removeLocalFolder();
  271. }
  272. }
  273. return result;
  274. }
  275. private void removeLocalFolder() {
  276. if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
  277. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  278. mStorageManager.removeFolder(
  279. mLocalFolder,
  280. true,
  281. ( mLocalFolder.isDown() &&
  282. mLocalFolder.getStoragePath().startsWith(currentSavePath)
  283. )
  284. );
  285. }
  286. }
  287. /**
  288. * Synchronizes the data retrieved from the server about the contents of the target folder
  289. * with the current data in the local database.
  290. *
  291. * Grants that mChildren is updated with fresh data after execution.
  292. *
  293. * @param folderAndFiles Remote folder and children files in Folder
  294. */
  295. private void synchronizeData(ArrayList<Object> folderAndFiles) {
  296. // get 'fresh data' from the database
  297. mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
  298. // parse data from remote folder
  299. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  300. remoteFolder.setParentId(mLocalFolder.getParentId());
  301. remoteFolder.setFileId(mLocalFolder.getFileId());
  302. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
  303. + " changed - starting update of local data ");
  304. List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
  305. mFilesToSyncContents.clear();
  306. // get current data about local contents of the folder to synchronize
  307. List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder, false);
  308. Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
  309. for (OCFile file : localFiles) {
  310. localFilesMap.put(file.getRemotePath(), file);
  311. }
  312. // loop to update every child
  313. OCFile remoteFile = null, localFile = null, updatedFile = null;
  314. RemoteFile r;
  315. for (int i=1; i<folderAndFiles.size(); i++) {
  316. /// new OCFile instance with the data from the server
  317. r = (RemoteFile) folderAndFiles.get(i);
  318. remoteFile = FileStorageUtils.fillOCFile(r);
  319. /// new OCFile instance to merge fresh data from server with local state
  320. updatedFile = FileStorageUtils.fillOCFile(r);
  321. updatedFile.setParentId(mLocalFolder.getFileId());
  322. /// retrieve local data for the read file
  323. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  324. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  325. /// add to updatedFile data about LOCAL STATE (not existing in server)
  326. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  327. if (localFile != null) {
  328. updatedFile.setFileId(localFile.getFileId());
  329. updatedFile.setAvailableOffline(localFile.isAvailableOffline());
  330. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  331. updatedFile.setModificationTimestampAtLastSyncForData(
  332. localFile.getModificationTimestampAtLastSyncForData()
  333. );
  334. updatedFile.setStoragePath(localFile.getStoragePath());
  335. // eTag will not be updated unless file CONTENTS are synchronized
  336. updatedFile.setEtag(localFile.getEtag());
  337. if (updatedFile.isFolder()) {
  338. updatedFile.setFileLength(remoteFile.getFileLength());
  339. } else if (mRemoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
  340. remoteFile.getModificationTimestamp() !=
  341. localFile.getModificationTimestamp()) {
  342. updatedFile.setNeedsUpdateThumbnail(true);
  343. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  344. }
  345. updatedFile.setPublicLink(localFile.getPublicLink());
  346. updatedFile.setShareViaLink(localFile.isSharedViaLink());
  347. updatedFile.setShareWithSharee(localFile.isSharedWithSharee());
  348. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  349. updatedFile.setFavorite(localFile.getIsFavorite());
  350. } else {
  351. // remote eTag will not be updated unless file CONTENTS are synchronized
  352. updatedFile.setEtag("");
  353. }
  354. /// check and fix, if needed, local storage path
  355. FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, mAccount);
  356. /// prepare content synchronization for kept-in-sync files
  357. if (updatedFile.isAvailableOffline()) {
  358. SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
  359. remoteFile,
  360. mAccount,
  361. true,
  362. mContext
  363. );
  364. mFilesToSyncContents.add(operation);
  365. }
  366. updatedFiles.add(updatedFile);
  367. }
  368. // save updated contents in local database
  369. mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  370. mChildren = updatedFiles;
  371. }
  372. /**
  373. * Performs a list of synchronization operations, determining if a download or upload is needed
  374. * or if exists conflict due to changes both in local and remote contents of the each file.
  375. *
  376. * If download or upload is needed, request the operation to the corresponding service and goes
  377. * on.
  378. *
  379. * @param filesToSyncContents Synchronization operations to execute.
  380. * @param client Interface to the remote ownCloud server.
  381. */
  382. private void startContentSynchronizations(
  383. List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
  384. ) {
  385. RemoteOperationResult contentsResult = null;
  386. for (SynchronizeFileOperation op: filesToSyncContents) {
  387. contentsResult = op.execute(mStorageManager, mContext); // async
  388. if (!contentsResult.isSuccess()) {
  389. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  390. mConflictsFound++;
  391. } else {
  392. mFailsInKeptInSyncFound++;
  393. if (contentsResult.getException() != null) {
  394. Log_OC.e(TAG, "Error while synchronizing favourites : "
  395. + contentsResult.getLogMessage(), contentsResult.getException());
  396. } else {
  397. Log_OC.e(TAG, "Error while synchronizing favourites : "
  398. + contentsResult.getLogMessage());
  399. }
  400. }
  401. } // won't let these fails break the synchronization process
  402. }
  403. }
  404. /**
  405. * Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
  406. *
  407. * @param client Handler of a session with an OC server.
  408. * @return The result of the remote operation retrieving the Share resources in the folder refreshed by
  409. * the operation.
  410. */
  411. private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
  412. RemoteOperationResult result = null;
  413. // remote request
  414. GetRemoteSharesForFileOperation operation =
  415. new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), true, true);
  416. result = operation.execute(client);
  417. if (result.isSuccess()) {
  418. // update local database
  419. ArrayList<OCShare> shares = new ArrayList<OCShare>();
  420. for(Object obj: result.getData()) {
  421. shares.add((OCShare) obj);
  422. }
  423. mStorageManager.saveSharesInFolder(shares, mLocalFolder);
  424. }
  425. return result;
  426. }
  427. /**
  428. * Sends a message to any application component interested in the progress
  429. * of the synchronization.
  430. *
  431. * @param event
  432. * @param dirRemotePath Remote path of a folder that was just synchronized
  433. * (with or without success)
  434. * @param result
  435. */
  436. private void sendLocalBroadcast(
  437. String event, String dirRemotePath, RemoteOperationResult result
  438. ) {
  439. Log_OC.d(TAG, "Send broadcast " + event);
  440. Intent intent = new Intent(event);
  441. intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
  442. if (dirRemotePath != null) {
  443. intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
  444. }
  445. DataHolderUtil dataHolderUtil = DataHolderUtil.getInstance();
  446. String dataHolderItemId = dataHolderUtil.nextItemId();
  447. dataHolderUtil.save(dataHolderItemId, result);
  448. intent.putExtra(FileSyncAdapter.EXTRA_RESULT, dataHolderItemId);
  449. intent.setPackage(mContext.getPackageName());
  450. mContext.sendStickyBroadcast(intent);
  451. //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
  452. }
  453. private void fetchKeptInSyncFilesToSyncFromLocalData() {
  454. List<OCFile> children = mStorageManager.getFolderContent(mLocalFolder, false);
  455. for (OCFile child : children) {
  456. if (!child.isFolder() && child.isAvailableOffline() && !child.isInConflict()) {
  457. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  458. child,
  459. child, // cheating with the remote file to get an update to server; to refactor
  460. mAccount,
  461. true,
  462. mContext
  463. );
  464. mFilesToSyncContents.add(operation);
  465. }
  466. }
  467. }
  468. }