SynchronizeFileOperation.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * @author masensio
  6. * Copyright (C) 2012 Bartek Przybylski
  7. * Copyright (C) 2015 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.owncloud.android.operations;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.text.TextUtils;
  25. import com.nextcloud.client.account.User;
  26. import com.owncloud.android.datamodel.FileDataStorageManager;
  27. import com.owncloud.android.datamodel.OCFile;
  28. import com.owncloud.android.files.services.FileDownloader;
  29. import com.owncloud.android.files.services.FileUploader;
  30. import com.owncloud.android.files.services.NameCollisionPolicy;
  31. import com.owncloud.android.lib.common.OwnCloudClient;
  32. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  33. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  34. import com.owncloud.android.lib.common.utils.Log_OC;
  35. import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
  36. import com.owncloud.android.lib.resources.files.model.RemoteFile;
  37. import com.owncloud.android.operations.common.SyncOperation;
  38. import com.owncloud.android.utils.FileStorageUtils;
  39. /**
  40. * Remote operation performing the read of remote file in the ownCloud server.
  41. */
  42. public class SynchronizeFileOperation extends SyncOperation {
  43. private static final String TAG = SynchronizeFileOperation.class.getSimpleName();
  44. private OCFile mLocalFile;
  45. private String mRemotePath;
  46. private OCFile mServerFile;
  47. private User mUser;
  48. private boolean mSyncFileContents;
  49. private Context mContext;
  50. private boolean mTransferWasRequested;
  51. /**
  52. * When 'false', uploads to the server are not done; only downloads or conflict detection.
  53. * This is a temporal field.
  54. * TODO Remove when 'folder synchronization' replaces 'folder download'.
  55. */
  56. private boolean mAllowUploads;
  57. /**
  58. * Constructor for "full synchronization mode".
  59. * <p/>
  60. * Uses remotePath to retrieve all the data both in local cache and in the remote OC server
  61. * when the operation is executed, instead of reusing {@link OCFile} instances.
  62. * <p/>
  63. * Useful for direct synchronization of a single file.
  64. *
  65. * @param remotePath remote path of the file
  66. * @param user Nextcloud user owning the file.
  67. * @param syncFileContents When 'true', transference of data will be started by the
  68. * operation if needed and no conflict is detected.
  69. * @param context Android context; needed to start transfers.
  70. */
  71. public SynchronizeFileOperation(
  72. String remotePath,
  73. User user,
  74. boolean syncFileContents,
  75. Context context,
  76. FileDataStorageManager storageManager) {
  77. super(storageManager);
  78. mRemotePath = remotePath;
  79. mLocalFile = null;
  80. mServerFile = null;
  81. mUser = user;
  82. mSyncFileContents = syncFileContents;
  83. mContext = context;
  84. mAllowUploads = true;
  85. }
  86. /**
  87. * Constructor allowing to reuse {@link OCFile} instances just queried from local cache or
  88. * from remote OC server.
  89. *
  90. * Useful to include this operation as part of the synchronization of a folder
  91. * (or a full account), avoiding the repetition of fetch operations (both in local database
  92. * or remote server).
  93. *
  94. * At least one of localFile or serverFile MUST NOT BE NULL. If you don't have none of them,
  95. * use the other constructor.
  96. *
  97. * @param localFile Data of file (just) retrieved from local cache/database.
  98. * @param serverFile Data of file (just) retrieved from a remote server. If null,
  99. * will be retrieved from network by the operation when executed.
  100. * @param user Nextcloud user owning the file.
  101. * @param syncFileContents When 'true', transference of data will be started by the
  102. * operation if needed and no conflict is detected.
  103. * @param context Android context; needed to start transfers.
  104. */
  105. public SynchronizeFileOperation(
  106. OCFile localFile,
  107. OCFile serverFile,
  108. User user,
  109. boolean syncFileContents,
  110. Context context,
  111. FileDataStorageManager storageManager) {
  112. super(storageManager);
  113. mLocalFile = localFile;
  114. mServerFile = serverFile;
  115. if (mLocalFile != null) {
  116. mRemotePath = mLocalFile.getRemotePath();
  117. if (mServerFile != null && !mServerFile.getRemotePath().equals(mRemotePath)) {
  118. throw new IllegalArgumentException("serverFile and localFile do not correspond" +
  119. " to the same OC file");
  120. }
  121. } else if (mServerFile != null) {
  122. mRemotePath = mServerFile.getRemotePath();
  123. } else {
  124. throw new IllegalArgumentException("Both serverFile and localFile are NULL");
  125. }
  126. mUser = user;
  127. mSyncFileContents = syncFileContents;
  128. mContext = context;
  129. mAllowUploads = true;
  130. }
  131. /**
  132. * Temporal constructor.
  133. *
  134. * Extends the previous one to allow constrained synchronizations where uploads are never
  135. * performed - only downloads or conflict detection.
  136. *
  137. * Do not use unless you are involved in 'folder synchronization' or 'folder download' work
  138. * in progress.
  139. *
  140. * TODO Remove when 'folder synchronization' replaces 'folder download'.
  141. *
  142. * @param localFile Data of file (just) retrieved from local cache/database.
  143. * MUSTN't be null.
  144. * @param serverFile Data of file (just) retrieved from a remote server.
  145. * If null, will be retrieved from network by the operation
  146. * when executed.
  147. * @param user Nextcloud user owning the file.
  148. * @param syncFileContents When 'true', transference of data will be started by the
  149. * operation if needed and no conflict is detected.
  150. * @param allowUploads When 'false', uploads to the server are not done;
  151. * only downloads or conflict detection.
  152. * @param context Android context; needed to start transfers.
  153. */
  154. public SynchronizeFileOperation(
  155. OCFile localFile,
  156. OCFile serverFile,
  157. User user,
  158. boolean syncFileContents,
  159. boolean allowUploads,
  160. Context context,
  161. FileDataStorageManager storageManager) {
  162. this(localFile, serverFile, user, syncFileContents, context, storageManager);
  163. mAllowUploads = allowUploads;
  164. }
  165. @Override
  166. protected RemoteOperationResult run(OwnCloudClient client) {
  167. RemoteOperationResult result = null;
  168. mTransferWasRequested = false;
  169. if (mLocalFile == null) {
  170. // Get local file from the DB
  171. mLocalFile = getStorageManager().getFileByPath(mRemotePath);
  172. }
  173. if (!mLocalFile.isDown()) {
  174. /// easy decision
  175. requestForDownload(mLocalFile);
  176. result = new RemoteOperationResult(ResultCode.OK);
  177. } else {
  178. /// local copy in the device -> need to think a bit more before do anything
  179. if (mServerFile == null) {
  180. ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
  181. result = operation.execute(client);
  182. if (result.isSuccess()) {
  183. mServerFile = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
  184. mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
  185. } else if (result.getCode() != ResultCode.FILE_NOT_FOUND) {
  186. return result;
  187. }
  188. }
  189. if (mServerFile != null) {
  190. /// check changes in server and local file
  191. boolean serverChanged;
  192. if (TextUtils.isEmpty(mLocalFile.getEtag())) {
  193. // file uploaded (null) or downloaded ("") before upgrade to version 1.8.0; check the old condition
  194. serverChanged = mServerFile.getModificationTimestamp() !=
  195. mLocalFile.getModificationTimestampAtLastSyncForData();
  196. } else {
  197. serverChanged = !mServerFile.getEtag().equals(mLocalFile.getEtag());
  198. }
  199. boolean localChanged =
  200. mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData();
  201. /// decide action to perform depending upon changes
  202. //if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
  203. if (localChanged && serverChanged) {
  204. result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
  205. getStorageManager().saveConflict(mLocalFile, mServerFile.getEtag());
  206. } else if (localChanged) {
  207. if (mSyncFileContents && mAllowUploads) {
  208. requestForUpload(mLocalFile);
  209. // the local update of file properties will be done by the FileUploader
  210. // service when the upload finishes
  211. } else {
  212. // NOTHING TO DO HERE: updating the properties of the file in the server
  213. // without uploading the contents would be stupid;
  214. // So, an instance of SynchronizeFileOperation created with
  215. // syncFileContents == false is completely useless when we suspect
  216. // that an upload is necessary (for instance, in FileObserverService).
  217. Log_OC.d(TAG, "Nothing to do here");
  218. }
  219. result = new RemoteOperationResult(ResultCode.OK);
  220. } else if (serverChanged) {
  221. mLocalFile.setRemoteId(mServerFile.getRemoteId());
  222. if (mSyncFileContents) {
  223. requestForDownload(mLocalFile); // local, not server; we won't to keep
  224. // the value of favorite!
  225. // the update of local data will be done later by the FileUploader
  226. // service when the upload finishes
  227. } else {
  228. // TODO CHECK: is this really useful in some point in the code?
  229. mServerFile.setFavorite(mLocalFile.isFavorite());
  230. mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
  231. mServerFile.setStoragePath(mLocalFile.getStoragePath());
  232. mServerFile.setParentId(mLocalFile.getParentId());
  233. mServerFile.setEtag(mLocalFile.getEtag());
  234. getStorageManager().saveFile(mServerFile);
  235. }
  236. result = new RemoteOperationResult(ResultCode.OK);
  237. } else {
  238. // nothing changed, nothing to do
  239. result = new RemoteOperationResult(ResultCode.OK);
  240. }
  241. // safe blanket: sync'ing a not in-conflict file will clean wrong conflict markers in ancestors
  242. if (result.getCode() != ResultCode.SYNC_CONFLICT) {
  243. getStorageManager().saveConflict(mLocalFile, null);
  244. }
  245. } else {
  246. // remote file does not exist, deleting local copy
  247. boolean deleteResult = getStorageManager().removeFile(mLocalFile, true, true);
  248. if (deleteResult) {
  249. result = new RemoteOperationResult(ResultCode.FILE_NOT_FOUND);
  250. } else {
  251. Log_OC.e(TAG, "Removal of local copy failed (remote file does not exist any longer).");
  252. }
  253. }
  254. }
  255. Log_OC.i(TAG, "Synchronizing " + mUser.getAccountName() + ", file " + mLocalFile.getRemotePath() +
  256. ": " + result.getLogMessage());
  257. return result;
  258. }
  259. /**
  260. * Requests for an upload to the FileUploader service
  261. *
  262. * @param file OCFile object representing the file to upload
  263. */
  264. private void requestForUpload(OCFile file) {
  265. FileUploader.uploadUpdateFile(
  266. mContext,
  267. mUser,
  268. file,
  269. FileUploader.LOCAL_BEHAVIOUR_MOVE,
  270. NameCollisionPolicy.OVERWRITE
  271. );
  272. mTransferWasRequested = true;
  273. }
  274. /**
  275. * Requests for a download to the FileDownloader service
  276. *
  277. * @param file OCFile object representing the file to download
  278. */
  279. private void requestForDownload(OCFile file) {
  280. Intent i = new Intent(mContext, FileDownloader.class);
  281. i.putExtra(FileDownloader.EXTRA_USER, mUser);
  282. i.putExtra(FileDownloader.EXTRA_FILE, file);
  283. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  284. mContext.startForegroundService(i);
  285. } else {
  286. mContext.startService(i);
  287. }
  288. mTransferWasRequested = true;
  289. }
  290. public boolean transferWasRequested() {
  291. return mTransferWasRequested;
  292. }
  293. public OCFile getLocalFile() {
  294. return mLocalFile;
  295. }
  296. }