SynchronizeFolderOperation.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 as published by
  6. * the Free Software Foundation, either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.operations;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.OutputStream;
  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 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.util.Log;
  35. import com.owncloud.android.Log_OC;
  36. import com.owncloud.android.datamodel.DataStorageManager;
  37. import com.owncloud.android.datamodel.OCFile;
  38. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  39. import com.owncloud.android.utils.FileStorageUtils;
  40. import eu.alefzero.webdav.WebdavClient;
  41. import eu.alefzero.webdav.WebdavEntry;
  42. import eu.alefzero.webdav.WebdavUtils;
  43. /**
  44. * Remote operation performing the synchronization a the contents of a remote folder with the local database
  45. *
  46. * @author David A. Velasco
  47. */
  48. public class SynchronizeFolderOperation extends RemoteOperation {
  49. private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
  50. /** Remote folder to synchronize */
  51. private String mRemotePath;
  52. /** Timestamp for the synchronization in progress */
  53. private long mCurrentSyncTime;
  54. /** Id of the folder to synchronize in the local database */
  55. private long mParentId;
  56. /** Access to the local database */
  57. private DataStorageManager mStorageManager;
  58. /** Account where the file to synchronize belongs */
  59. private Account mAccount;
  60. /** Android context; necessary to send requests to the download service; maybe something to refactor */
  61. private Context mContext;
  62. /** Files and folders contained in the synchronized folder */
  63. private List<OCFile> mChildren;
  64. private int mConflictsFound;
  65. private int mFailsInFavouritesFound;
  66. private Map<String, String> mForgottenLocalFiles;
  67. public SynchronizeFolderOperation( String remotePath,
  68. long currentSyncTime,
  69. long parentId,
  70. DataStorageManager dataStorageManager,
  71. Account account,
  72. Context context ) {
  73. mRemotePath = remotePath;
  74. mCurrentSyncTime = currentSyncTime;
  75. mParentId = parentId;
  76. mStorageManager = dataStorageManager;
  77. mAccount = account;
  78. mContext = context;
  79. mForgottenLocalFiles = new HashMap<String, String>();
  80. }
  81. public int getConflictsFound() {
  82. return mConflictsFound;
  83. }
  84. public int getFailsInFavouritesFound() {
  85. return mFailsInFavouritesFound;
  86. }
  87. public Map<String, String> getForgottenLocalFiles() {
  88. return mForgottenLocalFiles;
  89. }
  90. /**
  91. * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
  92. *
  93. * @return List of files and folders contained in the synchronized folder.
  94. */
  95. public List<OCFile> getChildren() {
  96. return mChildren;
  97. }
  98. @Override
  99. protected RemoteOperationResult run(WebdavClient client) {
  100. RemoteOperationResult result = null;
  101. mFailsInFavouritesFound = 0;
  102. mConflictsFound = 0;
  103. mForgottenLocalFiles.clear();
  104. // code before in FileSyncAdapter.fetchData
  105. PropFindMethod query = null;
  106. try {
  107. Log_OC.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
  108. // remote request
  109. query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
  110. int status = client.executeMethod(query);
  111. // check and process response - /// TODO take into account all the possible status per child-resource
  112. if (isMultiStatus(status)) {
  113. MultiStatus resp = query.getResponseBodyAsMultiStatus();
  114. // synchronize properties of the parent folder, if necessary
  115. if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
  116. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
  117. OCFile parent = fillOCFile(we);
  118. mStorageManager.saveFile(parent);
  119. mParentId = parent.getFileId();
  120. }
  121. // read contents in folder
  122. List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
  123. List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
  124. for (int i = 1; i < resp.getResponses().length; ++i) {
  125. /// new OCFile instance with the data from the server
  126. WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
  127. OCFile file = fillOCFile(we);
  128. /// set data about local state, keeping unchanged former data if existing
  129. file.setLastSyncDateForProperties(mCurrentSyncTime);
  130. OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
  131. if (oldFile != null) {
  132. file.setKeepInSync(oldFile.keepInSync());
  133. file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
  134. file.setModificationTimestampAtLastSyncForData(oldFile.getModificationTimestampAtLastSyncForData()); // must be kept unchanged when the file contents are not updated
  135. checkAndFixForeignStoragePath(oldFile);
  136. file.setStoragePath(oldFile.getStoragePath());
  137. }
  138. /// scan default location if local copy of file is not linked in OCFile instance
  139. if (file.getStoragePath() == null && !file.isDirectory()) {
  140. File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
  141. if (f.exists()) {
  142. file.setStoragePath(f.getAbsolutePath());
  143. file.setLastSyncDateForData(f.lastModified());
  144. }
  145. }
  146. /// prepare content synchronization for kept-in-sync files
  147. if (file.keepInSync()) {
  148. SynchronizeFileOperation operation = new SynchronizeFileOperation( oldFile,
  149. file,
  150. mStorageManager,
  151. mAccount,
  152. true,
  153. false,
  154. mContext
  155. );
  156. filesToSyncContents.add(operation);
  157. }
  158. updatedFiles.add(file);
  159. }
  160. // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
  161. mStorageManager.saveFiles(updatedFiles);
  162. // request for the synchronization of files AFTER saving last properties
  163. SynchronizeFileOperation op = null;
  164. RemoteOperationResult contentsResult = null;
  165. for (int i=0; i < filesToSyncContents.size(); i++) {
  166. op = filesToSyncContents.get(i);
  167. contentsResult = op.execute(client); // returns without waiting for upload or download finishes
  168. if (!contentsResult.isSuccess()) {
  169. if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
  170. mConflictsFound++;
  171. } else {
  172. mFailsInFavouritesFound++;
  173. if (contentsResult.getException() != null) {
  174. Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
  175. } else {
  176. Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
  177. }
  178. }
  179. } // won't let these fails break the synchronization process
  180. }
  181. // removal of obsolete files
  182. mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
  183. OCFile file;
  184. String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
  185. for (int i=0; i < mChildren.size(); ) {
  186. file = mChildren.get(i);
  187. if (file.getLastSyncDateForProperties() != mCurrentSyncTime) {
  188. Log_OC.d(TAG, "removing file: " + file);
  189. mStorageManager.removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
  190. mChildren.remove(i);
  191. } else {
  192. i++;
  193. }
  194. }
  195. } else {
  196. client.exhaustResponse(query.getResponseBodyAsStream());
  197. }
  198. // prepare result object
  199. if (isMultiStatus(status)) {
  200. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  201. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
  202. } else {
  203. result = new RemoteOperationResult(true, status);
  204. }
  205. } else {
  206. result = new RemoteOperationResult(false, status);
  207. }
  208. Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
  209. } catch (Exception e) {
  210. result = new RemoteOperationResult(e);
  211. Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
  212. } finally {
  213. if (query != null)
  214. query.releaseConnection(); // let the connection available for other methods
  215. }
  216. return result;
  217. }
  218. public boolean isMultiStatus(int status) {
  219. return (status == HttpStatus.SC_MULTI_STATUS);
  220. }
  221. /**
  222. * Creates and populates a new {@link OCFile} object with the data read from the server.
  223. *
  224. * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
  225. * @return New OCFile instance representing the remote resource described by we.
  226. */
  227. private OCFile fillOCFile(WebdavEntry we) {
  228. OCFile file = new OCFile(we.decodedPath());
  229. file.setCreationTimestamp(we.createTimestamp());
  230. file.setFileLength(we.contentLength());
  231. file.setMimetype(we.contentType());
  232. file.setModificationTimestamp(we.modifiedTimestamp());
  233. file.setParentId(mParentId);
  234. return file;
  235. }
  236. /**
  237. * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
  238. * tries to copy the file inside it.
  239. *
  240. * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
  241. * {@link #mForgottenLocalFiles}
  242. *
  243. * @param file File to check and fix.
  244. */
  245. private void checkAndFixForeignStoragePath(OCFile file) {
  246. String storagePath = file.getStoragePath();
  247. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
  248. if (storagePath != null && !storagePath.equals(expectedPath)) {
  249. /// fix storagePaths out of the local ownCloud folder
  250. File originalFile = new File(storagePath);
  251. if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
  252. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  253. file.setStoragePath(null);
  254. } else {
  255. InputStream in = null;
  256. OutputStream out = null;
  257. try {
  258. File expectedFile = new File(expectedPath);
  259. File expectedParent = expectedFile.getParentFile();
  260. expectedParent.mkdirs();
  261. if (!expectedParent.isDirectory()) {
  262. throw new IOException("Unexpected error: parent directory could not be created");
  263. }
  264. expectedFile.createNewFile();
  265. if (!expectedFile.isFile()) {
  266. throw new IOException("Unexpected error: target file could not be created");
  267. }
  268. in = new FileInputStream(originalFile);
  269. out = new FileOutputStream(expectedFile);
  270. byte[] buf = new byte[1024];
  271. int len;
  272. while ((len = in.read(buf)) > 0){
  273. out.write(buf, 0, len);
  274. }
  275. file.setStoragePath(expectedPath);
  276. } catch (Exception e) {
  277. Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
  278. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  279. file.setStoragePath(null);
  280. } finally {
  281. try {
  282. if (in != null) in.close();
  283. } catch (Exception e) {
  284. Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
  285. }
  286. try {
  287. if (out != null) out.close();
  288. } catch (Exception e) {
  289. Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
  290. }
  291. }
  292. }
  293. }
  294. }
  295. }