summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/service/download/HttpDownloader.java
blob: aa7a734315d79033fbd622cc190864cefbde7658 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package de.danoeh.antennapod.service.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.net.http.AndroidHttpClient;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.asynctask.DownloadStatus;
import de.danoeh.antennapod.util.DownloadError;
import de.danoeh.antennapod.util.StorageUtils;

public class HttpDownloader extends Downloader {
	private static final String TAG = "HttpDownloader";

	private static final int MAX_REDIRECTS = 5;

	private static final int BUFFER_SIZE = 8 * 1024;
	private static final int CONNECTION_TIMEOUT = 5000;

	public HttpDownloader(DownloaderCallback downloaderCallback,
			DownloadStatus status) {
		super(downloaderCallback, status);
	}

	private AndroidHttpClient createHttpClient() {
		AndroidHttpClient httpClient = AndroidHttpClient.newInstance("");
		HttpParams params = httpClient.getParams();
		params.setIntParameter("http.protocol.max-redirects", MAX_REDIRECTS);
		params.setBooleanParameter("http.protocol.reject-relative-redirect",
				false);
		params.setIntParameter("http.socket.timeout", CONNECTION_TIMEOUT);
		HttpClientParams.setRedirecting(params, true);
		return httpClient;
	}

	/**
	 * This method is called by establishConnection(String). Don't call it
	 * directly.
	 * */
	private HttpURLConnection establishConnection(String location,
			int redirectCount) throws MalformedURLException, IOException {
		URL url = new URL(location);
		HttpURLConnection connection = null;
		int responseCode = -1;
		connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(CONNECTION_TIMEOUT);
		// try with 'follow redirect'
		connection.setInstanceFollowRedirects(true);
		try {
			responseCode = connection.getResponseCode();
		} catch (IOException e) {
			e.printStackTrace();
			if (AppConfig.DEBUG)
				Log.d(TAG,
						"Failed to establish connection with 'follow redirects. Disabling 'follow redirects'");
			connection.disconnect();
			connection.setInstanceFollowRedirects(false);
			responseCode = connection.getResponseCode();
		}
		if (AppConfig.DEBUG)
			Log.d(TAG, "Response Code: " + responseCode);
		switch (responseCode) {
		case HttpStatus.SC_TEMPORARY_REDIRECT:
			if (redirectCount < MAX_REDIRECTS) {
				final String redirect = connection.getHeaderField("Location");
				if (redirect != null) {
					return establishConnection(redirect, redirectCount + 1);
				}
			}
		case HttpStatus.SC_OK:
			return connection;
		default:
			onFail(DownloadError.ERROR_HTTP_DATA_ERROR,
					String.valueOf(responseCode));
			return null;
		}
	}

	/**
	 * Establish connection to resource. This method will also try to handle
	 * different response codes / redirect issues.
	 * 
	 * @return the HttpURLConnection object if the connection could be opened,
	 *         null otherwise.
	 * @throws MalformedURLException
	 *             , IOException
	 * */
	private HttpURLConnection establishConnection(String location)
			throws MalformedURLException, IOException {
		return establishConnection(location, 0);
	}

	@Override
	protected void download() {
		AndroidHttpClient httpClient = null;
		OutputStream out = null;
		InputStream connection = null;
		try {
			HttpGet httpGet = new HttpGet(status.getFeedFile()
					.getDownload_url());
			httpClient = createHttpClient();
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity httpEntity = response.getEntity();
			int responseCode = response.getStatusLine().getStatusCode();
			if (AppConfig.DEBUG)
				Log.d(TAG, "Response code is " + responseCode);
			if (responseCode == HttpURLConnection.HTTP_OK && httpEntity != null) {
				if (StorageUtils.storageAvailable(PodcastApp.getInstance())) {
					File destination = new File(status.getFeedFile()
							.getFile_url());
					if (!destination.exists()) {
						connection = httpEntity.getContent();
						InputStream in = new BufferedInputStream(connection);
						out = new BufferedOutputStream(new FileOutputStream(
								destination));
						byte[] buffer = new byte[BUFFER_SIZE];
						int count = 0;
						status.setStatusMsg(R.string.download_running);
						if (AppConfig.DEBUG)
							Log.d(TAG, "Getting size of download");
						status.setSize(httpEntity.getContentLength());
						if (AppConfig.DEBUG)
							Log.d(TAG, "Size is " + status.getSize());
						if (status.getSize() < 0) {
							status.setSize(DownloadStatus.SIZE_UNKNOWN);
						}

						long freeSpace = StorageUtils.getFreeSpaceAvailable();
						if (AppConfig.DEBUG)
							Log.d(TAG, "Free space is " + freeSpace);
						if (status.getSize() == DownloadStatus.SIZE_UNKNOWN
								|| status.getSize() <= freeSpace) {
							if (AppConfig.DEBUG)
								Log.d(TAG, "Starting download");
							while (!cancelled
									&& (count = in.read(buffer)) != -1) {
								out.write(buffer, 0, count);
								status.setSoFar(status.getSoFar() + count);
								status.setProgressPercent((int) (((double) status
										.getSoFar() / (double) status.getSize()) * 100));
							}
							if (cancelled) {
								onCancelled();
							} else {
								onSuccess();
							}
						} else {
							onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null);
						}
					} else {
						Log.w(TAG, "File already exists");
						onFail(DownloadError.ERROR_FILE_EXISTS, null);
					}
				} else {
					onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null);
				}
			} else {
				onFail(DownloadError.ERROR_HTTP_DATA_ERROR,
						String.valueOf(responseCode));
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage());
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage());
		} catch (UnknownHostException e) {
			e.printStackTrace();
			onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			onFail(DownloadError.ERROR_IO_ERROR, e.getMessage());
		} catch (NullPointerException e) {
			// might be thrown by connection.getInputStream()
			e.printStackTrace();
			onFail(DownloadError.ERROR_CONNECTION_ERROR, status.getFeedFile()
					.getDownload_url());
		} finally {
			IOUtils.closeQuietly(connection);
			IOUtils.closeQuietly(out);
			if (httpClient != null) {
				httpClient.close();
			}
		}
	}

	private void onSuccess() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Download was successful");
		status.setSuccessful(true);
		status.setDone(true);
	}

	private void onFail(int reason, String reasonDetailed) {
		if (AppConfig.DEBUG) {
			Log.d(TAG, "Download failed");
		}
		status.setReason(reason);
		status.setReasonDetailed(reasonDetailed);
		status.setDone(true);
		status.setSuccessful(false);
	}

	private void onCancelled() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Download was cancelled");
		status.setReason(DownloadError.ERROR_DOWNLOAD_CANCELLED);
		status.setDone(true);
		status.setSuccessful(false);
		status.setCancelled(true);
	}

}