SynchronizeFolderOperation.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 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.files.services.FileDownloader;
  28. import com.owncloud.android.lib.common.OwnCloudClient;
  29. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  30. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  31. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  32. import com.owncloud.android.lib.common.utils.Log_OC;
  33. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  34. import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
  35. import com.owncloud.android.lib.resources.files.RemoteFile;
  36. import com.owncloud.android.operations.common.SyncOperation;
  37. import com.owncloud.android.services.OperationsService;
  38. import com.owncloud.android.utils.FileStorageUtils;
  39. import com.owncloud.android.utils.MimeTypeUtil;
  40. import java.io.File;
  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. import java.util.concurrent.atomic.AtomicBoolean;
  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();
  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) throws OperationCancelledException {
  140. Log_OC.d(TAG, "Checking changes in " + mAccount.name + mRemotePath);
  141. mRemoteFolderChanged = true;
  142. RemoteOperationResult result;
  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 = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
  153. result = new RemoteOperationResult(ResultCode.OK);
  154. Log_OC.i(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  155. (mRemoteFolderChanged ? "changed" : "not changed"));
  156. } else {
  157. // check failed
  158. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  159. removeLocalFolder();
  160. }
  161. if (result.isException()) {
  162. Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  163. result.getLogMessage(), result.getException());
  164. } else {
  165. Log_OC.e(TAG, "Checked " + mAccount.name + mRemotePath + " : " +
  166. result.getLogMessage());
  167. }
  168. }
  169. return result;
  170. }
  171. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) throws OperationCancelledException {
  172. if (mCancellationRequested.get()) {
  173. throw new OperationCancelledException();
  174. }
  175. ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(mRemotePath);
  176. RemoteOperationResult result = operation.execute(client);
  177. Log_OC.d(TAG, "Synchronizing " + mAccount.name + mRemotePath);
  178. if (result.isSuccess()) {
  179. synchronizeData(result.getData());
  180. if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
  181. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  182. // should be a different result code, but will do the job
  183. }
  184. } else {
  185. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  186. removeLocalFolder();
  187. }
  188. }
  189. return result;
  190. }
  191. private void removeLocalFolder() {
  192. FileDataStorageManager storageManager = getStorageManager();
  193. if (storageManager.fileExists(mLocalFolder.getFileId())) {
  194. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  195. storageManager.removeFolder(
  196. mLocalFolder,
  197. true,
  198. ( mLocalFolder.isDown() && // TODO: debug, I think this is
  199. // always false for folders
  200. mLocalFolder.getStoragePath().startsWith(currentSavePath)
  201. )
  202. );
  203. }
  204. }
  205. /**
  206. * Synchronizes the data retrieved from the server about the contents of the target folder
  207. * with the current data in the local database.
  208. *
  209. * Grants that mChildren is updated with fresh data after execution.
  210. *
  211. * @param folderAndFiles Remote folder and children files in Folder
  212. */
  213. private void synchronizeData(ArrayList<Object> folderAndFiles) throws OperationCancelledException {
  214. FileDataStorageManager storageManager = getStorageManager();
  215. // parse data from remote folder
  216. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
  217. remoteFolder.setParentId(mLocalFolder.getParentId());
  218. remoteFolder.setFileId(mLocalFolder.getFileId());
  219. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
  220. + " changed - starting update of local data ");
  221. List<OCFile> updatedFiles = new Vector<>(folderAndFiles.size() - 1);
  222. mFilesForDirectDownload.clear();
  223. mFilesToSyncContents.clear();
  224. if (mCancellationRequested.get()) {
  225. throw new OperationCancelledException();
  226. }
  227. // get current data about local contents of the folder to synchronize
  228. List<OCFile> localFiles = storageManager.getFolderContent(mLocalFolder, false);
  229. Map<String, OCFile> localFilesMap = new HashMap<>(localFiles.size());
  230. for (OCFile file : localFiles) {
  231. localFilesMap.put(file.getRemotePath(), file);
  232. }
  233. // loop to synchronize every child
  234. OCFile remoteFile = null, localFile = null, updatedFile = null;
  235. RemoteFile r;
  236. for (int i=1; i<folderAndFiles.size(); i++) {
  237. /// new OCFile instance with the data from the server
  238. r = (RemoteFile) folderAndFiles.get(i);
  239. remoteFile = FileStorageUtils.fillOCFile(r);
  240. /// retrieve local data for the read file
  241. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  242. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  243. /// new OCFile instance to merge fresh data from server with local state
  244. updatedFile = FileStorageUtils.fillOCFile(r);
  245. updatedFile.setParentId(mLocalFolder.getFileId());
  246. /// add to updatedFile data about LOCAL STATE (not existing in server)
  247. updateLocalStateData(remoteFile, localFile, updatedFile);
  248. /// check and fix, if needed, local storage path
  249. searchForLocalFileInDefaultPath(updatedFile);
  250. /// classify file to sync/download contents later
  251. classifyFileForLaterSyncOrDownload(remoteFile, localFile);
  252. updatedFiles.add(updatedFile);
  253. }
  254. // save updated contents in local database
  255. storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  256. }
  257. private void updateLocalStateData(OCFile remoteFile, OCFile localFile, OCFile updatedFile) {
  258. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  259. if (localFile != null) {
  260. updatedFile.setFileId(localFile.getFileId());
  261. updatedFile.setAvailableOffline(localFile.isAvailableOffline());
  262. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  263. updatedFile.setModificationTimestampAtLastSyncForData(
  264. localFile.getModificationTimestampAtLastSyncForData()
  265. );
  266. updatedFile.setStoragePath(localFile.getStoragePath());
  267. // eTag will not be updated unless file CONTENTS are synchronized
  268. updatedFile.setEtag(localFile.getEtag());
  269. if (updatedFile.isFolder()) {
  270. updatedFile.setFileLength(localFile.getFileLength());
  271. // TODO move operations about size of folders to FileContentProvider
  272. } else if (mRemoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
  273. remoteFile.getModificationTimestamp() !=
  274. localFile.getModificationTimestamp()) {
  275. updatedFile.setNeedsUpdateThumbnail(true);
  276. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  277. }
  278. updatedFile.setPublicLink(localFile.getPublicLink());
  279. updatedFile.setShareViaLink(localFile.isSharedViaLink());
  280. updatedFile.setShareWithSharee(localFile.isSharedWithSharee());
  281. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  282. } else {
  283. // remote eTag will not be updated unless file CONTENTS are synchronized
  284. updatedFile.setEtag("");
  285. }
  286. }
  287. private void classifyFileForLaterSyncOrDownload(OCFile remoteFile, OCFile localFile)
  288. throws OperationCancelledException {
  289. if (remoteFile.isFolder()) {
  290. /// to download children files recursively
  291. synchronized (mCancellationRequested) {
  292. if (mCancellationRequested.get()) {
  293. throw new OperationCancelledException();
  294. }
  295. startSyncFolderOperation(remoteFile.getRemotePath());
  296. }
  297. } else {
  298. /// prepare content synchronization for files (any file, not just favorites)
  299. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  300. localFile,
  301. remoteFile,
  302. mAccount,
  303. true,
  304. mContext
  305. );
  306. mFilesToSyncContents.add(operation);
  307. }
  308. }
  309. private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
  310. List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder, false);
  311. for (OCFile child : children) {
  312. /// classify file to sync/download contents later
  313. if (child.isFolder()) {
  314. /// to download children files recursively
  315. synchronized(mCancellationRequested) {
  316. if (mCancellationRequested.get()) {
  317. throw new OperationCancelledException();
  318. }
  319. startSyncFolderOperation(child.getRemotePath());
  320. }
  321. } else {
  322. /// synchronization for regular files
  323. if (!child.isDown()) {
  324. mFilesForDirectDownload.add(child);
  325. } else {
  326. /// this should result in direct upload of files that were locally modified
  327. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  328. child,
  329. (child.getEtagInConflict() != null ? child : null),
  330. mAccount,
  331. true,
  332. mContext
  333. );
  334. mFilesToSyncContents.add(operation);
  335. }
  336. }
  337. }
  338. }
  339. private void syncContents() throws OperationCancelledException {
  340. startDirectDownloads();
  341. startContentSynchronizations(mFilesToSyncContents);
  342. }
  343. private void startDirectDownloads() throws OperationCancelledException {
  344. for (OCFile file : mFilesForDirectDownload) {
  345. synchronized(mCancellationRequested) {
  346. if (mCancellationRequested.get()) {
  347. throw new OperationCancelledException();
  348. }
  349. Intent i = new Intent(mContext, FileDownloader.class);
  350. i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
  351. i.putExtra(FileDownloader.EXTRA_FILE, file);
  352. mContext.startService(i);
  353. }
  354. }
  355. }
  356. /**
  357. * Performs a list of synchronization operations, determining if a download or upload is needed
  358. * or if exists conflict due to changes both in local and remote contents of the each file.
  359. *
  360. * If download or upload is needed, request the operation to the corresponding service and goes on.
  361. *
  362. * @param filesToSyncContents Synchronization operations to execute.
  363. */
  364. private void startContentSynchronizations(List<SyncOperation> filesToSyncContents)
  365. throws OperationCancelledException {
  366. Log_OC.v(TAG, "Starting content synchronization... ");
  367. RemoteOperationResult contentsResult;
  368. for (SyncOperation op: filesToSyncContents) {
  369. if (mCancellationRequested.get()) {
  370. throw new OperationCancelledException();
  371. }
  372. contentsResult = op.execute(getStorageManager(), mContext);
  373. if (!contentsResult.isSuccess()) {
  374. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  375. mConflictsFound++;
  376. } else {
  377. mFailsInFileSyncsFound++;
  378. if (contentsResult.getException() != null) {
  379. Log_OC.e(TAG, "Error while synchronizing file : "
  380. + contentsResult.getLogMessage(), contentsResult.getException());
  381. } else {
  382. Log_OC.e(TAG, "Error while synchronizing file : "
  383. + contentsResult.getLogMessage());
  384. }
  385. }
  386. // TODO - use the errors count in notifications
  387. } // won't let these fails break the synchronization process
  388. }
  389. }
  390. /**
  391. * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
  392. * object with the data read from the server.
  393. *
  394. * @param remote remote file read from the server (remote file or folder).
  395. * @return New OCFile instance representing the remote resource described by we.
  396. */
  397. private OCFile fillOCFile(RemoteFile remote) {
  398. return FileStorageUtils.fillOCFile(remote);
  399. }
  400. /**
  401. * Scans the default location for saving local copies of files searching for
  402. * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
  403. * received as parameter.
  404. *
  405. * @param file File to associate a possible 'lost' local file.
  406. */
  407. private void searchForLocalFileInDefaultPath(OCFile file) {
  408. if (file.getStoragePath() == null && !file.isFolder()) {
  409. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  410. if (f.exists()) {
  411. file.setStoragePath(f.getAbsolutePath());
  412. file.setLastSyncDateForData(f.lastModified());
  413. }
  414. }
  415. }
  416. /**
  417. * Cancel operation
  418. */
  419. public void cancel() {
  420. mCancellationRequested.set(true);
  421. }
  422. public String getFolderPath() {
  423. String path = mLocalFolder.getStoragePath();
  424. if (path != null && path.length() > 0) {
  425. return path;
  426. }
  427. return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
  428. }
  429. private void startSyncFolderOperation(String path){
  430. Intent intent = new Intent(mContext, OperationsService.class);
  431. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  432. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
  433. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
  434. mContext.startService(intent);
  435. }
  436. public String getRemotePath() {
  437. return mRemotePath;
  438. }
  439. }