DownloadFileOperation.java 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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.HashSet;
  24. import java.util.Iterator;
  25. import java.util.Set;
  26. import java.util.concurrent.atomic.AtomicBoolean;
  27. import org.apache.commons.httpclient.HttpException;
  28. import org.apache.commons.httpclient.methods.GetMethod;
  29. import org.apache.http.HttpStatus;
  30. import com.owncloud.android.datamodel.OCFile;
  31. import com.owncloud.android.files.services.FileDownloader;
  32. import com.owncloud.android.operations.RemoteOperation;
  33. import com.owncloud.android.operations.RemoteOperationResult;
  34. import eu.alefzero.webdav.OnDatatransferProgressListener;
  35. import eu.alefzero.webdav.WebdavClient;
  36. import eu.alefzero.webdav.WebdavUtils;
  37. import android.accounts.Account;
  38. import android.util.Log;
  39. import android.webkit.MimeTypeMap;
  40. /**
  41. * Remote operation performing the download of a file to an ownCloud server
  42. *
  43. * @author David A. Velasco
  44. */
  45. public class DownloadFileOperation extends RemoteOperation {
  46. private static final String TAG = DownloadFileOperation.class.getCanonicalName();
  47. private Account mAccount = null;
  48. private OCFile mFile;
  49. private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
  50. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  51. public DownloadFileOperation(Account account, OCFile file) {
  52. if (account == null)
  53. throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
  54. if (file == null)
  55. throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
  56. mAccount = account;
  57. mFile = file;
  58. }
  59. public Account getAccount() {
  60. return mAccount;
  61. }
  62. public OCFile getFile() {
  63. return mFile;
  64. }
  65. public String getSavePath() {
  66. return FileDownloader.getSavePath(mAccount.name) + mFile.getRemotePath();
  67. }
  68. public String getTmpPath() {
  69. return FileDownloader.getTemporalPath(mAccount.name) + mFile.getRemotePath();
  70. }
  71. public String getRemotePath() {
  72. return mFile.getRemotePath();
  73. }
  74. public String getMimeType() {
  75. String mimeType = mFile.getMimetype();
  76. if (mimeType == null || mimeType.length() <= 0) {
  77. try {
  78. mimeType = MimeTypeMap.getSingleton()
  79. .getMimeTypeFromExtension(
  80. mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
  81. } catch (IndexOutOfBoundsException e) {
  82. Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
  83. }
  84. }
  85. if (mimeType == null) {
  86. mimeType = "application/octet-stream";
  87. }
  88. return mimeType;
  89. }
  90. public long getSize() {
  91. return mFile.getFileLength();
  92. }
  93. public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
  94. mDataTransferListeners.add(listener);
  95. }
  96. @Override
  97. protected RemoteOperationResult run(WebdavClient client) {
  98. RemoteOperationResult result = null;
  99. File newFile = null;
  100. boolean moved = false;
  101. /// download will be performed to a temporal file, then moved to the final location
  102. File tmpFile = new File(getTmpPath());
  103. /// perform the download
  104. try {
  105. tmpFile.getParentFile().mkdirs();
  106. int status = downloadFile(client, tmpFile);
  107. if (isSuccess(status)) {
  108. newFile = new File(getSavePath());
  109. newFile.getParentFile().mkdirs();
  110. moved = tmpFile.renameTo(newFile);
  111. }
  112. if (!moved)
  113. result = new RemoteOperationResult(RemoteOperationResult.ResultCode.STORAGE_ERROR_MOVING_FROM_TMP);
  114. else
  115. result = new RemoteOperationResult(isSuccess(status), status);
  116. Log.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
  117. } catch (Exception e) {
  118. result = new RemoteOperationResult(e);
  119. Log.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
  120. }
  121. return result;
  122. }
  123. public boolean isSuccess(int status) {
  124. return (status == HttpStatus.SC_OK);
  125. }
  126. protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
  127. int status = -1;
  128. boolean savedFile = false;
  129. GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
  130. Iterator<OnDatatransferProgressListener> it = null;
  131. FileOutputStream fos = null;
  132. try {
  133. status = client.executeMethod(get);
  134. if (isSuccess(status)) {
  135. targetFile.createNewFile();
  136. BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
  137. fos = new FileOutputStream(targetFile);
  138. long transferred = 0;
  139. byte[] bytes = new byte[4096];
  140. int readResult = 0;
  141. while ((readResult = bis.read(bytes)) != -1) {
  142. synchronized(mCancellationRequested) {
  143. if (mCancellationRequested.get()) {
  144. get.abort();
  145. throw new OperationCancelledException();
  146. }
  147. }
  148. fos.write(bytes, 0, readResult);
  149. transferred += readResult;
  150. it = mDataTransferListeners.iterator();
  151. while (it.hasNext()) {
  152. it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
  153. }
  154. }
  155. savedFile = true;
  156. } else {
  157. client.exhaustResponse(get.getResponseBodyAsStream());
  158. }
  159. } finally {
  160. if (fos != null) fos.close();
  161. if (!savedFile && targetFile.exists()) {
  162. targetFile.delete();
  163. }
  164. get.releaseConnection(); // let the connection available for other methods
  165. }
  166. return status;
  167. }
  168. public void cancel() {
  169. mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
  170. }
  171. }