SynchronizeFolderOperation.java 23 KB

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