SynchronizeFolderOperation.java 22 KB

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