SynchronizeFolderOperation.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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;
  235. OCFile localFile = null;
  236. OCFile updatedFile = null;
  237. RemoteFile r;
  238. for (int i=1; i<folderAndFiles.size(); i++) {
  239. /// new OCFile instance with the data from the server
  240. r = (RemoteFile) folderAndFiles.get(i);
  241. remoteFile = FileStorageUtils.fillOCFile(r);
  242. /// retrieve local data for the read file
  243. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  244. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  245. /// new OCFile instance to merge fresh data from server with local state
  246. updatedFile = FileStorageUtils.fillOCFile(r);
  247. updatedFile.setParentId(mLocalFolder.getFileId());
  248. /// add to updatedFile data about LOCAL STATE (not existing in server)
  249. updateLocalStateData(remoteFile, localFile, updatedFile);
  250. /// check and fix, if needed, local storage path
  251. searchForLocalFileInDefaultPath(updatedFile);
  252. /// classify file to sync/download contents later
  253. classifyFileForLaterSyncOrDownload(remoteFile, localFile);
  254. updatedFiles.add(updatedFile);
  255. }
  256. // save updated contents in local database
  257. storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  258. }
  259. private void updateLocalStateData(OCFile remoteFile, OCFile localFile, OCFile updatedFile) {
  260. updatedFile.setLastSyncDateForProperties(mCurrentSyncTime);
  261. if (localFile != null) {
  262. updatedFile.setFileId(localFile.getFileId());
  263. updatedFile.setAvailableOffline(localFile.isAvailableOffline());
  264. updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  265. updatedFile.setModificationTimestampAtLastSyncForData(
  266. localFile.getModificationTimestampAtLastSyncForData()
  267. );
  268. updatedFile.setStoragePath(localFile.getStoragePath());
  269. // eTag will not be updated unless file CONTENTS are synchronized
  270. updatedFile.setEtag(localFile.getEtag());
  271. if (updatedFile.isFolder()) {
  272. updatedFile.setFileLength(localFile.getFileLength());
  273. // TODO move operations about size of folders to FileContentProvider
  274. } else if (mRemoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
  275. remoteFile.getModificationTimestamp() !=
  276. localFile.getModificationTimestamp()) {
  277. updatedFile.setNeedsUpdateThumbnail(true);
  278. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  279. }
  280. updatedFile.setPublicLink(localFile.getPublicLink());
  281. updatedFile.setShareViaLink(localFile.isSharedViaLink());
  282. updatedFile.setShareWithSharee(localFile.isSharedWithSharee());
  283. updatedFile.setEtagInConflict(localFile.getEtagInConflict());
  284. } else {
  285. // remote eTag will not be updated unless file CONTENTS are synchronized
  286. updatedFile.setEtag("");
  287. }
  288. }
  289. private void classifyFileForLaterSyncOrDownload(OCFile remoteFile, OCFile localFile)
  290. throws OperationCancelledException {
  291. if (remoteFile.isFolder()) {
  292. /// to download children files recursively
  293. synchronized (mCancellationRequested) {
  294. if (mCancellationRequested.get()) {
  295. throw new OperationCancelledException();
  296. }
  297. startSyncFolderOperation(remoteFile.getRemotePath());
  298. }
  299. } else {
  300. /// prepare content synchronization for files (any file, not just favorites)
  301. SynchronizeFileOperation operation = new SynchronizeFileOperation(
  302. localFile,
  303. remoteFile,
  304. mAccount,
  305. true,
  306. mContext
  307. );
  308. mFilesToSyncContents.add(operation);
  309. }
  310. }
  311. private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
  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() throws OperationCancelledException {
  342. startDirectDownloads();
  343. startContentSynchronizations(mFilesToSyncContents);
  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 on.
  363. *
  364. * @param filesToSyncContents Synchronization operations to execute.
  365. */
  366. private void startContentSynchronizations(List<SyncOperation> filesToSyncContents)
  367. throws OperationCancelledException {
  368. Log_OC.v(TAG, "Starting content synchronization... ");
  369. RemoteOperationResult contentsResult;
  370. for (SyncOperation op: filesToSyncContents) {
  371. if (mCancellationRequested.get()) {
  372. throw new OperationCancelledException();
  373. }
  374. contentsResult = op.execute(getStorageManager(), mContext);
  375. if (!contentsResult.isSuccess()) {
  376. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  377. mConflictsFound++;
  378. } else {
  379. mFailsInFileSyncsFound++;
  380. if (contentsResult.getException() != null) {
  381. Log_OC.e(TAG, "Error while synchronizing file : "
  382. + contentsResult.getLogMessage(), contentsResult.getException());
  383. } else {
  384. Log_OC.e(TAG, "Error while synchronizing file : "
  385. + contentsResult.getLogMessage());
  386. }
  387. }
  388. // TODO - use the errors count in notifications
  389. } // won't let these fails break the synchronization process
  390. }
  391. }
  392. /**
  393. * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile}
  394. * object with the data read from the server.
  395. *
  396. * @param remote remote file read from the server (remote file or folder).
  397. * @return New OCFile instance representing the remote resource described by we.
  398. */
  399. private OCFile fillOCFile(RemoteFile remote) {
  400. return FileStorageUtils.fillOCFile(remote);
  401. }
  402. /**
  403. * Scans the default location for saving local copies of files searching for
  404. * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile}
  405. * received as parameter.
  406. *
  407. * @param file File to associate a possible 'lost' local file.
  408. */
  409. private void searchForLocalFileInDefaultPath(OCFile file) {
  410. if (file.getStoragePath() == null && !file.isFolder()) {
  411. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  412. if (f.exists()) {
  413. file.setStoragePath(f.getAbsolutePath());
  414. file.setLastSyncDateForData(f.lastModified());
  415. }
  416. }
  417. }
  418. /**
  419. * Cancel operation
  420. */
  421. public void cancel() {
  422. mCancellationRequested.set(true);
  423. }
  424. public String getFolderPath() {
  425. String path = mLocalFolder.getStoragePath();
  426. if (path != null && path.length() > 0) {
  427. return path;
  428. }
  429. return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mLocalFolder);
  430. }
  431. private void startSyncFolderOperation(String path){
  432. Intent intent = new Intent(mContext, OperationsService.class);
  433. intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
  434. intent.putExtra(OperationsService.EXTRA_ACCOUNT, mAccount);
  435. intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
  436. mContext.startService(intent);
  437. }
  438. public String getRemotePath() {
  439. return mRemotePath;
  440. }
  441. }