SynchronizeFolderOperation.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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.io.File;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Vector;
  27. import android.accounts.Account;
  28. import android.content.Context;
  29. import android.content.Intent;
  30. import android.util.Log;
  31. import com.owncloud.android.datamodel.FileDataStorageManager;
  32. import com.owncloud.android.datamodel.OCFile;
  33. import com.owncloud.android.files.services.FileDownloader;
  34. import com.owncloud.android.lib.common.OwnCloudClient;
  35. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  36. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  37. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  38. import com.owncloud.android.lib.common.utils.Log_OC;
  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.operations.common.SyncOperation;
  43. import com.owncloud.android.services.OperationsService;
  44. import com.owncloud.android.utils.FileStorageUtils;
  45. import java.util.concurrent.atomic.AtomicBoolean;
  46. //import android.support.v4.content.LocalBroadcastManager;
  47. /**
  48. * Remote operation performing the synchronization of the list of files contained
  49. * in a folder identified with its remote path.
  50. *
  51. * Fetches the list and properties of the files contained in the given folder, including their
  52. * properties, and updates the local database with them.
  53. *
  54. * Does NOT enter in the child folders to synchronize their contents also, BUT requests for a new operation instance
  55. * doing so.
  56. */
  57. public class SynchronizeFolderOperation extends SyncOperation {
  58. private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
  59. /** Time stamp for the synchronization process in progress */
  60. private long mCurrentSyncTime;
  61. /** Remote path of the folder to synchronize */
  62. private String mRemotePath;
  63. /** Account where the file to synchronize belongs */
  64. private Account mAccount;
  65. /** Android context; necessary to send requests to the download service */
  66. private Context mContext;
  67. /** Locally cached information about folder to synchronize */
  68. private OCFile mLocalFolder;
  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 mFailsInFileSyncsFound;
  75. /** 'True' means that the remote folder changed and should be fetched */
  76. private boolean mRemoteFolderChanged;
  77. private List<OCFile> mFilesForDirectDownload;
  78. // to avoid extra PROPFINDs when there was no change in the folder
  79. private List<SyncOperation> mFilesToSyncContents;
  80. // this will be used for every file when 'folder synchronization' replaces 'folder download'
  81. private final AtomicBoolean mCancellationRequested;
  82. /**
  83. * Creates a new instance of {@link SynchronizeFolderOperation}.
  84. *
  85. * @param context Application context.
  86. * @param remotePath Path to synchronize.
  87. * @param account ownCloud account where the folder is located.
  88. * @param currentSyncTime Time stamp for the synchronization process in progress.
  89. */
  90. public SynchronizeFolderOperation(Context context, String remotePath, Account account,
  91. long currentSyncTime){
  92. mRemotePath = remotePath;
  93. mCurrentSyncTime = currentSyncTime;
  94. mAccount = account;
  95. mContext = context;
  96. mRemoteFolderChanged = false;
  97. mFilesForDirectDownload = new Vector<OCFile>();
  98. mFilesToSyncContents = new Vector<SyncOperation>();
  99. mCancellationRequested = new AtomicBoolean(false);
  100. }
  101. public int getConflictsFound() {
  102. return mConflictsFound;
  103. }
  104. public int getFailsInFileSyncsFound() {
  105. return mFailsInFileSyncsFound;
  106. }
  107. /**
  108. * Performs the synchronization.
  109. *
  110. * {@inheritDoc}
  111. */
  112. @Override
  113. protected RemoteOperationResult run(OwnCloudClient client) {
  114. RemoteOperationResult result = null;
  115. mFailsInFileSyncsFound = 0;
  116. mConflictsFound = 0;
  117. try {
  118. // get locally cached information about folder
  119. mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
  120. result = checkForChanges(client);
  121. if (result.isSuccess()) {
  122. if (mRemoteFolderChanged) {
  123. result = fetchAndSyncRemoteFolder(client);
  124. } else {
  125. prepareOpsFromLocalKnowledge();
  126. }
  127. if (result.isSuccess()) {
  128. syncContents(client);
  129. }
  130. }
  131. if (mCancellationRequested.get()) {
  132. throw new OperationCancelledException();
  133. }
  134. } catch (OperationCancelledException e) {
  135. result = new RemoteOperationResult(e);
  136. }
  137. return result;
  138. }
  139. private RemoteOperationResult checkForChanges(OwnCloudClient client)
  140. throws OperationCancelledException {
  141. Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
  142. mRemoteFolderChanged = true;
  143. RemoteOperationResult result = null;
  144. if (mCancellationRequested.get()) {
  145. throw new OperationCancelledException();
  146. }
  147. // remote request
  148. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mRemotePath);
  149. result = operation.execute(client);
  150. if (result.isSuccess()){
  151. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  152. // check if remote and local folder are different
  153. mRemoteFolderChanged =
  154. !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
  155. result = new RemoteOperationResult(ResultCode.OK);
  156. Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  157. (mRemoteFolderChanged ? "changed" : "not changed"));
  158. } else {
  159. // check failed
  160. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  161. removeLocalFolder();
  162. }
  163. if (result.isException()) {
  164. Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  165. result.getLogMessage(), result.getException());
  166. } else {
  167. Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  168. result.getLogMessage());
  169. }
  170. }
  171. return result;
  172. }
  173. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client)
  174. throws OperationCancelledException {
  175. if (mCancellationRequested.get()) {
  176. throw new OperationCancelledException();
  177. }
  178. ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
  179. RemoteOperationResult result = operation.execute(client);
  180. Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
  181. if (result.isSuccess()) {
  182. synchronizeData(result.getData(), client);
  183. if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
  184. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  185. // should be a different result code, but will do the job
  186. }
  187. } else {
  188. if (result.getCode() == ResultCode.FILE_NOT_FOUND)
  189. removeLocalFolder();
  190. }
  191. return result;
  192. }
  193. private void removeLocalFolder() {
  194. FileDataStorageManager storageManager = getStorageManager();
  195. if (storageManager.fileExists(mLocalFolder.getFileId())) {
  196. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  197. storageManager.removeFolder(
  198. mLocalFolder,
  199. true,
  200. ( mLocalFolder.isDown() && // TODO: debug, I think this is
  201. // always false for folders
  202. mLocalFolder.getStoragePath().startsWith(currentSavePath)
  203. )
  204. );
  205. }
  206. }
  207. /**
  208. * Synchronizes the data retrieved from the server about the contents of the target folder
  209. * with the current data in the local database.
  210. *
  211. * Grants that mChildren is updated with fresh data after execution.
  212. *
  213. * @param folderAndFiles Remote folder and children files in Folder
  214. *
  215. * @param client Client instance to the remote server where the data were
  216. * retrieved.
  217. * @return 'True' when any change was made in the local data, 'false' otherwise
  218. */
  219. private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client)
  220. throws OperationCancelledException {
  221. FileDataStorageManager storageManager = getStorageManager();
  222. // parse data from remote folder
  223. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  224. remoteFolder.setParentId(mLocalFolder.getParentId());
  225. remoteFolder.setFileId(mLocalFolder.getFileId());
  226. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
  227. + " changed - starting update of local data ");
  228. List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
  229. mFilesForDirectDownload.clear();
  230. mFilesToSyncContents.clear();
  231. if (mCancellationRequested.get()) {
  232. throw new OperationCancelledException();
  233. }
  234. // get current data about local contents of the folder to synchronize
  235. // TODO Enable when "On Device" is recovered ?
  236. List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder/*, false*/);
  237. Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
  238. for (OCFile file : localFiles) {
  239. localFilesMap.put(file.getRemotePath(), file);
  240. }
  241. // loop to synchronize every child
  242. OCFile remoteFile = null, localFile = null, updatedFile = null;
  243. RemoteFile r;
  244. for (int i=1; i<folderAndFiles.size(); i++) {
  245. /// new OCFile instance with the data from the server
  246. r = (RemoteFile) folderAndFiles.get(i);
  247. remoteFile = FileStorageUtils.fillOCFile(r);
  248. /// new OCFile instance to merge fresh data from server with local state
  249. updatedFile = FileStorageUtils.fillOCFile(r);
  250. updatedFile.setParentId(mLocalFolder.getFileId());
  251. /// retrieve local data for the read file
  252. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  253. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  254. /// add to updatedFile data about LOCAL STATE (not existing in server)
  255. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  256. if (localFile != null) {
  257. updatedFile.setFileId(localFile.getFileId());
  258. updatedFile.setFavorite(localFile.isFavorite());
  259. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  260. updatedFile.setModificationTimestampAtLastSyncForData(
  261. localFile.getModificationTimestampAtLastSyncForData()
  262. );
  263. updatedFile.setStoragePath(localFile.getStoragePath());
  264. // eTag will not be updated unless file CONTENTS are synchronized
  265. updatedFile.setEtag(localFile.getEtag());
  266. if (updatedFile.isFolder()) {
  267. updatedFile.setFileLength(localFile.getFileLength());
  268. // TODO move operations about size of folders to FileContentProvider
  269. } else if (mRemoteFolderChanged && remoteFile.isImage() &&
  270. remoteFile.getModificationTimestamp() !=
  271. localFile.getModificationTimestamp()) {
  272. updatedFile.setNeedsUpdateThumbnail(true);
  273. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  274. }
  275. updatedFile.setPublicLink(localFile.getPublicLink());
  276. updatedFile.setShareViaLink(localFile.isSharedViaLink());
  277. updatedFile.setShareWithSharee(localFile.isSharedWithSharee());
  278. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  279. } else {
  280. // remote eTag will not be updated unless file CONTENTS are synchronized
  281. updatedFile.setEtag("");
  282. }
  283. /// check and fix, if needed, local storage path
  284. searchForLocalFileInDefaultPath(updatedFile);
  285. /// classify file to sync/download contents later
  286. if (remoteFile.isFolder()) {
  287. /// to download children files recursively
  288. synchronized (mCancellationRequested) {
  289. if (mCancellationRequested.get()) {
  290. throw new OperationCancelledException();
  291. }
  292. startSyncFolderOperation(remoteFile.getRemotePath());
  293. }
  294. } else {
  295. /// prepare content synchronization for files (any file, not just favorites)
  296. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  297. localFile,
  298. remoteFile,
  299. mAccount,
  300. true,
  301. mContext
  302. );
  303. mFilesToSyncContents.add(operation);
  304. }
  305. updatedFiles.add(updatedFile);
  306. }
  307. // save updated contents in local database
  308. storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  309. }
  310. private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
  311. // TODO Enable when "On Device" is recovered ?
  312. List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder/*, false*/);
  313. for (OCFile child : children) {
  314. /// classify file to sync/download contents later
  315. if (child.isFolder()) {
  316. /// to download children files recursively
  317. synchronized(mCancellationRequested) {
  318. if (mCancellationRequested.get()) {
  319. throw new OperationCancelledException();
  320. }
  321. startSyncFolderOperation(child.getRemotePath());
  322. }
  323. } else {
  324. /// synchronization for regular files
  325. if (!child.isDown()) {
  326. mFilesForDirectDownload.add(child);
  327. } else {
  328. /// this should result in direct upload of files that were locally modified
  329. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  330. child,
  331. (child.getEtagInConflict() != null ? child : null),
  332. mAccount,
  333. true,
  334. mContext
  335. );
  336. mFilesToSyncContents.add(operation);
  337. }
  338. }
  339. }
  340. }
  341. private void syncContents(OwnCloudClient client) throws OperationCancelledException {
  342. startDirectDownloads();
  343. startContentSynchronizations(mFilesToSyncContents, client);
  344. }
  345. private void startDirectDownloads() throws OperationCancelledException {
  346. for (OCFile file : mFilesForDirectDownload) {
  347. synchronized(mCancellationRequested) {
  348. if (mCancellationRequested.get()) {
  349. throw new OperationCancelledException();
  350. }
  351. Intent i = new Intent(mContext, FileDownloader.class);
  352. i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
  353. i.putExtra(FileDownloader.EXTRA_FILE, file);
  354. mContext.startService(i);
  355. }
  356. }
  357. }
  358. /**
  359. * Performs a list of synchronization operations, determining if a download or upload is needed
  360. * or if exists conflict due to changes both in local and remote contents of the each file.
  361. *
  362. * If download or upload is needed, request the operation to the corresponding service and goes
  363. * on.
  364. *
  365. * @param filesToSyncContents Synchronization operations to execute.
  366. * @param client Interface to the remote ownCloud server.
  367. */
  368. private void startContentSynchronizations(List<SyncOperation> filesToSyncContents,
  369. OwnCloudClient client)
  370. throws OperationCancelledException {
  371. Log_OC.v(TAG, "Starting content synchronization... ");
  372. RemoteOperationResult contentsResult = null;
  373. for (SyncOperation op: filesToSyncContents) {
  374. if (mCancellationRequested.get()) {
  375. throw new OperationCancelledException();
  376. }
  377. contentsResult = op.execute(getStorageManager(), mContext);
  378. if (!contentsResult.isSuccess()) {
  379. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  380. mConflictsFound++;
  381. } else {
  382. mFailsInFileSyncsFound++;
  383. if (contentsResult.getException() != null) {
  384. Log_OC.e(TAG, "Error while synchronizing file : "
  385. + contentsResult.getLogMessage(), contentsResult.getException());
  386. } else {
  387. Log_OC.e(TAG, "Error while synchronizing file : "
  388. + contentsResult.getLogMessage());
  389. }
  390. }
  391. // TODO - use the errors count in notifications
  392. } // won't let these fails break the synchronization process
  393. }
  394. }
  395. /**
  396. * Scans the default location for saving local copies of files searching for
  397. * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
  398. * received as parameter.
  399. *
  400. * @param file File to associate a possible 'lost' local file.
  401. */
  402. private void searchForLocalFileInDefaultPath(OCFile file) {
  403. if (file.getStoragePath() == null && !file.isFolder()) {
  404. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  405. if (f.exists()) {
  406. file.setStoragePath(f.getAbsolutePath());
  407. file.setLastSyncDateForData(f.lastModified());
  408. }
  409. }
  410. }
  411. /**
  412. * Cancel operation
  413. */
  414. public void cancel() {
  415. mCancellationRequested.set(true);
  416. }
  417. public String getFolderPath() {
  418. String path = mLocalFolder.getStoragePath();
  419. if (path != null && path.length() > 0) {
  420. return path;
  421. }
  422. return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
  423. }
  424. private void startSyncFolderOperation(String path){
  425. Intent intent = new Intent(mContext, OperationsService.class);
  426. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  427. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
  428. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
  429. mContext.startService(intent);
  430. }
  431. public String getRemotePath() {
  432. return mRemotePath;
  433. }
  434. }