RefreshFolderOperation.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. // Update Capabilities for this account
  191. if (update.getOCVersion().isVersionWithCapabilitiesAPI()) {
  192. updateCapabilities(client);
  193. } else {
  194. Log_OC.d(TAG, "Capabilities API disabled");
  195. }
  196. }
  197. }
  198. private void updateCapabilities(OwnCloudClient client){
  199. GetCapabilitiesOperarion getCapabilities = new GetCapabilitiesOperarion();
  200. RemoteOperationResult result = getCapabilities.execute(mStorageManager,mContext);
  201. if (!result.isSuccess()){
  202. Log_OC.w(TAG, "Update Capabilities unsuccessfully");
  203. }
  204. }
  205. private RemoteOperationResult checkForChanges(OwnCloudClient client) {
  206. mRemoteFolderChanged = true;
  207. RemoteOperationResult result = null;
  208. String remotePath = mLocalFolder.getRemotePath();
  209. Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
  210. // remote request
  211. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
  212. result = operation.execute(client);
  213. if (result.isSuccess()){
  214. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  215. if (!mIgnoreETag) {
  216. // check if remote and local folder are different
  217. String remoteFolderETag = remoteFolder.getEtag();
  218. if (remoteFolderETag != null) {
  219. mRemoteFolderChanged =
  220. !(remoteFolderETag.equalsIgnoreCase(mLocalFolder.getEtag()));
  221. } else {
  222. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  223. "No ETag received from server");
  224. }
  225. }
  226. result = new RemoteOperationResult(ResultCode.OK);
  227. Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
  228. (mRemoteFolderChanged ? "changed" : "not changed"));
  229. } else {
  230. // check failed
  231. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  232. removeLocalFolder();
  233. }
  234. if (result.isException()) {
  235. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  236. result.getLogMessage(), result.getException());
  237. } else {
  238. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  239. result.getLogMessage());
  240. }
  241. }
  242. return result;
  243. }
  244. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
  245. String remotePath = mLocalFolder.getRemotePath();
  246. ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
  247. RemoteOperationResult result = operation.execute(client);
  248. Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
  249. if (result.isSuccess()) {
  250. synchronizeData(result.getData(), client);
  251. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  252. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  253. // should be a different result code, but will do the job
  254. }
  255. } else {
  256. if (result.getCode() == ResultCode.FILE_NOT_FOUND)
  257. removeLocalFolder();
  258. }
  259. return result;
  260. }
  261. private void removeLocalFolder() {
  262. if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
  263. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  264. mStorageManager.removeFolder(
  265. mLocalFolder,
  266. true,
  267. ( mLocalFolder.isDown() &&
  268. mLocalFolder.getStoragePath().startsWith(currentSavePath)
  269. )
  270. );
  271. }
  272. }
  273. /**
  274. * Synchronizes the data retrieved from the server about the contents of the target folder
  275. * with the current data in the local database.
  276. *
  277. * Grants that mChildren is updated with fresh data after execution.
  278. *
  279. * @param folderAndFiles Remote folder and children files in Folder
  280. *
  281. * @param client Client instance to the remote server where the data were
  282. * retrieved.
  283. * @return 'True' when any change was made in the local data, 'false' otherwise
  284. */
  285. private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
  286. // get 'fresh data' from the database
  287. mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
  288. // parse data from remote folder
  289. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  290. remoteFolder.setParentId(mLocalFolder.getParentId());
  291. remoteFolder.setFileId(mLocalFolder.getFileId());
  292. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
  293. + " changed - starting update of local data ");
  294. List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
  295. mFilesToSyncContents.clear();
  296. // get current data about local contents of the folder to synchronize
  297. // TODO Enable when "On Device" is recovered ?
  298. List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder/*, false*/);
  299. Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
  300. for (OCFile file : localFiles) {
  301. localFilesMap.put(file.getRemotePath(), file);
  302. }
  303. // loop to update every child
  304. OCFile remoteFile = null, localFile = null, updatedFile = null;
  305. RemoteFile r;
  306. for (int i=1; i<folderAndFiles.size(); i++) {
  307. /// new OCFile instance with the data from the server
  308. r = (RemoteFile) folderAndFiles.get(i);
  309. remoteFile = FileStorageUtils.fillOCFile(r);
  310. /// new OCFile instance to merge fresh data from server with local state
  311. updatedFile = FileStorageUtils.fillOCFile(r);
  312. updatedFile.setParentId(mLocalFolder.getFileId());
  313. /// retrieve local data for the read file
  314. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  315. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  316. /// add to updatedFile data about LOCAL STATE (not existing in server)
  317. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  318. if (localFile != null) {
  319. updatedFile.setFileId(localFile.getFileId());
  320. updatedFile.setFavorite(localFile.isFavorite());
  321. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  322. updatedFile.setModificationTimestampAtLastSyncForData(
  323. localFile.getModificationTimestampAtLastSyncForData()
  324. );
  325. updatedFile.setStoragePath(localFile.getStoragePath());
  326. // eTag will not be updated unless file CONTENTS are synchronized
  327. updatedFile.setEtag(localFile.getEtag());
  328. if (updatedFile.isFolder()) {
  329. updatedFile.setFileLength(localFile.getFileLength());
  330. // TODO move operations about size of folders to FileContentProvider
  331. } else if (mRemoteFolderChanged && remoteFile.isImage() &&
  332. remoteFile.getModificationTimestamp() !=
  333. localFile.getModificationTimestamp()) {
  334. updatedFile.setNeedsUpdateThumbnail(true);
  335. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  336. }
  337. updatedFile.setPublicLink(localFile.getPublicLink());
  338. updatedFile.setShareViaLink(localFile.isSharedViaLink());
  339. updatedFile.setShareWithSharee(localFile.isSharedWithSharee());
  340. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  341. } else {
  342. // remote eTag will not be updated unless file CONTENTS are synchronized
  343. updatedFile.setEtag("");
  344. }
  345. /// check and fix, if needed, local storage path
  346. FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, mAccount);
  347. /// prepare content synchronization for kept-in-sync files
  348. if (updatedFile.isFavorite()) {
  349. SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
  350. remoteFile,
  351. mAccount,
  352. true,
  353. mContext
  354. );
  355. mFilesToSyncContents.add(operation);
  356. }
  357. updatedFiles.add(updatedFile);
  358. }
  359. // save updated contents in local database
  360. mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  361. mChildren = updatedFiles;
  362. }
  363. /**
  364. * Performs a list of synchronization operations, determining if a download or upload is needed
  365. * or if exists conflict due to changes both in local and remote contents of the each file.
  366. *
  367. * If download or upload is needed, request the operation to the corresponding service and goes
  368. * on.
  369. *
  370. * @param filesToSyncContents Synchronization operations to execute.
  371. * @param client Interface to the remote ownCloud server.
  372. */
  373. private void startContentSynchronizations(
  374. List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
  375. ) {
  376. RemoteOperationResult contentsResult = null;
  377. for (SynchronizeFileOperation op: filesToSyncContents) {
  378. contentsResult = op.execute(mStorageManager, mContext); // async
  379. if (!contentsResult.isSuccess()) {
  380. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  381. mConflictsFound++;
  382. } else {
  383. mFailsInFavouritesFound++;
  384. if (contentsResult.getException() != null) {
  385. Log_OC.e(TAG, "Error while synchronizing favourites : "
  386. + contentsResult.getLogMessage(), contentsResult.getException());
  387. } else {
  388. Log_OC.e(TAG, "Error while synchronizing favourites : "
  389. + contentsResult.getLogMessage());
  390. }
  391. }
  392. } // won't let these fails break the synchronization process
  393. }
  394. }
  395. /**
  396. * Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
  397. *
  398. * @param client Handler of a session with an OC server.
  399. * @return The result of the remote operation retrieving the Share resources in the folder refreshed by
  400. * the operation.
  401. */
  402. private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
  403. RemoteOperationResult result = null;
  404. // remote request
  405. GetRemoteSharesForFileOperation operation =
  406. new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), true, true);
  407. result = operation.execute(client);
  408. if (result.isSuccess()) {
  409. // update local database
  410. ArrayList<OCShare> shares = new ArrayList<OCShare>();
  411. for(Object obj: result.getData()) {
  412. shares.add((OCShare) obj);
  413. }
  414. mStorageManager.saveSharesInFolder(shares, mLocalFolder);
  415. }
  416. return result;
  417. }
  418. /**
  419. * Sends a message to any application component interested in the progress
  420. * of the synchronization.
  421. *
  422. * @param event
  423. * @param dirRemotePath Remote path of a folder that was just synchronized
  424. * (with or without success)
  425. * @param result
  426. */
  427. private void sendLocalBroadcast(
  428. String event, String dirRemotePath, RemoteOperationResult result
  429. ) {
  430. Log_OC.d(TAG, "Send broadcast " + event);
  431. Intent intent = new Intent(event);
  432. intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
  433. if (dirRemotePath != null) {
  434. intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
  435. }
  436. intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
  437. mContext.sendStickyBroadcast(intent);
  438. //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
  439. }
  440. private void fetchFavoritesToSyncFromLocalData() {
  441. List<OCFile> children = mStorageManager.getFolderContent(mLocalFolder);
  442. for (OCFile child : children) {
  443. if (!child.isFolder() && child.isFavorite() && !child.isInConflict()) {
  444. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  445. child,
  446. child, // cheating with the remote file to get an update to server; to refactor
  447. mAccount,
  448. true,
  449. mContext
  450. );
  451. mFilesToSyncContents.add(operation);
  452. }
  453. }
  454. }
  455. }