summaryrefslogtreecommitdiff
path: root/src/de/podfetcher/storage/DownloadRequester.java
blob: e346ccdad7d9b27b66ee9028918c91c40634703e (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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package de.podfetcher.storage;

import java.util.ArrayList;
import java.io.File;
import java.util.concurrent.Callable;

import de.podfetcher.feed.*;
import de.podfetcher.service.DownloadService;
import de.podfetcher.util.NumberGenerator;
import de.podfetcher.R;

import android.util.Log;
import android.database.Cursor;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Messenger;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.content.ComponentName;
import android.os.Message;
import android.os.RemoteException;
import android.content.Intent;

public class DownloadRequester {
	private static final String TAG = "DownloadRequester";

	public static String EXTRA_DOWNLOAD_ID = "extra.de.podfetcher.storage.download_id";
	public static String EXTRA_ITEM_ID = "extra.de.podfetcher.storage.item_id";

	public static String ACTION_FEED_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.feed_download_completed";
	public static String ACTION_MEDIA_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.media_download_completed";
	public static String ACTION_IMAGE_DOWNLOAD_COMPLETED = "action.de.podfetcher.storage.image_download_completed";

	private static boolean STORE_ON_SD = true;
	public static String IMAGE_DOWNLOADPATH = "images/";
	public static String FEED_DOWNLOADPATH = "cache/";
	public static String MEDIA_DOWNLOADPATH = "media/";


	private static DownloadRequester downloader;
	private DownloadManager manager; 

	public ArrayList<FeedFile> feeds;
	public ArrayList<FeedFile> images;
	public ArrayList<FeedFile> media;

	private DownloadRequester(){
		feeds = new ArrayList<FeedFile>();
		images = new ArrayList<FeedFile>();
		media = new ArrayList<FeedFile>();

	}

	public static DownloadRequester getInstance() {
		if(downloader == null) {
			downloader = new DownloadRequester();
		}
		return downloader;
	}

	private void download(Context context, ArrayList<FeedFile> type, FeedFile item, File dest, boolean visibleInUI) {
		Log.d(TAG, "Requesting download of url "+ item.getDownload_url());
		type.add(item);
		DownloadManager.Request request = new DownloadManager.Request(Uri.parse(item.getDownload_url()));
		//request.allowScanningByMediaScanner();

		request.setDestinationUri(Uri.fromFile(dest));
		request.setVisibleInDownloadsUi(visibleInUI);
		// TODO Set Allowed Network Types
		DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
		context.startService(new Intent(context, DownloadService.class));
		item.setDownloadId(manager.enqueue(request));
		item.setFile_url(dest.toString());	
	}
	public void downloadFeed(Context context, Feed feed) {
		download(context, feeds, feed, 
				new File(getFeedfilePath(context), getFeedfileName(feed)),
				true);
	}

	public void downloadImage(Context context, FeedImage image) {
		download(context, images, image, 
				new File(getImagefilePath(context), getImagefileName(image)),
				true);
	}

	public void downloadMedia(Context context, FeedMedia feedmedia) {
		download(context, media, feedmedia,
				new File(context.getExternalFilesDir(MEDIA_DOWNLOADPATH), "media-" + media.size()),
				true);
	}

	/** Get a Feed by its download id */
	public Feed getFeed(long id) {
		for(FeedFile f: feeds) {
			if(f.getDownloadId() == id) {
				return (Feed) f;
			}
		}
		return null;
	}

	/** Get a FeedImage by its download id */
	public FeedImage getFeedImage(long id) {
		for(FeedFile f: images) {
			if(f.getDownloadId() == id) {
				return (FeedImage) f;
			}
		}
		return null;
	}


	/** Get media by its download id */
	public FeedMedia getFeedMedia(long id) {
		for(FeedFile f: media) {
			if(f.getDownloadId() == id) {
				return (FeedMedia) f;
			}
		}
		return null;
	}

	public void removeFeed(Feed f) {
		feeds.remove(f);	
	}

	public void removeFeedMedia(FeedMedia m) {
		media.remove(m);
	}

	public void removeFeedImage(FeedImage fi) {
		images.remove(fi);
	}


	/** Get the number of uncompleted Downloads */
	public int getNumberOfDownloads() {
		return feeds.size() + images.size() + media.size();
	}

	public int getNumberOfFeedDownloads() {
		return feeds.size();
	}

	public String getFeedfilePath(Context context) {
		return context.getExternalFilesDir(FEED_DOWNLOADPATH).toString() + "/";	
	}

	public String getFeedfileName(Feed feed) {
		return "feed-" + NumberGenerator.generateLong(feed.getDownload_url());
	}

	public String getImagefilePath(Context context) {
		return context.getExternalFilesDir(IMAGE_DOWNLOADPATH).toString() + "/";
	}

	public String getImagefileName(FeedImage image) {
		return "image-" + NumberGenerator.generateLong(image.getDownload_url());
	}

	/* ------------ Methods for communicating with the DownloadManager ------------- */


	/** observes the status of a specific Download */
	public static class DownloadObserver extends Thread {
		private static final String TAG = "DownloadObserver";
		long id;
		Context context;
		Callable client;
		long waiting_intervall;
		private volatile int result;
		private volatile boolean done;
		private Cursor cursor;
		private final long DEFAULT_WAITING_INTERVALL = 500L;
		private DownloadRequester requester;

		public DownloadObserver(long id, Context c) {
			this.id = id;
			this.context = c;
			this.client = client;
			this.waiting_intervall = DEFAULT_WAITING_INTERVALL;
			done = false;
			requester = DownloadRequester.getInstance();
		}

		public void run() {
			Log.d(TAG, "Thread started.");
			while(!isInterrupted()) {
				cursor = getDownloadCursor();
				int status = getDownloadStatus(cursor, DownloadManager.COLUMN_STATUS);
				switch(status) {
					case DownloadManager.STATUS_SUCCESSFUL:
						Log.d(TAG, "Download was successful.");
						done = true;
						result = R.string.download_successful;
						break;
					case DownloadManager.STATUS_RUNNING:
						Log.d(TAG, "Download is running.");
						result = getDownloadStatus(cursor, DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
						break;
					case DownloadManager.STATUS_FAILED:
						Log.d(TAG, "Download failed.");
						result = R.string.download_failed;
						done = true;
						requester.notifyDownloadService(context);
						break;
					case DownloadManager.STATUS_PENDING:
						Log.d(TAG, "Download pending.");
						result = R.string.download_pending;
						break;
					
				}
				try {
				client.call();
				}catch (Exception e) {
				}

				if(done) {
					break;
				} else {
					try {
						sleep(waiting_intervall);
					}catch (InterruptedException e) {}
				}
			}
			Log.d(TAG, "Thread stopped.");
		}
	
		public void setClient(Callable callable) {
			this.client = callable;
		}

		public Cursor getDownloadCursor() {
			DownloadManager.Query query = buildQuery(id);
			DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

			Cursor result = manager.query(query);
			return result;
		}
		public int getDownloadStatus(Cursor c, String column) {
			if(c.moveToFirst()) {
				int status = c.getInt(c.getColumnIndex(column));
				return status;	
			} else {
				return -1;
			}
		}

		private DownloadManager.Query buildQuery(long id) {
			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(id);
			return query;
		}

		public int getResult() {
			return result;
		}

		public boolean getDone() {
			return done;
		}
	}

	/* ------------ Methods for communicating with the DownloadService ------------- */
	private Messenger mService = null;
	boolean mIsBound;

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mService = new Messenger(service);

			try {
				Message msg = Message.obtain(null, DownloadService.MSG_QUERY_DOWNLOADS_LEFT);
				Log.d(TAG, "Sending message to DownloadService.");
				mService.send(msg);
			} catch(RemoteException e) {
				Log.e(TAG, "An Exception happened while communication with the DownloadService");
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			mService = null;
			Log.i(TAG, "Closed connection with DownloadService.");
		}
	};


	/** Notifies the DownloadService to check if there are any Downloads left */
	public void notifyDownloadService(Context context) {
		context.bindService(new Intent(context, DownloadService.class), mConnection, Context.BIND_AUTO_CREATE);
		mIsBound = true;
		context.unbindService(mConnection);
		mIsBound = false;
	}
}