RefreshFolderOperation.java 22 KB

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