DownloadFileOperation.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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.content.Context;
  23. import android.text.TextUtils;
  24. import android.webkit.MimeTypeMap;
  25. import com.nextcloud.client.account.User;
  26. import com.owncloud.android.datamodel.DecryptedFolderMetadata;
  27. import com.owncloud.android.datamodel.FileDataStorageManager;
  28. import com.owncloud.android.datamodel.OCFile;
  29. import com.owncloud.android.lib.common.OwnCloudClient;
  30. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  31. import com.owncloud.android.lib.common.operations.OperationCancelledException;
  32. import com.owncloud.android.lib.common.operations.RemoteOperation;
  33. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  34. import com.owncloud.android.lib.common.utils.Log_OC;
  35. import com.owncloud.android.lib.resources.files.DownloadFileRemoteOperation;
  36. import com.owncloud.android.utils.EncryptionUtils;
  37. import com.owncloud.android.utils.FileExportUtils;
  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 DownloadType downloadType;
  57. private Context context;
  58. private Set<OnDatatransferProgressListener> dataTransferListeners = new HashSet<>();
  59. private long modificationTimestamp;
  60. private DownloadFileRemoteOperation downloadOperation;
  61. private final AtomicBoolean cancellationRequested = new AtomicBoolean(false);
  62. public DownloadFileOperation(User user,
  63. OCFile file,
  64. String behaviour,
  65. String activityName,
  66. String packageName,
  67. Context context,
  68. DownloadType downloadType) {
  69. if (user == null) {
  70. throw new IllegalArgumentException("Illegal null user in DownloadFileOperation " +
  71. "creation");
  72. }
  73. if (file == null) {
  74. throw new IllegalArgumentException("Illegal null file in DownloadFileOperation " +
  75. "creation");
  76. }
  77. this.user = user;
  78. this.file = file;
  79. this.behaviour = behaviour;
  80. this.activityName = activityName;
  81. this.packageName = packageName;
  82. this.context = context;
  83. this.downloadType = downloadType;
  84. }
  85. public DownloadFileOperation(User user, OCFile file, Context context) {
  86. this(user, file, null, null, null, context, DownloadType.DOWNLOAD);
  87. }
  88. public String getSavePath() {
  89. if (file.getStoragePath() != null) {
  90. File parentFile = new File(file.getStoragePath()).getParentFile();
  91. if (parentFile != null && !parentFile.exists()) {
  92. parentFile.mkdirs();
  93. }
  94. File path = new File(file.getStoragePath()); // re-downloads should be done over the original file
  95. if (path.canWrite() || parentFile != null && parentFile.canWrite()) {
  96. return path.getAbsolutePath();
  97. }
  98. }
  99. return FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), file);
  100. }
  101. public String getTmpPath() {
  102. return FileStorageUtils.getTemporalPath(user.getAccountName()) + file.getRemotePath();
  103. }
  104. public String getTmpFolder() {
  105. return FileStorageUtils.getTemporalPath(user.getAccountName());
  106. }
  107. public String getRemotePath() {
  108. return file.getRemotePath();
  109. }
  110. public String getMimeType() {
  111. String mimeType = file.getMimeType();
  112. if (TextUtils.isEmpty(mimeType)) {
  113. try {
  114. mimeType = MimeTypeMap.getSingleton()
  115. .getMimeTypeFromExtension(
  116. file.getRemotePath().substring(
  117. file.getRemotePath().lastIndexOf('.') + 1));
  118. } catch (IndexOutOfBoundsException e) {
  119. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " +
  120. file.getRemotePath());
  121. }
  122. }
  123. if (mimeType == null) {
  124. mimeType = "application/octet-stream";
  125. }
  126. return mimeType;
  127. }
  128. public long getSize() {
  129. return file.getFileLength();
  130. }
  131. public long getModificationTimestamp() {
  132. return modificationTimestamp > 0 ? modificationTimestamp : file.getModificationTimestamp();
  133. }
  134. @Override
  135. protected RemoteOperationResult run(OwnCloudClient client) {
  136. /// perform the download
  137. synchronized(cancellationRequested) {
  138. if (cancellationRequested.get()) {
  139. return new RemoteOperationResult(new OperationCancelledException());
  140. }
  141. }
  142. RemoteOperationResult result;
  143. File newFile = null;
  144. boolean moved;
  145. /// download will be performed to a temporal file, then moved to the final location
  146. File tmpFile = new File(getTmpPath());
  147. String tmpFolder = getTmpFolder();
  148. downloadOperation = new DownloadFileRemoteOperation(file.getRemotePath(), tmpFolder);
  149. if (downloadType == DownloadType.DOWNLOAD) {
  150. Iterator<OnDatatransferProgressListener> listener = dataTransferListeners.iterator();
  151. while (listener.hasNext()) {
  152. downloadOperation.addDatatransferProgressListener(listener.next());
  153. }
  154. }
  155. result = downloadOperation.execute(client);
  156. if (result.isSuccess()) {
  157. modificationTimestamp = downloadOperation.getModificationTimestamp();
  158. etag = downloadOperation.getEtag();
  159. if (downloadType == DownloadType.DOWNLOAD) {
  160. newFile = new File(getSavePath());
  161. if (!newFile.getParentFile().exists() && !newFile.getParentFile().mkdirs()) {
  162. Log_OC.e(TAG, "Unable to create parent folder " + newFile.getParentFile().getAbsolutePath());
  163. }
  164. }
  165. // decrypt file
  166. if (file.isEncrypted()) {
  167. FileDataStorageManager fileDataStorageManager = new FileDataStorageManager(user, context.getContentResolver());
  168. OCFile parent = fileDataStorageManager.getFileByPath(file.getParentRemotePath());
  169. DecryptedFolderMetadata metadata = EncryptionUtils.downloadFolderMetadata(parent,
  170. client,
  171. context,
  172. user);
  173. if (metadata == null) {
  174. return new RemoteOperationResult(RemoteOperationResult.ResultCode.METADATA_NOT_FOUND);
  175. }
  176. byte[] key = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  177. .get(file.getEncryptedFileName()).getEncrypted().getKey());
  178. byte[] iv = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  179. .get(file.getEncryptedFileName()).getInitializationVector());
  180. byte[] authenticationTag = EncryptionUtils.decodeStringToBase64Bytes(metadata.getFiles()
  181. .get(file.getEncryptedFileName()).getAuthenticationTag());
  182. try {
  183. byte[] decryptedBytes = EncryptionUtils.decryptFile(tmpFile, key, iv, authenticationTag);
  184. try (FileOutputStream fileOutputStream = new FileOutputStream(tmpFile)) {
  185. fileOutputStream.write(decryptedBytes);
  186. }
  187. } catch (Exception e) {
  188. return new RemoteOperationResult(e);
  189. }
  190. }
  191. if (downloadType == DownloadType.DOWNLOAD) {
  192. moved = tmpFile.renameTo(newFile);
  193. newFile.setLastModified(file.getModificationTimestamp());
  194. if (!moved) {
  195. result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
  196. }
  197. } else if (downloadType == DownloadType.EXPORT) {
  198. new FileExportUtils().exportFile(file.getFileName(),
  199. file.getMimeType(),
  200. context.getContentResolver(),
  201. null,
  202. tmpFile);
  203. if (!tmpFile.delete()) {
  204. Log_OC.e(TAG, "Deletion of " + tmpFile.getAbsolutePath() + " failed!");
  205. }
  206. }
  207. }
  208. Log_OC.i(TAG, "Download of " + file.getRemotePath() + " to " + getSavePath() + ": " +
  209. result.getLogMessage());
  210. return result;
  211. }
  212. public void cancel() {
  213. cancellationRequested.set(true); // atomic set; there is no need of synchronizing it
  214. if (downloadOperation != null) {
  215. downloadOperation.cancel();
  216. }
  217. }
  218. public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
  219. synchronized (dataTransferListeners) {
  220. dataTransferListeners.add(listener);
  221. }
  222. }
  223. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
  224. synchronized (dataTransferListeners) {
  225. dataTransferListeners.remove(listener);
  226. }
  227. }
  228. public User getUser() {
  229. return this.user;
  230. }
  231. public OCFile getFile() {
  232. return this.file;
  233. }
  234. public String getBehaviour() {
  235. return this.behaviour;
  236. }
  237. public String getEtag() {
  238. return this.etag;
  239. }
  240. public String getActivityName() {
  241. return this.activityName;
  242. }
  243. public String getPackageName() {
  244. return this.packageName;
  245. }
  246. public DownloadType getDownloadType() {
  247. return downloadType;
  248. }
  249. }