OC-1867: Remove package eu.alefzero.webdav
[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.network.webdav.OnDatatransferProgressListener;
38 import com.owncloud.android.network.webdav.WebdavClient;
39 import com.owncloud.android.network.webdav.WebdavUtils;
40 import com.owncloud.android.operations.RemoteOperation;
41 import com.owncloud.android.operations.RemoteOperationResult;
42 import com.owncloud.android.utils.FileStorageUtils;
43
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 private GetMethod mGet;
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_OC.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 synchronized (mDataTransferListeners) {
127 mDataTransferListeners.add(listener);
128 }
129 }
130
131 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
132 synchronized (mDataTransferListeners) {
133 mDataTransferListeners.remove(listener);
134 }
135 }
136
137 @Override
138 protected RemoteOperationResult run(WebdavClient client) {
139 RemoteOperationResult result = null;
140 File newFile = null;
141 boolean moved = true;
142
143 /// download will be performed to a temporal file, then moved to the final location
144 File tmpFile = new File(getTmpPath());
145
146 /// perform the download
147 try {
148 tmpFile.getParentFile().mkdirs();
149 int status = downloadFile(client, tmpFile);
150 if (isSuccess(status)) {
151 newFile = new File(getSavePath());
152 newFile.getParentFile().mkdirs();
153 moved = tmpFile.renameTo(newFile);
154 }
155 if (!moved)
156 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
157 else
158 result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
159 Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
160
161 } catch (Exception e) {
162 result = new RemoteOperationResult(e);
163 Log_OC.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
164 }
165
166 return result;
167 }
168
169
170 public boolean isSuccess(int status) {
171 return (status == HttpStatus.SC_OK);
172 }
173
174
175 protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
176 int status = -1;
177 boolean savedFile = false;
178 mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
179 Iterator<OnDatatransferProgressListener> it = null;
180
181 FileOutputStream fos = null;
182 try {
183 status = client.executeMethod(mGet);
184 if (isSuccess(status)) {
185 targetFile.createNewFile();
186 BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream());
187 fos = new FileOutputStream(targetFile);
188 long transferred = 0;
189
190 byte[] bytes = new byte[4096];
191 int readResult = 0;
192 while ((readResult = bis.read(bytes)) != -1) {
193 synchronized(mCancellationRequested) {
194 if (mCancellationRequested.get()) {
195 mGet.abort();
196 throw new OperationCancelledException();
197 }
198 }
199 fos.write(bytes, 0, readResult);
200 transferred += readResult;
201 synchronized (mDataTransferListeners) {
202 it = mDataTransferListeners.iterator();
203 while (it.hasNext()) {
204 it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
205 }
206 }
207 }
208 savedFile = true;
209 Header modificationTime = mGet.getResponseHeader("Last-Modified");
210 if (modificationTime != null) {
211 Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
212 mModificationTimestamp = (d != null) ? d.getTime() : 0;
213 }
214
215 } else {
216 client.exhaustResponse(mGet.getResponseBodyAsStream());
217 }
218
219 } finally {
220 if (fos != null) fos.close();
221 if (!savedFile && targetFile.exists()) {
222 targetFile.delete();
223 }
224 mGet.releaseConnection(); // let the connection available for other methods
225 }
226 return status;
227 }
228
229
230 public void cancel() {
231 mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
232 }
233
234
235 }