Merge pull request #294 from owncloud/setup_buttons
[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
42 import eu.alefzero.webdav.OnDatatransferProgressListener;
43 import eu.alefzero.webdav.WebdavClient;
44 import eu.alefzero.webdav.WebdavUtils;
45 import android.accounts.Account;
46 import android.webkit.MimeTypeMap;
47
48 /**
49 * Remote operation performing the download of a file to an ownCloud server
50 *
51 * @author David A. Velasco
52 */
53 public class DownloadFileOperation extends RemoteOperation {
54
55 private static final String TAG = DownloadFileOperation.class.getSimpleName();
56
57 private Account mAccount;
58 private OCFile mFile;
59 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
60 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
61 private long mModificationTimestamp = 0;
62 private GetMethod mGet;
63
64
65 public DownloadFileOperation(Account account, OCFile file) {
66 if (account == null)
67 throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
68 if (file == null)
69 throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
70
71 mAccount = account;
72 mFile = file;
73 }
74
75
76 public Account getAccount() {
77 return mAccount;
78 }
79
80 public OCFile getFile() {
81 return mFile;
82 }
83
84 public String getSavePath() {
85 String path = mFile.getStoragePath(); // re-downloads should be done over the original file
86 if (path != null && path.length() > 0) {
87 return path;
88 }
89 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
90 }
91
92 public String getTmpPath() {
93 return FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
94 }
95
96 public String getRemotePath() {
97 return mFile.getRemotePath();
98 }
99
100 public String getMimeType() {
101 String mimeType = mFile.getMimetype();
102 if (mimeType == null || mimeType.length() <= 0) {
103 try {
104 mimeType = MimeTypeMap.getSingleton()
105 .getMimeTypeFromExtension(
106 mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
107 } catch (IndexOutOfBoundsException e) {
108 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
109 }
110 }
111 if (mimeType == null) {
112 mimeType = "application/octet-stream";
113 }
114 return mimeType;
115 }
116
117 public long getSize() {
118 return mFile.getFileLength();
119 }
120
121 public long getModificationTimestamp() {
122 return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp();
123 }
124
125
126 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
127 synchronized (mDataTransferListeners) {
128 mDataTransferListeners.add(listener);
129 }
130 }
131
132 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
133 synchronized (mDataTransferListeners) {
134 mDataTransferListeners.remove(listener);
135 }
136 }
137
138 @Override
139 protected RemoteOperationResult run(WebdavClient client) {
140 RemoteOperationResult result = null;
141 File newFile = null;
142 boolean moved = true;
143
144 /// download will be performed to a temporal file, then moved to the final location
145 File tmpFile = new File(getTmpPath());
146
147 /// perform the download
148 try {
149 tmpFile.getParentFile().mkdirs();
150 int status = downloadFile(client, tmpFile);
151 if (isSuccess(status)) {
152 newFile = new File(getSavePath());
153 newFile.getParentFile().mkdirs();
154 moved = tmpFile.renameTo(newFile);
155 }
156 if (!moved)
157 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
158 else
159 result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
160 Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
161
162 } catch (Exception e) {
163 result = new RemoteOperationResult(e);
164 Log_OC.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
165 }
166
167 return result;
168 }
169
170
171 public boolean isSuccess(int status) {
172 return (status == HttpStatus.SC_OK);
173 }
174
175
176 protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
177 int status = -1;
178 boolean savedFile = false;
179 mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
180 Iterator<OnDatatransferProgressListener> it = null;
181
182 FileOutputStream fos = null;
183 try {
184 status = client.executeMethod(mGet);
185 if (isSuccess(status)) {
186 targetFile.createNewFile();
187 BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream());
188 fos = new FileOutputStream(targetFile);
189 long transferred = 0;
190
191 byte[] bytes = new byte[4096];
192 int readResult = 0;
193 while ((readResult = bis.read(bytes)) != -1) {
194 synchronized(mCancellationRequested) {
195 if (mCancellationRequested.get()) {
196 mGet.abort();
197 throw new OperationCancelledException();
198 }
199 }
200 fos.write(bytes, 0, readResult);
201 transferred += readResult;
202 synchronized (mDataTransferListeners) {
203 it = mDataTransferListeners.iterator();
204 while (it.hasNext()) {
205 it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
206 }
207 }
208 }
209 savedFile = true;
210 Header modificationTime = mGet.getResponseHeader("Last-Modified");
211 if (modificationTime != null) {
212 Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
213 mModificationTimestamp = (d != null) ? d.getTime() : 0;
214 }
215
216 } else {
217 client.exhaustResponse(mGet.getResponseBodyAsStream());
218 }
219
220 } finally {
221 if (fos != null) fos.close();
222 if (!savedFile && targetFile.exists()) {
223 targetFile.delete();
224 }
225 mGet.releaseConnection(); // let the connection available for other methods
226 }
227 return status;
228 }
229
230
231 public void cancel() {
232 mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
233 }
234
235
236 }