DownloadFileOperation.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.operations;
  19. import java.io.BufferedInputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.util.Date;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.Set;
  27. import java.util.concurrent.atomic.AtomicBoolean;
  28. import org.apache.commons.httpclient.Header;
  29. import org.apache.commons.httpclient.HttpException;
  30. import org.apache.commons.httpclient.methods.GetMethod;
  31. import org.apache.http.HttpStatus;
  32. import com.owncloud.android.datamodel.OCFile;
  33. import com.owncloud.android.operations.RemoteOperation;
  34. import com.owncloud.android.operations.RemoteOperationResult;
  35. import com.owncloud.android.utils.FileStorageUtils;
  36. import eu.alefzero.webdav.OnDatatransferProgressListener;
  37. import eu.alefzero.webdav.WebdavClient;
  38. import eu.alefzero.webdav.WebdavUtils;
  39. import android.accounts.Account;
  40. import android.util.Log;
  41. import android.webkit.MimeTypeMap;
  42. /**
  43. * Remote operation performing the download of a file to an ownCloud server
  44. *
  45. * @author David A. Velasco
  46. */
  47. public class DownloadFileOperation extends RemoteOperation {
  48. private static final String TAG = DownloadFileOperation.class.getSimpleName();
  49. private Account mAccount;
  50. private OCFile mFile;
  51. private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
  52. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  53. private long mModificationTimestamp = 0;
  54. public DownloadFileOperation(Account account, OCFile file) {
  55. if (account == null)
  56. throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
  57. if (file == null)
  58. throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
  59. mAccount = account;
  60. mFile = file;
  61. }
  62. public Account getAccount() {
  63. return mAccount;
  64. }
  65. public OCFile getFile() {
  66. return mFile;
  67. }
  68. public String getSavePath() {
  69. String path = mFile.getStoragePath(); // re-downloads should be done over the original file
  70. if (path != null && path.length() > 0) {
  71. return path;
  72. }
  73. return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
  74. }
  75. public String getTmpPath() {
  76. return FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  77. }
  78. public String getRemotePath() {
  79. return mFile.getRemotePath();
  80. }
  81. public String getMimeType() {
  82. String mimeType = mFile.getMimetype();
  83. if (mimeType == null || mimeType.length() <= 0) {
  84. try {
  85. mimeType = MimeTypeMap.getSingleton()
  86. .getMimeTypeFromExtension(
  87. mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
  88. } catch (IndexOutOfBoundsException e) {
  89. Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
  90. }
  91. }
  92. if (mimeType == null) {
  93. mimeType = "application/octet-stream";
  94. }
  95. return mimeType;
  96. }
  97. public long getSize() {
  98. return mFile.getFileLength();
  99. }
  100. public long getModificationTimestamp() {
  101. return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp();
  102. }
  103. public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
  104. mDataTransferListeners.add(listener);
  105. }
  106. @Override
  107. protected RemoteOperationResult run(WebdavClient client) {
  108. RemoteOperationResult result = null;
  109. File newFile = null;
  110. boolean moved = true;
  111. /// download will be performed to a temporal file, then moved to the final location
  112. File tmpFile = new File(getTmpPath());
  113. /// perform the download
  114. try {
  115. tmpFile.getParentFile().mkdirs();
  116. int status = downloadFile(client, tmpFile);
  117. if (isSuccess(status)) {
  118. newFile = new File(getSavePath());
  119. newFile.getParentFile().mkdirs();
  120. moved = tmpFile.renameTo(newFile);
  121. }
  122. if (!moved)
  123. result = new RemoteOperationResult(RemoteOperationResult.ResultCode.STORAGE_ERROR_MOVING_FROM_TMP);
  124. else
  125. result = new RemoteOperationResult(isSuccess(status), status);
  126. Log.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
  127. } catch (Exception e) {
  128. result = new RemoteOperationResult(e);
  129. Log.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
  130. }
  131. return result;
  132. }
  133. public boolean isSuccess(int status) {
  134. return (status == HttpStatus.SC_OK);
  135. }
  136. protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
  137. int status = -1;
  138. boolean savedFile = false;
  139. GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
  140. Iterator<OnDatatransferProgressListener> it = null;
  141. FileOutputStream fos = null;
  142. try {
  143. status = client.executeMethod(get);
  144. if (isSuccess(status)) {
  145. targetFile.createNewFile();
  146. BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
  147. fos = new FileOutputStream(targetFile);
  148. long transferred = 0;
  149. byte[] bytes = new byte[4096];
  150. int readResult = 0;
  151. while ((readResult = bis.read(bytes)) != -1) {
  152. synchronized(mCancellationRequested) {
  153. if (mCancellationRequested.get()) {
  154. get.abort();
  155. throw new OperationCancelledException();
  156. }
  157. }
  158. fos.write(bytes, 0, readResult);
  159. transferred += readResult;
  160. it = mDataTransferListeners.iterator();
  161. while (it.hasNext()) {
  162. it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
  163. }
  164. }
  165. savedFile = true;
  166. Header modificationTime = get.getResponseHeader("Last-Modified");
  167. if (modificationTime != null) {
  168. Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
  169. mModificationTimestamp = (d != null) ? d.getTime() : 0;
  170. }
  171. } else {
  172. client.exhaustResponse(get.getResponseBodyAsStream());
  173. }
  174. } finally {
  175. if (fos != null) fos.close();
  176. if (!savedFile && targetFile.exists()) {
  177. targetFile.delete();
  178. }
  179. get.releaseConnection(); // let the connection available for other methods
  180. }
  181. return status;
  182. }
  183. public void cancel() {
  184. mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
  185. }
  186. }