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