SyncFolderOperation.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012-2014 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 android.accounts.Account;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.util.Log;
  22. import com.owncloud.android.datamodel.FileDataStorageManager;
  23. import com.owncloud.android.datamodel.OCFile;
  24. import com.owncloud.android.files.services.FileDownloader;
  25. import com.owncloud.android.lib.common.OwnCloudClient;
  26. import com.owncloud.android.lib.common.operations.RemoteOperation;
  27. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  28. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  29. import com.owncloud.android.lib.common.utils.Log_OC;
  30. import com.owncloud.android.lib.resources.files.FileUtils;
  31. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  32. import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
  33. import com.owncloud.android.lib.resources.files.RemoteFile;
  34. import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
  35. import com.owncloud.android.lib.resources.shares.OCShare;
  36. import com.owncloud.android.operations.common.SyncOperation;
  37. import com.owncloud.android.syncadapter.FileSyncAdapter;
  38. import com.owncloud.android.utils.FileStorageUtils;
  39. import org.apache.http.HttpStatus;
  40. import java.io.File;
  41. import java.io.FileInputStream;
  42. import java.io.FileOutputStream;
  43. import java.io.IOException;
  44. import java.io.InputStream;
  45. import java.io.OutputStream;
  46. import java.util.ArrayList;
  47. import java.util.HashMap;
  48. import java.util.List;
  49. import java.util.Map;
  50. import java.util.Vector;
  51. //import android.support.v4.content.LocalBroadcastManager;
  52. /**
  53. * Remote operation performing the synchronization of the list of files contained
  54. * in a folder identified with its remote path.
  55. *
  56. * Fetches the list and properties of the files contained in the given folder, including their
  57. * properties, and updates the local database with them.
  58. *
  59. * Does NOT enter in the child folders to synchronize their contents also.
  60. *
  61. * @author David A. Velasco
  62. */
  63. public class SyncFolderOperation extends SyncOperation {
  64. private static final String TAG = SyncFolderOperation.class.getSimpleName();
  65. /** Time stamp for the synchronization process in progress */
  66. private long mCurrentSyncTime;
  67. /** Remote folder to synchronize */
  68. private OCFile mLocalFolder;
  69. /** Access to the local database */
  70. private FileDataStorageManager mStorageManager;
  71. /** Account where the file to synchronize belongs */
  72. private Account mAccount;
  73. /** Android context; necessary to send requests to the download service */
  74. private Context mContext;
  75. /** Files and folders contained in the synchronized folder after a successful operation */
  76. private List<OCFile> mChildren;
  77. /** Counter of conflicts found between local and remote files */
  78. private int mConflictsFound;
  79. /** Counter of failed operations in synchronization of kept-in-sync files */
  80. private int mFailsInFavouritesFound;
  81. /**
  82. * Map of remote and local paths to files that where locally stored in a location
  83. * out of the ownCloud folder and couldn't be copied automatically into it
  84. **/
  85. private Map<String, String> mForgottenLocalFiles;
  86. /** 'True' means that the remote folder changed and should be fetched */
  87. private boolean mRemoteFolderChanged;
  88. /**
  89. * Creates a new instance of {@link SyncFolderOperation}.
  90. *
  91. * @param context Application context.
  92. * @param remotePath Path to synchronize.
  93. * @param account ownCloud account where the folder is located.
  94. * @param currentSyncTime Time stamp for the synchronization process in progress.
  95. */
  96. public SyncFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){
  97. mLocalFolder = new OCFile(remotePath);
  98. mCurrentSyncTime = currentSyncTime;
  99. mStorageManager = getStorageManager();
  100. mAccount = account;
  101. mContext = context;
  102. mForgottenLocalFiles = new HashMap<String, String>();
  103. mRemoteFolderChanged = false;
  104. }
  105. public int getConflictsFound() {
  106. return mConflictsFound;
  107. }
  108. public int getFailsInFavouritesFound() {
  109. return mFailsInFavouritesFound;
  110. }
  111. public Map<String, String> getForgottenLocalFiles() {
  112. return mForgottenLocalFiles;
  113. }
  114. /**
  115. * Returns the list of files and folders contained in the synchronized folder,
  116. * 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(OwnCloudClient 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. return result;
  143. }
  144. private RemoteOperationResult checkForChanges(OwnCloudClient client) {
  145. mRemoteFolderChanged = true;
  146. RemoteOperationResult result = null;
  147. String remotePath = null;
  148. remotePath = mLocalFolder.getRemotePath();
  149. Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
  150. // remote request
  151. ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
  152. result = operation.execute(client);
  153. if (result.isSuccess()){
  154. OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  155. // check if remote and local folder are different
  156. mRemoteFolderChanged =
  157. !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
  158. result = new RemoteOperationResult(ResultCode.OK);
  159. Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
  160. (mRemoteFolderChanged ? "changed" : "not changed"));
  161. } else {
  162. // check failed
  163. if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
  164. removeLocalFolder();
  165. }
  166. if (result.isException()) {
  167. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  168. result.getLogMessage(), result.getException());
  169. } else {
  170. Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
  171. result.getLogMessage());
  172. }
  173. }
  174. return result;
  175. }
  176. private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
  177. String remotePath = mLocalFolder.getRemotePath();
  178. ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
  179. RemoteOperationResult result = operation.execute(client);
  180. Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
  181. if (result.isSuccess()) {
  182. synchronizeData(result.getData(), client);
  183. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  184. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  185. // should be a different result code, but will do the job
  186. }
  187. } else {
  188. if (result.getCode() == ResultCode.FILE_NOT_FOUND)
  189. removeLocalFolder();
  190. }
  191. return result;
  192. }
  193. private void removeLocalFolder() {
  194. if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
  195. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  196. mStorageManager.removeFolder(
  197. mLocalFolder,
  198. true,
  199. ( mLocalFolder.isDown() &&
  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. * @param client Client instance to the remote server where the data were
  214. * retrieved.
  215. * @return 'True' when any change was made in the local data, 'false' otherwise
  216. */
  217. private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
  218. // get 'fresh data' from the database
  219. mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
  220. // parse data from remote folder
  221. OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
  222. remoteFolder.setParentId(mLocalFolder.getParentId());
  223. remoteFolder.setFileId(mLocalFolder.getFileId());
  224. Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
  225. + " changed - starting update of local data ");
  226. List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
  227. List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
  228. // get current data about local contents of the folder to synchronize
  229. List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
  230. Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
  231. for (OCFile file : localFiles) {
  232. localFilesMap.put(file.getRemotePath(), file);
  233. }
  234. // loop to update every child
  235. OCFile remoteFile = null, localFile = null;
  236. for (int i=1; i<folderAndFiles.size(); i++) {
  237. /// new OCFile instance with the data from the server
  238. remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
  239. remoteFile.setParentId(mLocalFolder.getFileId());
  240. /// retrieve local data for the read file
  241. // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
  242. localFile = localFilesMap.remove(remoteFile.getRemotePath());
  243. /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
  244. remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
  245. if (localFile != null) {
  246. // some properties of local state are kept unmodified
  247. remoteFile.setFileId(localFile.getFileId());
  248. remoteFile.setKeepInSync(localFile.keepInSync());
  249. remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
  250. remoteFile.setModificationTimestampAtLastSyncForData(
  251. localFile.getModificationTimestampAtLastSyncForData()
  252. );
  253. remoteFile.setStoragePath(localFile.getStoragePath());
  254. // eTag will not be updated unless contents are synchronized
  255. // (Synchronize[File|Folder]Operation with remoteFile as parameter)
  256. remoteFile.setEtag(localFile.getEtag());
  257. if (remoteFile.isFolder()) {
  258. remoteFile.setFileLength(localFile.getFileLength());
  259. // TODO move operations about size of folders to FileContentProvider
  260. } else if (mRemoteFolderChanged && remoteFile.isImage() &&
  261. remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
  262. remoteFile.setNeedsUpdateThumbnail(true);
  263. Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
  264. }
  265. remoteFile.setPublicLink(localFile.getPublicLink());
  266. remoteFile.setShareByLink(localFile.isShareByLink());
  267. } else {
  268. // remote eTag will not be updated unless contents are synchronized
  269. // (Synchronize[File|Folder]Operation with remoteFile as parameter)
  270. remoteFile.setEtag("");
  271. }
  272. /// check and fix, if needed, local storage path
  273. checkAndFixForeignStoragePath(remoteFile); // policy - local files are COPIED
  274. // into the ownCloud local folder;
  275. searchForLocalFileInDefaultPath(remoteFile); // legacy
  276. /// prepare content synchronization for kept-in-sync files
  277. if (remoteFile.keepInSync()) {
  278. SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
  279. remoteFile,
  280. mAccount,
  281. true,
  282. mContext
  283. );
  284. filesToSyncContents.add(operation);
  285. }
  286. // Start the download of all the files in the folder (non recursively)
  287. if (!remoteFile.isFolder()) {
  288. requestForDownloadFile(remoteFile);
  289. }
  290. updatedFiles.add(remoteFile);
  291. }
  292. // save updated contents in local database
  293. mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
  294. // request for the synchronization of file contents AFTER saving current remote properties
  295. startContentSynchronizations(filesToSyncContents, client);
  296. mChildren = updatedFiles;
  297. }
  298. /**
  299. * Performs a list of synchronization operations, determining if a download or upload is needed
  300. * or if exists conflict due to changes both in local and remote contents of the each file.
  301. *
  302. * If download or upload is needed, request the operation to the corresponding service and goes
  303. * on.
  304. *
  305. * @param filesToSyncContents Synchronization operations to execute.
  306. * @param client Interface to the remote ownCloud server.
  307. */
  308. private void startContentSynchronizations(
  309. List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
  310. ) {
  311. RemoteOperationResult contentsResult = null;
  312. for (SynchronizeFileOperation op: filesToSyncContents) {
  313. contentsResult = op.execute(mStorageManager, mContext); // async
  314. if (!contentsResult.isSuccess()) {
  315. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  316. mConflictsFound++;
  317. } else {
  318. mFailsInFavouritesFound++;
  319. if (contentsResult.getException() != null) {
  320. Log_OC.e(TAG, "Error while synchronizing favourites : "
  321. + contentsResult.getLogMessage(), contentsResult.getException());
  322. } else {
  323. Log_OC.e(TAG, "Error while synchronizing favourites : "
  324. + contentsResult.getLogMessage());
  325. }
  326. }
  327. } // won't let these fails break the synchronization process
  328. }
  329. }
  330. public boolean isMultiStatus(int status) {
  331. return (status == HttpStatus.SC_MULTI_STATUS);
  332. }
  333. /**
  334. * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
  335. *
  336. * @param remote remote file read from the server (remote file or folder).
  337. * @return New OCFile instance representing the remote resource described by we.
  338. */
  339. private OCFile fillOCFile(RemoteFile remote) {
  340. OCFile file = new OCFile(remote.getRemotePath());
  341. file.setCreationTimestamp(remote.getCreationTimestamp());
  342. file.setFileLength(remote.getLength());
  343. file.setMimetype(remote.getMimeType());
  344. file.setModificationTimestamp(remote.getModifiedTimestamp());
  345. file.setEtag(remote.getEtag());
  346. file.setPermissions(remote.getPermissions());
  347. file.setRemoteId(remote.getRemoteId());
  348. return file;
  349. }
  350. /**
  351. * Checks the storage path of the OCFile received as parameter.
  352. * If it's out of the local ownCloud folder, tries to copy the file inside it.
  353. *
  354. * If the copy fails, the link to the local file is nullified. The account of forgotten
  355. * files is kept in {@link #mForgottenLocalFiles}
  356. *)
  357. * @param file File to check and fix.
  358. */
  359. private void checkAndFixForeignStoragePath(OCFile file) {
  360. String storagePath = file.getStoragePath();
  361. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
  362. if (storagePath != null && !storagePath.equals(expectedPath)) {
  363. /// fix storagePaths out of the local ownCloud folder
  364. File originalFile = new File(storagePath);
  365. if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
  366. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  367. file.setStoragePath(null);
  368. } else {
  369. InputStream in = null;
  370. OutputStream out = null;
  371. try {
  372. File expectedFile = new File(expectedPath);
  373. File expectedParent = expectedFile.getParentFile();
  374. expectedParent.mkdirs();
  375. if (!expectedParent.isDirectory()) {
  376. throw new IOException(
  377. "Unexpected error: parent directory could not be created"
  378. );
  379. }
  380. expectedFile.createNewFile();
  381. if (!expectedFile.isFile()) {
  382. throw new IOException("Unexpected error: target file could not be created");
  383. }
  384. in = new FileInputStream(originalFile);
  385. out = new FileOutputStream(expectedFile);
  386. byte[] buf = new byte[1024];
  387. int len;
  388. while ((len = in.read(buf)) > 0){
  389. out.write(buf, 0, len);
  390. }
  391. file.setStoragePath(expectedPath);
  392. } catch (Exception e) {
  393. Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
  394. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  395. file.setStoragePath(null);
  396. } finally {
  397. try {
  398. if (in != null) in.close();
  399. } catch (Exception e) {
  400. Log_OC.d(TAG, "Weird exception while closing input stream for "
  401. + storagePath + " (ignoring)", e);
  402. }
  403. try {
  404. if (out != null) out.close();
  405. } catch (Exception e) {
  406. Log_OC.d(TAG, "Weird exception while closing output stream for "
  407. + expectedPath + " (ignoring)", e);
  408. }
  409. }
  410. }
  411. }
  412. }
  413. /**
  414. * Scans the default location for saving local copies of files searching for
  415. * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
  416. * parameter.
  417. *
  418. * @param file File to associate a possible 'lost' local file.
  419. */
  420. private void searchForLocalFileInDefaultPath(OCFile file) {
  421. if (file.getStoragePath() == null && !file.isFolder()) {
  422. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  423. if (f.exists()) {
  424. file.setStoragePath(f.getAbsolutePath());
  425. file.setLastSyncDateForData(f.lastModified());
  426. }
  427. }
  428. }
  429. /**
  430. * Requests for a download to the FileDownloader service
  431. *
  432. * @param file OCFile object representing the file to download
  433. */
  434. private void requestForDownloadFile(OCFile file) {
  435. Intent i = new Intent(mContext, FileDownloader.class);
  436. i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
  437. i.putExtra(FileDownloader.EXTRA_FILE, file);
  438. mContext.startService(i);
  439. }
  440. public boolean getRemoteFolderChanged() {
  441. return mRemoteFolderChanged;
  442. }
  443. }