summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/asynctask/DownloadObserver.java
blob: a626be34e0625b5d2fef9845681171227b9f5281 (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
package de.danoeh.antennapod.asynctask;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;
import de.danoeh.antennapod.feed.FeedFile;
import de.danoeh.antennapod.storage.DownloadRequester;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.R;

/** Observes the status of a specific Download */
public class DownloadObserver extends AsyncTask<Void, Void, Void> {
	private static final String TAG = "DownloadObserver";

	/** Types of downloads to observe. */
	public static final int TYPE_FEED = 0;
	public static final int TYPE_IMAGE = 1;
	public static final int TYPE_MEDIA = 2;

	/** Error codes */
	public static final int ALREADY_DOWNLOADED = 1;
	public static final int NO_DOWNLOAD_FOUND = 2;

	private final long DEFAULT_WAITING_INTERVALL = 1000L;

	private DownloadRequester requester;
	private Context context;
	private ArrayList<DownloadStatus> statusList;
	private List<DownloadObserver.Callback> observer;

	public DownloadObserver(Context context) {
		super();
		this.context = context;
		requester = DownloadRequester.getInstance();
		statusList = new ArrayList<DownloadStatus>();
		observer = Collections
				.synchronizedList(new ArrayList<DownloadObserver.Callback>());
	}

	@Override
	protected void onCancelled() {
		if (AppConfig.DEBUG) Log.d(TAG, "Task was cancelled.");
		statusList.clear();
		for (DownloadObserver.Callback callback : observer) {
			callback.onFinish();
		}
	}

	@Override
	protected void onPostExecute(Void result) {
		if (AppConfig.DEBUG) Log.d(TAG, "Background task has finished");
		statusList.clear();
		for (DownloadObserver.Callback callback : observer) {
			callback.onFinish();
		}
	}

	protected Void doInBackground(Void... params) {
		if (AppConfig.DEBUG) Log.d(TAG, "Background Task started.");
		while (downloadsLeft() && !isCancelled()) {
			refreshStatuslist();
			publishProgress();
			try {
				Thread.sleep(DEFAULT_WAITING_INTERVALL);
			} catch (InterruptedException e) {
				Log.w(TAG, "Thread was interrupted while waiting.");
			}
		}
		if (AppConfig.DEBUG) Log.d(TAG, "Background Task finished.");
		return null;
	}

	@Override
	protected void onProgressUpdate(Void... values) {
		for (DownloadObserver.Callback callback : observer) {
			callback.onProgressUpdate();
		}
	}

	private void refreshStatuslist() {
		ArrayList<DownloadStatus> unhandledItems = new ArrayList<DownloadStatus>(
				statusList);

		Cursor cursor = getDownloadCursor();
		if (cursor.moveToFirst()) {
			do {
				long downloadId = getDownloadStatus(cursor,
						DownloadManager.COLUMN_ID);
				FeedFile feedFile = requester.getFeedFile(downloadId);
				if (feedFile != null) {
					DownloadStatus status = findDownloadStatus(feedFile);

					if (status == null) {
						status = new DownloadStatus(feedFile);
						statusList.add(status);
					} else {
						unhandledItems.remove(status);
					}

					// refresh status
					int statusId = getDownloadStatus(cursor,
							DownloadManager.COLUMN_STATUS);
					getDownloadProgress(cursor, status);
					switch (statusId) {
					case DownloadManager.STATUS_SUCCESSFUL:
						status.statusMsg = R.string.download_successful;
						status.successful = true;
						status.done = true;
					case DownloadManager.STATUS_RUNNING:
						status.statusMsg = R.string.download_running;
						break;
					case DownloadManager.STATUS_FAILED:
						status.statusMsg = R.string.download_failed;
						requester.notifyDownloadService(context);
						status.successful = false;
						status.done = true;
						status.reason = getDownloadStatus(cursor,
								DownloadManager.COLUMN_REASON);
					case DownloadManager.STATUS_PENDING:
						status.statusMsg = R.string.download_pending;
						break;
					default:
						status.done = true;
						status.successful = false;
						status.statusMsg = R.string.download_cancelled_msg;
					}
				}
			} while (cursor.moveToNext());
		}
		cursor.close();

		// remove unhandled items from statuslist
		for (DownloadStatus status : unhandledItems) {
			statusList.remove(status);
		}
	}

	/** Request a cursor with all running Feedfile downloads */
	private Cursor getDownloadCursor() {
		// Collect download ids
		int numDownloads = requester.getNumberOfDownloads();
		long ids[] = new long[numDownloads];
		for (int i = 0; i < numDownloads; i++) {
			ids[i] = requester.getDownloadAt(i).getDownloadId();
		}
		DownloadManager.Query query = new DownloadManager.Query();
		query.setFilterById(ids);
		DownloadManager manager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);

		Cursor result = manager.query(query);
		return result;
	}

	/** Return value of a specific column */
	private int getDownloadStatus(Cursor c, String column) {
		int status = c.getInt(c.getColumnIndex(column));
		return status;
	}

	private void getDownloadProgress(Cursor c, DownloadStatus status) {
		status.size = c.getLong(c
				.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
		status.soFar = c
				.getLong(c
						.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
		status.progressPercent = (int) (((double) status.soFar / (double) status.size) * 100);
	}

	public Context getContext() {
		return context;
	}

	/** Find a DownloadStatus entry by its FeedFile */
	public DownloadStatus findDownloadStatus(FeedFile f) {
		for (DownloadStatus status : statusList) {
			if (status.feedfile == f) {
				return status;
			}
		}
		return null;
	}

	public ArrayList<DownloadStatus> getStatusList() {
		return statusList;
	}

	private boolean downloadsLeft() {
		return !requester.hasNoDownloads();
	}

	public void registerCallback(DownloadObserver.Callback callback) {
		observer.add(callback);
	}

	public void unregisterCallback(DownloadObserver.Callback callback) {
		observer.remove(callback);
	}

	public interface Callback {
		public void onProgressUpdate();

		public void onFinish();
	}

}