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