SynchronizeFolderOperation.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  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 3 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.datamodel.DataStorageManager;
  36. import com.owncloud.android.datamodel.OCFile;
  37. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  38. import com.owncloud.android.utils.FileStorageUtils;
  39. import eu.alefzero.webdav.WebdavClient;
  40. import eu.alefzero.webdav.WebdavEntry;
  41. import eu.alefzero.webdav.WebdavUtils;
  42. /**
  43. * Remote operation performing the synchronization a the contents of a remote folder with the local database
  44. *
  45. * @author David A. Velasco
  46. */
  47. public class SynchronizeFolderOperation extends RemoteOperation {
  48. private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
  49. /** Remote folder to synchronize */
  50. private String mRemotePath;
  51. /** Timestamp for the synchronization in progress */
  52. private long mCurrentSyncTime;
  53. /** Id of the folder to synchronize in the local database */
  54. private long mParentId;
  55. /** Access to the local database */
  56. private DataStorageManager mStorageManager;
  57. /** Account where the file to synchronize belongs */
  58. private Account mAccount;
  59. /** Android context; necessary to send requests to the download service; maybe something to refactor */
  60. private Context mContext;
  61. /** Files and folders contained in the synchronized folder */
  62. private List<OCFile> mChildren;
  63. private int mConflictsFound;
  64. private int mFailsInFavouritesFound;
  65. private Map<String, String> mForgottenLocalFiles;
  66. public SynchronizeFolderOperation( String remotePath,
  67. long currentSyncTime,
  68. long parentId,
  69. DataStorageManager dataStorageManager,
  70. Account account,
  71. Context context ) {
  72. mRemotePath = remotePath;
  73. mCurrentSyncTime = currentSyncTime;
  74. mParentId = parentId;
  75. mStorageManager = dataStorageManager;
  76. mAccount = account;
  77. mContext = context;
  78. mForgottenLocalFiles = new HashMap<String, String>();
  79. }
  80. public int getConflictsFound() {
  81. return mConflictsFound;
  82. }
  83. public int getFailsInFavouritesFound() {
  84. return mFailsInFavouritesFound;
  85. }
  86. public Map<String, String> getForgottenLocalFiles() {
  87. return mForgottenLocalFiles;
  88. }
  89. /**
  90. * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
  91. *
  92. * @return List of files and folders contained in the synchronized folder.
  93. */
  94. public List<OCFile> getChildren() {
  95. return mChildren;
  96. }
  97. @Override
  98. protected RemoteOperationResult run(WebdavClient client) {
  99. RemoteOperationResult result = null;
  100. mFailsInFavouritesFound = 0;
  101. mConflictsFound = 0;
  102. mForgottenLocalFiles.clear();
  103. // code before in FileSyncAdapter.fetchData
  104. PropFindMethod query = null;
  105. try {
  106. Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);
  107. // remote request
  108. query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
  109. int status = client.executeMethod(query);
  110. // check and process response - /// TODO take into account all the possible status per child-resource
  111. if (isMultiStatus(status)) {
  112. MultiStatus resp = query.getResponseBodyAsMultiStatus();
  113. // synchronize properties of the parent folder, if necessary
  114. if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
  115. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
  116. OCFile parent = fillOCFile(we);
  117. mStorageManager.saveFile(parent);
  118. mParentId = parent.getFileId();
  119. }
  120. // read contents in folder
  121. List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
  122. List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
  123. for (int i = 1; i < resp.getResponses().length; ++i) {
  124. /// new OCFile instance with the data from the server
  125. WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
  126. OCFile file = fillOCFile(we);
  127. /// set data about local state, keeping unchanged former data if existing
  128. file.setLastSyncDateForProperties(mCurrentSyncTime);
  129. OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
  130. if (oldFile != null) {
  131. file.setKeepInSync(oldFile.keepInSync());
  132. file.setLastSyncDateForData(oldFile.getLastSyncDateForData());
  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.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
  173. } else {
  174. Log.d(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.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);
  202. }
  203. } else {
  204. result = new RemoteOperationResult(false, status);
  205. }
  206. Log.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
  207. } catch (Exception e) {
  208. result = new RemoteOperationResult(e);
  209. Log.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
  210. } finally {
  211. if (query != null)
  212. query.releaseConnection(); // let the connection available for other methods
  213. }
  214. return result;
  215. }
  216. public boolean isMultiStatus(int status) {
  217. return (status == HttpStatus.SC_MULTI_STATUS);
  218. }
  219. /**
  220. * Creates and populates a new {@link OCFile} object with the data read from the server.
  221. *
  222. * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder).
  223. * @return New OCFile instance representing the remote resource described by we.
  224. */
  225. private OCFile fillOCFile(WebdavEntry we) {
  226. OCFile file = new OCFile(we.decodedPath());
  227. file.setCreationTimestamp(we.createTimestamp());
  228. file.setFileLength(we.contentLength());
  229. file.setMimetype(we.contentType());
  230. file.setModificationTimestamp(we.modifiedTimestamp());
  231. file.setParentId(mParentId);
  232. return file;
  233. }
  234. /**
  235. * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
  236. * tries to copy the file inside it.
  237. *
  238. * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
  239. * {@link #mForgottenLocalFiles}
  240. *
  241. * @param file File to check and fix.
  242. */
  243. private void checkAndFixForeignStoragePath(OCFile file) {
  244. String storagePath = file.getStoragePath();
  245. String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
  246. if (storagePath != null && !storagePath.equals(expectedPath)) {
  247. /// fix storagePaths out of the local ownCloud folder
  248. File originalFile = new File(storagePath);
  249. if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
  250. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  251. file.setStoragePath(null);
  252. } else {
  253. InputStream in = null;
  254. OutputStream out = null;
  255. try {
  256. File expectedFile = new File(expectedPath);
  257. File expectedParent = expectedFile.getParentFile();
  258. expectedParent.mkdirs();
  259. if (!expectedParent.isDirectory()) {
  260. throw new IOException("Unexpected error: parent directory could not be created");
  261. }
  262. expectedFile.createNewFile();
  263. if (!expectedFile.isFile()) {
  264. throw new IOException("Unexpected error: target file could not be created");
  265. }
  266. in = new FileInputStream(originalFile);
  267. out = new FileOutputStream(expectedFile);
  268. byte[] buf = new byte[1024];
  269. int len;
  270. while ((len = in.read(buf)) > 0){
  271. out.write(buf, 0, len);
  272. }
  273. file.setStoragePath(expectedPath);
  274. } catch (Exception e) {
  275. Log.e(TAG, "Exception while copying foreign file " + expectedPath, e);
  276. mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
  277. file.setStoragePath(null);
  278. } finally {
  279. try {
  280. if (in != null) in.close();
  281. } catch (Exception e) {
  282. Log.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
  283. }
  284. try {
  285. if (out != null) out.close();
  286. } catch (Exception e) {
  287. Log.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
  288. }
  289. }
  290. }
  291. }
  292. }
  293. }