DownloadFileOperation.java 9.5 KB

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