75bf9234d2f3a6479b02bd54084ec634bfc74c8c
[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 as published by
6 * the Free Software Foundation, either version 2 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
19 package com.owncloud.android.operations;
20
21 import java.io.BufferedInputStream;
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.util.Date;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.Set;
29 import java.util.concurrent.atomic.AtomicBoolean;
30
31 import org.apache.commons.httpclient.Header;
32 import org.apache.commons.httpclient.HttpException;
33 import org.apache.commons.httpclient.methods.GetMethod;
34 import org.apache.http.HttpStatus;
35
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.util.Log;
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
63
64 public DownloadFileOperation(Account account, OCFile file) {
65 if (account == null)
66 throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
67 if (file == null)
68 throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
69
70 mAccount = account;
71 mFile = file;
72 }
73
74
75 public Account getAccount() {
76 return mAccount;
77 }
78
79 public OCFile getFile() {
80 return mFile;
81 }
82
83 public String getSavePath() {
84 String path = mFile.getStoragePath(); // re-downloads should be done over the original file
85 if (path != null && path.length() > 0) {
86 return path;
87 }
88 return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
89 }
90
91 public String getTmpPath() {
92 return FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
93 }
94
95 public String getRemotePath() {
96 return mFile.getRemotePath();
97 }
98
99 public String getMimeType() {
100 String mimeType = mFile.getMimetype();
101 if (mimeType == null || mimeType.length() <= 0) {
102 try {
103 mimeType = MimeTypeMap.getSingleton()
104 .getMimeTypeFromExtension(
105 mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
106 } catch (IndexOutOfBoundsException e) {
107 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
108 }
109 }
110 if (mimeType == null) {
111 mimeType = "application/octet-stream";
112 }
113 return mimeType;
114 }
115
116 public long getSize() {
117 return mFile.getFileLength();
118 }
119
120 public long getModificationTimestamp() {
121 return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp();
122 }
123
124
125 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
126 mDataTransferListeners.add(listener);
127 }
128
129 @Override
130 protected RemoteOperationResult run(WebdavClient client) {
131 RemoteOperationResult result = null;
132 File newFile = null;
133 boolean moved = true;
134
135 /// download will be performed to a temporal file, then moved to the final location
136 File tmpFile = new File(getTmpPath());
137
138 /// perform the download
139 try {
140 tmpFile.getParentFile().mkdirs();
141 int status = downloadFile(client, tmpFile);
142 if (isSuccess(status)) {
143 newFile = new File(getSavePath());
144 newFile.getParentFile().mkdirs();
145 moved = tmpFile.renameTo(newFile);
146 }
147 if (!moved)
148 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
149 else
150 result = new RemoteOperationResult(isSuccess(status), status);
151 Log.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
152
153 } catch (Exception e) {
154 result = new RemoteOperationResult(e);
155 Log.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
156 }
157
158 return result;
159 }
160
161
162 public boolean isSuccess(int status) {
163 return (status == HttpStatus.SC_OK);
164 }
165
166
167 protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
168 int status = -1;
169 boolean savedFile = false;
170 GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
171 Iterator<OnDatatransferProgressListener> it = null;
172
173 FileOutputStream fos = null;
174 try {
175 status = client.executeMethod(get);
176 if (isSuccess(status)) {
177 targetFile.createNewFile();
178 BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
179 fos = new FileOutputStream(targetFile);
180 long transferred = 0;
181
182 byte[] bytes = new byte[4096];
183 int readResult = 0;
184 while ((readResult = bis.read(bytes)) != -1) {
185 synchronized(mCancellationRequested) {
186 if (mCancellationRequested.get()) {
187 get.abort();
188 throw new OperationCancelledException();
189 }
190 }
191 fos.write(bytes, 0, readResult);
192 transferred += readResult;
193 it = mDataTransferListeners.iterator();
194 while (it.hasNext()) {
195 it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
196 }
197 }
198 savedFile = true;
199 Header modificationTime = get.getResponseHeader("Last-Modified");
200 if (modificationTime != null) {
201 Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
202 mModificationTimestamp = (d != null) ? d.getTime() : 0;
203 }
204
205 } else {
206 client.exhaustResponse(get.getResponseBodyAsStream());
207 }
208
209 } finally {
210 if (fos != null) fos.close();
211 if (!savedFile && targetFile.exists()) {
212 targetFile.delete();
213 }
214 get.releaseConnection(); // let the connection available for other methods
215 }
216 return status;
217 }
218
219
220 public void cancel() {
221 mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
222 }
223
224 }