SynchronizeFolderOperation.java 16 KB

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