SynchronizeFolderOperation.java 21 KB

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