SynchronizeFolderOperation.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012-2013 ownCloud Inc.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License version 2,
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. package com.owncloud.android.operations;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Vector;
  28. import org.apache.http.HttpStatus;
  29. import org.apache.jackrabbit.webdav.DavConstants;
  30. import org.apache.jackrabbit.webdav.MultiStatus;
  31. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  32. import android.accounts.Account;
  33. import android.content.Context;
  34. import android.content.Intent;
  35. import com.owncloud.android.Log_OC;
  36. import com.owncloud.android.datamodel.FileDataStorageManager;
  37. import com.owncloud.android.datamodel.OCFile;
  38. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  39. import com.owncloud.android.syncadapter.FileSyncService;
  40. import com.owncloud.android.utils.FileStorageUtils;
  41. import eu.alefzero.webdav.WebdavClient;
  42. import eu.alefzero.webdav.WebdavEntry;
  43. import eu.alefzero.webdav.WebdavUtils;
  44. /**
  45. * Remote operation performing the synchronization of the list of files contained
  46. * in a folder identified with its remote path.
  47. *
  48. * Fetches the list and properties of the files contained in the given folder, including their
  49. * properties, and updates the local database with them.
  50. *
  51. * Does NOT enter in the child folders to synchronize their contents also.
  52. *
  53. * @author David A. Velasco
  54. */
  55. public class SynchronizeFolderOperation extends RemoteOperation {
  56. private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
  57. /** Time stamp for the synchronization process in progress */
  58. private long mCurrentSyncTime;
  59. /** Remote folder to synchronize */
  60. private OCFile mLocalFolder;
  61. /** Access to the local database */
  62. private FileDataStorageManager mStorageManager;
  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. /** Files and folders contained in the synchronized folder after a successful operation */
  68. private List<OCFile> mChildren;
  69. /** Counter of conflicts found between local and remote files */
  70. private int mConflictsFound;
  71. /** Counter of failed operations in synchronization of kept-in-sync files */
  72. private int mFailsInFavouritesFound;
  73. /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
  74. private Map<String, String> mForgottenLocalFiles;
  75. /** 'True' means that this operation is part of a full account synchronization */
  76. private boolean mSyncFullAccount;
  77. /** 'True' means that the remote folder changed from last synchronization and should be fetched */
  78. private boolean mRemoteFolderChanged;
  79. /**
  80. * Creates a new instance of {@link SynchronizeFolderOperation}.
  81. *
  82. * @param remoteFolderPath Remote folder to synchronize.
  83. * @param currentSyncTime Time stamp for the synchronization process in progress.
  84. * @param localFolderId Identifier in the local database of the folder to synchronize.
  85. * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
  86. * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
  87. * @param dataStorageManager Interface with the local database.
  88. * @param account ownCloud account where the folder is located.
  89. * @param context Application context.
  90. */
  91. public SynchronizeFolderOperation( OCFile folder,
  92. long currentSyncTime,
  93. boolean syncFullAccount,
  94. FileDataStorageManager dataStorageManager,
  95. Account account,
  96. Context context ) {
  97. mLocalFolder = folder;
  98. mCurrentSyncTime = currentSyncTime;
  99. mSyncFullAccount = syncFullAccount;
  100. mStorageManager = dataStorageManager;
  101. mAccount = account;
  102. mContext = context;
  103. mForgottenLocalFiles = new HashMap<String, String>();
  104. mRemoteFolderChanged = false;
  105. }
  106. public int getConflictsFound() {
  107. return mConflictsFound;
  108. }
  109. public int getFailsInFavouritesFound() {
  110. return mFailsInFavouritesFound;
  111. }
  112. public Map<String, String> getForgottenLocalFiles() {
  113. return mForgottenLocalFiles;
  114. }
  115. /**
  116. * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
  117. *
  118. * @return List of files and folders contained in the synchronized folder.
  119. */
  120. public List<OCFile> getChildren() {
  121. return mChildren;
  122. }
  123. /**
  124. * Performs the synchronization.
  125. *
  126. * {@inheritDoc}
  127. */
  128. @Override
  129. protected RemoteOperationResult run(WebdavClient client) {
  130. RemoteOperationResult result = null;
  131. mFailsInFavouritesFound = 0;
  132. mConflictsFound = 0;
  133. mForgottenLocalFiles.clear();
  134. result = checkForChanges(client);
  135. if (result.isSuccess()) {
  136. if (mRemoteFolderChanged) {
  137. result = fetchAndSyncRemoteFolder(client);
  138. } else {
  139. mChildren = mStorageManager.getFolderContent(mLocalFolder);
  140. }
  141. }
  142. if (!mSyncFullAccount) {
  143. sendStickyBroadcast(false, mLocalFolder.getRemotePath(), result);
  144. }
  145. return result;
  146. }
  147. private RemoteOperationResult checkForChanges(WebdavClient client) {
  148. mRemoteFolderChanged = false;
  149. RemoteOperationResult result = null;
  150. String remotePath = null;
  151. PropFindMethod query = null;
  152. try {
  153. remotePath = mLocalFolder.getRemotePath();
  154. Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
  155. // remote request
  156. query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(remotePath),
  157. DavConstants.PROPFIND_ALL_PROP,
  158. DavConstants.DEPTH_0);
  159. int status = client.executeMethod(query);
  160. // check and process response
  161. if (isMultiStatus(status)) {
  162. // parse data from remote folder
  163. WebdavEntry we = new WebdavEntry(query.getResponseBodyAsMultiStatus().getResponses()[0], client.getBaseUri().getPath());
  164. OCFile remoteFolder = fillOCFile(we);
  165. // check if remote and local folder are different
  166. mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
  167. result = new RemoteOperationResult(ResultCode.OK);
  168. } else {
  169. // check failed
  170. client.exhaustResponse(query.getResponseBodyAsStream());
  171. if (status == HttpStatus.SC_NOT_FOUND) {
  172. removeLocalFolder();
  173. }
  174. result = new RemoteOperationResult(false, status, query.getResponseHeaders());
  175. }
  176. } catch (Exception e) {
  177. result = new RemoteOperationResult(e);
  178. } finally {
  179. if (query != null)
  180. query.releaseConnection(); // let the connection available for other methods
  181. if (result.isSuccess()) {
  182. Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " + (mRemoteFolderChanged ? "changed" : "not changed"));
  183. } else {
  184. if (result.isException()) {
  185. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage(), result.getException());
  186. } else {
  187. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage());
  188. }
  189. }
  190. }
  191. return result;
  192. }
  193. private RemoteOperationResult fetchAndSyncRemoteFolder(WebdavClient client) {
  194. RemoteOperationResult result = null;
  195. String remotePath = null;
  196. PropFindMethod query = null;
  197. try {
  198. remotePath = mLocalFolder.getRemotePath();
  199. Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
  200. // remote request
  201. query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(remotePath),
  202. DavConstants.PROPFIND_ALL_PROP,
  203. DavConstants.DEPTH_1);
  204. int status = client.executeMethod(query);
  205. // check and process response
  206. if (isMultiStatus(status)) {
  207. synchronizeData(query.getResponseBodyAsMultiStatus(), client);
  208. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  209. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
  210. } else {
  211. result = new RemoteOperationResult(true, status, query.getResponseHeaders());
  212. }
  213. } else {
  214. // synchronization failed
  215. client.exhaustResponse(query.getResponseBodyAsStream());
  216. if (status == HttpStatus.SC_NOT_FOUND) {
  217. removeLocalFolder();
  218. }
  219. result = new RemoteOperationResult(false, status, query.getResponseHeaders());
  220. }
  221. } catch (Exception e) {
  222. result = new RemoteOperationResult(e);
  223. } finally {
  224. if (query != null)
  225. query.releaseConnection(); // let the connection available for other methods
  226. if (result.isSuccess()) {
  227. Log_OC.i(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage());
  228. } else {
  229. if (result.isException()) {
  230. Log_OC.e(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage(), result.getException());
  231. } else {
  232. Log_OC.e(TAG, "Synchronized " + mAccount.name + remotePath + ": " + result.getLogMessage());
  233. }
  234. }
  235. }
  236. return result;
  237. }
  238. private void removeLocalFolder() {
  239. if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
  240. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  241. mStorageManager.removeFolder(mLocalFolder, true, (mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)));
  242. }
  243. }
  244. /**
  245. * Synchronizes the data retrieved from the server about the contents of the target folder
  246. * with the current data in the local database.
  247. *
  248. * Grants that mChildren is updated with fresh data after execution.
  249. *
  250. * @param dataInServer Full response got from the server with the data of the target
  251. * folder and its direct children.
  252. * @param client Client instance to the remote server where the data were
  253. * retrieved.
  254. * @return 'True' when any change was made in the local data, 'false' otherwise.
  255. */
  256. private void synchronizeData(MultiStatus dataInServer, WebdavClient client) {
  257. // get 'fresh data' from the database
  258. mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
  259. // parse data from remote folder
  260. WebdavEntry we = new WebdavEntry(dataInServer.getResponses()[0], client.getBaseUri().getPath());
  261. OCFile remoteFolder = fillOCFile(we);
  262. remoteFolder.setParentId(mLocalFolder.getParentId());
  263. remoteFolder.setFileId(mLocalFolder.getFileId());
  264. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
  265. List<OCFile> updatedFiles = new Vector<OCFile>(dataInServer.getResponses().length - 1);
  266. List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
  267. // get current data about local contents of the folder to synchronize
  268. List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
  269. Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
  270. for (OCFile file : localFiles) {
  271. localFilesMap.put(file.getRemotePath(), file);
  272. }
  273. // loop to update every child
  274. OCFile remoteFile = null, localFile = null;
  275. for (int i = 1; i < dataInServer.getResponses().length; ++i) {
  276. /// new OCFile instance with the data from the server
  277. we = new WebdavEntry(dataInServer.getResponses()[i], client.getBaseUri().getPath());
  278. remoteFile = fillOCFile(we);
  279. remoteFile.setParentId(mLocalFolder.getFileId());
  280. /// retrieve local data for the read file
  281. //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  282. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  283. /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
  284. remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
  285. if (localFile != null) {
  286. // some properties of local state are kept unmodified
  287. remoteFile.setFileId(localFile.getFileId());
  288. remoteFile.setKeepInSync(localFile.keepInSync());
  289. remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  290. remoteFile.setModificationTimestampAtLastSyncForData(localFile.getModificationTimestampAtLastSyncForData());
  291. remoteFile.setStoragePath(localFile.getStoragePath());
  292. remoteFile.setEtag(localFile.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
  293. if (remoteFile.isFolder()) {
  294. remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider
  295. }
  296. } else {
  297. remoteFile.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
  298. }
  299. /// check and fix, if needed, local storage path
  300. checkAndFixForeignStoragePath(remoteFile); // fixing old policy - now local files must be copied into the ownCloud local folder
  301. searchForLocalFileInDefaultPath(remoteFile); // legacy
  302. /// prepare content synchronization for kept-in-sync files
  303. if (remoteFile.keepInSync()) {
  304. SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
  305. remoteFile,
  306. mStorageManager,
  307. mAccount,
  308. true,
  309. mContext
  310. );
  311. filesToSyncContents.add(operation);
  312. }
  313. updatedFiles.add(remoteFile);
  314. }
  315. // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
  316. mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  317. // request for the synchronization of file contents AFTER saving current remote properties
  318. startContentSynchronizations(filesToSyncContents, client);
  319. // removal of obsolete files
  320. //removeObsoleteFiles();
  321. // must be done AFTER saving all the children information, so that eTag is not updated in the database in case of unexpected exceptions
  322. //mStorageManager.saveFile(remoteFolder);
  323. mChildren = updatedFiles;
  324. }
  325. /**
  326. * Performs a list of synchronization operations, determining if a download or upload is needed or
  327. * if exists conflict due to changes both in local and remote contents of the each file.
  328. *
  329. * If download or upload is needed, request the operation to the corresponding service and goes on.
  330. *
  331. * @param filesToSyncContents Synchronization operations to execute.
  332. * @param client Interface to the remote ownCloud server.
  333. */
  334. private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents, WebdavClient client) {
  335. RemoteOperationResult contentsResult = null;
  336. for (SynchronizeFileOperation op: filesToSyncContents) {
  337. contentsResult = op.execute(client); // returns without waiting for upload or download finishes
  338. if (!contentsResult.isSuccess()) {
  339. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  340. mConflictsFound++;
  341. } else {
  342. mFailsInFavouritesFound++;
  343. if (contentsResult.getException() != null) {
  344. Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
  345. } else {
  346. Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
  347. }
  348. }
  349. } // won't let these fails break the synchronization process
  350. }
  351. }
  352. public boolean isMultiStatus(int status) {
  353. return (status == HttpStatus.SC_MULTI_STATUS);
  354. }
  355. /**
  356. * Creates and populates a new {@link OCFile} object with the data read from the server.
  357. *
  358. * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
  359. * @return New OCFile instance representing the remote resource described by we.
  360. */
  361. private OCFile fillOCFile(WebdavEntry we) {
  362. OCFile file = new OCFile(we.decodedPath());
  363. file.setCreationTimestamp(we.createTimestamp());
  364. file.setFileLength(we.contentLength());
  365. file.setMimetype(we.contentType());
  366. file.setModificationTimestamp(we.modifiedTimestamp());
  367. file.setEtag(we.etag());
  368. return file;
  369. }
  370. /**
  371. * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
  372. * tries to copy the file inside it.
  373. *
  374. * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
  375. * {@link #mForgottenLocalFiles}
  376. *)
  377. * @param file File to check and fix.
  378. */
  379. private void checkAndFixForeignStoragePath(OCFile file) {
  380. String storagePath = file.getStoragePath();
  381. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
  382. if (storagePath != null && !storagePath.equals(expectedPath)) {
  383. /// fix storagePaths out of the local ownCloud folder
  384. File originalFile = new File(storagePath);
  385. if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
  386. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  387. file.setStoragePath(null);
  388. } else {
  389. InputStream in = null;
  390. OutputStream out = null;
  391. try {
  392. File expectedFile = new File(expectedPath);
  393. File expectedParent = expectedFile.getParentFile();
  394. expectedParent.mkdirs();
  395. if (!expectedParent.isDirectory()) {
  396. throw new IOException("Unexpected error: parent directory could not be created");
  397. }
  398. expectedFile.createNewFile();
  399. if (!expectedFile.isFile()) {
  400. throw new IOException("Unexpected error: target file could not be created");
  401. }
  402. in = new FileInputStream(originalFile);
  403. out = new FileOutputStream(expectedFile);
  404. byte[] buf = new byte[1024];
  405. int len;
  406. while ((len = in.read(buf)) > 0){
  407. out.write(buf, 0, len);
  408. }
  409. file.setStoragePath(expectedPath);
  410. } catch (Exception e) {
  411. Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
  412. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  413. file.setStoragePath(null);
  414. } finally {
  415. try {
  416. if (in != null) in.close();
  417. } catch (Exception e) {
  418. Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
  419. }
  420. try {
  421. if (out != null) out.close();
  422. } catch (Exception e) {
  423. Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
  424. }
  425. }
  426. }
  427. }
  428. }
  429. /**
  430. * Scans the default location for saving local copies of files searching for
  431. * a 'lost' file with the same full name as the {@link OCFile} received as
  432. * parameter.
  433. *
  434. * @param file File to associate a possible 'lost' local file.
  435. */
  436. private void searchForLocalFileInDefaultPath(OCFile file) {
  437. if (file.getStoragePath() == null && !file.isFolder()) {
  438. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  439. if (f.exists()) {
  440. file.setStoragePath(f.getAbsolutePath());
  441. file.setLastSyncDateForData(f.lastModified());
  442. }
  443. }
  444. }
  445. /**
  446. * Sends a message to any application component interested in the progress of the synchronization.
  447. *
  448. * @param inProgress 'True' when the synchronization progress is not finished.
  449. * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
  450. */
  451. private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {
  452. Intent i = new Intent(FileSyncService.getSyncMessage());
  453. i.putExtra(FileSyncService.IN_PROGRESS, inProgress);
  454. i.putExtra(FileSyncService.ACCOUNT_NAME, mAccount.name);
  455. if (dirRemotePath != null) {
  456. i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);
  457. }
  458. if (result != null) {
  459. i.putExtra(FileSyncService.SYNC_RESULT, result);
  460. }
  461. mContext.sendStickyBroadcast(i);
  462. }
  463. public boolean getRemoteFolderChanged() {
  464. return mRemoteFolderChanged;
  465. }
  466. }