DownloadFileOperation.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * @author masensio
  6. * Copyright (C) 2015 ownCloud Inc.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License version 2,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package com.owncloud.android.operations;
  22. import android.accounts.Account;
  23. import android.content.Context;
  24. import android.text.TextUtils;
  25. import android.webkit.MimeTypeMap;
  26. import com.nextcloud.client.account.User;
  27. import com.owncloud.android.datamodel.DecryptedFolderMetadata;
  28. import com.owncloud.android.datamodel.FileDataStorageManager;
  29. import com.owncloud.android.datamodel.OCFile;
  30. import com.owncloud.android.lib.common.OwnCloudClient;
  31. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  32. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  33. import com.owncloud.android.lib.common.operations.RemoteOperation;
  34. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  35. import com.owncloud.android.lib.common.utils.Log_OC;
  36. import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation;
  37. import com.owncloud.android.utils.EncryptionUtils;
  38. import com.owncloud.android.utils.FileStorageUtils;
  39. import java.io.File;
  40. import java.io.FileOutputStream;
  41. import java.util.HashSet;
  42. import java.util.Iterator;
  43. import java.util.Set;
  44. import java.util.concurrent.atomic.AtomicBoolean;
  45. /**
  46. * Remote DownloadOperation performing the download of a file to an ownCloud server
  47. */
  48. public class DownloadFileOperation extends RemoteOperation {
  49. private static final String TAG = DownloadFileOperation.class.getSimpleName();
  50. private User user;
  51. private OCFile file;
  52. private String behaviour;
  53. private String etag = "";
  54. private String activityName;
  55. private String packageName;
  56. private Context context;
  57. private Set<OnDatatransferProgressListener> dataTransferListeners = new HashSet<>();
  58. private long modificationTimestamp;
  59. private DownloadFileRemoteOperation downloadOperation;
  60. private final AtomicBoolean cancellationRequested = new AtomicBoolean(false);
  61. public DownloadFileOperation(User user, OCFile file, String behaviour, String activityName,
  62. String packageName, Context context) {
  63. if (user == null) {
  64. throw new IllegalArgumentException("Illegal null user in DownloadFileOperation " +
  65. "creation");
  66. }
  67. if (file == null) {
  68. throw new IllegalArgumentException("Illegal null file in DownloadFileOperation " +
  69. "creation");
  70. }
  71. this.user = user;
  72. this.file = file;
  73. this.behaviour = behaviour;
  74. this.activityName = activityName;
  75. this.packageName = packageName;
  76. this.context = context;
  77. }
  78. public DownloadFileOperation(User user, OCFile file, Context context) {
  79. this(user, file, null, null, null, context);
  80. }
  81. public String getSavePath() {
  82. if (file.getStoragePath() != null) {
  83. File parentFile = new File(file.getStoragePath()).getParentFile();
  84. if (parentFile != null && !parentFile.exists()) {
  85. parentFile.mkdirs();
  86. }
  87. File path = new File(file.getStoragePath()); // re-downloads should be done over the original file
  88. if (path.canWrite() || parentFile != null && parentFile.canWrite()) {
  89. return path.getAbsolutePath();
  90. }
  91. }
  92. return FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), file);
  93. }
  94. public String getTmpPath() {
  95. return FileStorageUtils.getTemporalPath(user.getAccountName()) + file.getRemotePath();
  96. }
  97. public String getTmpFolder() {
  98. return FileStorageUtils.getTemporalPath(user.getAccountName());
  99. }
  100. public String getRemotePath() {
  101. return file.getRemotePath();
  102. }
  103. public String getMimeType() {
  104. String mimeType = file.getMimeType();
  105. if (TextUtils.isEmpty(mimeType)) {
  106. try {
  107. mimeType = MimeTypeMap.getSingleton()
  108. .getMimeTypeFromExtension(
  109. file.getRemotePath().substring(
  110. file.getRemotePath().lastIndexOf('.') + 1));
  111. } catch (IndexOutOfBoundsException e) {
  112. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
  113. file.getRemotePath());
  114. }
  115. }
  116. if (mimeType == null) {
  117. mimeType = "application/octet-stream";
  118. }
  119. return mimeType;
  120. }
  121. public long getSize() {
  122. return file.getFileLength();
  123. }
  124. public long getModificationTimestamp() {
  125. return modificationTimestamp > 0 ? modificationTimestamp : file.getModificationTimestamp();
  126. }
  127. @Override
  128. protected RemoteOperationResult run(OwnCloudClient client) {
  129. /// perform the download
  130. synchronized(cancellationRequested) {
  131. if (cancellationRequested.get()) {
  132. return new RemoteOperationResult(new OperationCancelledException());
  133. }
  134. }
  135. RemoteOperationResult result;
  136. File newFile;
  137. boolean moved;
  138. /// download will be performed to a temporal file, then moved to the final location
  139. File tmpFile = new File(getTmpPath());
  140. String tmpFolder = getTmpFolder();
  141. downloadOperation = new DownloadFileRemoteOperation(file.getRemotePath(), tmpFolder);
  142. Iterator<OnDatatransferProgressListener> listener = dataTransferListeners.iterator();
  143. while (listener.hasNext()) {
  144. downloadOperation.addDatatransferProgressListener(listener.next());
  145. }
  146. result = downloadOperation.execute(client);
  147. if (result.isSuccess()) {
  148. modificationTimestamp = downloadOperation.getModificationTimestamp();
  149. etag = downloadOperation.getEtag();
  150. newFile = new File(getSavePath());
  151. if (!newFile.getParentFile().exists() && !newFile.getParentFile().mkdirs()) {
  152. Log_OC.e(TAG, "Unable to create parent folder " + newFile.getParentFile().getAbsolutePath());
  153. }
  154. // decrypt file
  155. if (file.isEncrypted()) {
  156. FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user, context.getContentResolver());
  157. OCFile parent = fileDataStorageManager.getFileByPath(file.getParentRemotePath());
  158. DecryptedFolderMetadata metadata = EncryptionUtils.downloadFolderMetadata(parent,
  159. client,
  160. context,
  161. user.toPlatformAccount());
  162. if (metadata == null) {
  163. return new RemoteOperationResult(RemoteOperationResult.ResultCode.METADATA_NOT_FOUND);
  164. }
  165. byte[] key = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  166. .get(file.getEncryptedFileName()).getEncrypted().getKey());
  167. byte[] iv = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  168. .get(file.getEncryptedFileName()).getInitializationVector());
  169. byte[] authenticationTag = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  170. .get(file.getEncryptedFileName()).getAuthenticationTag());
  171. try {
  172. byte[] decryptedBytes = EncryptionUtils.decryptFile(tmpFile, key, iv, authenticationTag);
  173. try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile)) {
  174. fileOutputStream.write(decryptedBytes);
  175. }
  176. } catch (Exception e) {
  177. return new RemoteOperationResult(e);
  178. }
  179. }
  180. moved = tmpFile.renameTo(newFile);
  181. newFile.setLastModified(file.getModificationTimestamp());
  182. if (!moved) {
  183. result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
  184. }
  185. }
  186. Log_OC.i(TAG, "Download of " + file.getRemotePath() + " to " + getSavePath() + ": " +
  187. result.getLogMessage());
  188. return result;
  189. }
  190. public void cancel() {
  191. cancellationRequested.set(true); // atomic set; there is no need of synchronizing it
  192. if (downloadOperation != null) {
  193. downloadOperation.cancel();
  194. }
  195. }
  196. public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
  197. synchronized (dataTransferListeners) {
  198. dataTransferListeners.add(listener);
  199. }
  200. }
  201. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
  202. synchronized (dataTransferListeners) {
  203. dataTransferListeners.remove(listener);
  204. }
  205. }
  206. @Deprecated
  207. public Account getAccount() {
  208. return this.user.toPlatformAccount();
  209. }
  210. public User getUser() {
  211. return this.user;
  212. }
  213. public OCFile getFile() {
  214. return this.file;
  215. }
  216. public String getBehaviour() {
  217. return this.behaviour;
  218. }
  219. public String getEtag() {
  220. return this.etag;
  221. }
  222. public String getActivityName() {
  223. return this.activityName;
  224. }
  225. public String getPackageName() {
  226. return this.packageName;
  227. }
  228. }