DownloadFileOperation.java 12 KB

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