summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/feed/FeedManager.java
blob: 6a18113e3cf6a093f571bf6f3d4aa0a027699e6f (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
package de.danoeh.antennapod.feed;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.asynctask.DownloadStatus;
import de.danoeh.antennapod.preferences.PlaybackPreferences;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.storage.DownloadRequestException;
import de.danoeh.antennapod.storage.DownloadRequester;
import de.danoeh.antennapod.storage.PodDBAdapter;
import de.danoeh.antennapod.util.DownloadError;
import de.danoeh.antennapod.util.EpisodeFilter;
import de.danoeh.antennapod.util.FeedtitleComparator;
import de.danoeh.antennapod.util.comparator.DownloadStatusComparator;
import de.danoeh.antennapod.util.comparator.FeedItemPubdateComparator;
import de.danoeh.antennapod.util.comparator.PlaybackCompletionDateComparator;
import de.danoeh.antennapod.util.exception.MediaFileNotFoundException;

/**
 * Singleton class that - provides access to all Feeds and FeedItems and to
 * several lists of FeedItems. - provides methods for modifying the
 * application's data - takes care of updating the information stored in the
 * database when something is modified
 * 
 * An instance of this class can be retrieved via getInstance().
 * */
public class FeedManager {
	private static final String TAG = "FeedManager";

	/** Number of completed Download status entries to store. */
	private static final int DOWNLOAD_LOG_SIZE = 50;

	private static FeedManager singleton;

	private List<Feed> feeds;

	/** Contains all items where 'read' is false */
	private List<FeedItem> unreadItems;

	/** Contains completed Download status entries */
	private List<DownloadStatus> downloadLog;

	/** Contains the queue of items to be played. */
	private List<FeedItem> queue;

	/** Contains the last played items */
	private List<FeedItem> playbackHistory;

	/** Maximum number of items in the playback history. */
	private static final int PLAYBACK_HISTORY_SIZE = 15;

	private DownloadRequester requester = DownloadRequester.getInstance();
	private EventDistributor eventDist = EventDistributor.getInstance();

	/**
	 * Should be used to change the content of the arrays from another thread to
	 * ensure that arrays are only modified on the main thread.
	 */
	private Handler contentChanger;

	/** Ensures that there are no parallel db operations. */
	private Executor dbExec;

	/** Prevents user from starting several feed updates at the same time. */
	private static boolean isStartingFeedRefresh = false;

	private FeedManager() {
		feeds = Collections.synchronizedList(new ArrayList<Feed>());
		unreadItems = Collections.synchronizedList(new ArrayList<FeedItem>());
		downloadLog = new ArrayList<DownloadStatus>();
		queue = Collections.synchronizedList(new ArrayList<FeedItem>());
		playbackHistory = Collections
				.synchronizedList(new ArrayList<FeedItem>());
		contentChanger = new Handler();
		dbExec = Executors.newSingleThreadExecutor(new ThreadFactory() {

			@Override
			public Thread newThread(Runnable r) {
				Thread t = new Thread(r);
				t.setPriority(Thread.MIN_PRIORITY);
				return t;
			}
		});
	}

	/** Creates a new instance of this class if necessary and returns it. */
	public static FeedManager getInstance() {
		if (singleton == null) {
			singleton = new FeedManager();
		}
		return singleton;
	}

	/**
	 * Play FeedMedia and start the playback service + launch Mediaplayer
	 * Activity.
	 * 
	 * @param context
	 *            for starting the playbackservice
	 * @param media
	 *            that shall be played
	 * @param showPlayer
	 *            if Mediaplayer activity shall be started
	 * @param startWhenPrepared
	 *            if Mediaplayer shall be started after it has been prepared
	 * @param shouldStream
	 *            if Mediaplayer should stream the file
	 */
	public void playMedia(Context context, FeedMedia media, boolean showPlayer,
			boolean startWhenPrepared, boolean shouldStream) {
		try {
			if (!shouldStream) {
				if (media.fileExists() == false) {
					throw new MediaFileNotFoundException(
							"No episode was found at " + media.getFile_url(),
							media);
				}
			}
			// Start playback Service
			Intent launchIntent = new Intent(context, PlaybackService.class);
			launchIntent
					.putExtra(PlaybackService.EXTRA_MEDIA_ID, media.getId());
			launchIntent.putExtra(PlaybackService.EXTRA_FEED_ID, media
					.getItem().getFeed().getId());
			launchIntent.putExtra(PlaybackService.EXTRA_START_WHEN_PREPARED,
					startWhenPrepared);
			launchIntent.putExtra(PlaybackService.EXTRA_SHOULD_STREAM,
					shouldStream);
			launchIntent.putExtra(PlaybackService.EXTRA_PREPARE_IMMEDIATELY,
					true);
			context.startService(launchIntent);
			if (showPlayer) {
				// Launch Mediaplayer
				context.startActivity(PlaybackService.getPlayerActivityIntent(
						context, media));
			}
		} catch (MediaFileNotFoundException e) {
			e.printStackTrace();
			if (PlaybackPreferences.getLastPlayedId() == media.getId()) {
				context.sendBroadcast(new Intent(
						PlaybackService.ACTION_SHUTDOWN_PLAYBACK_SERVICE));
			}
			notifyMissingFeedMediaFile(context, media);
		}
	}

	/** Remove media item that has been downloaded. */
	public boolean deleteFeedMedia(Context context, FeedMedia media) {
		boolean result = false;
		if (media.isDownloaded()) {
			File mediaFile = new File(media.file_url);
			if (mediaFile.exists()) {
				result = mediaFile.delete();
			}
			media.setDownloaded(false);
			media.setFile_url(null);
			setFeedMedia(context, media);

			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(context);
			if (media.getId() == PlaybackPreferences.getLastPlayedId()) {
				SharedPreferences.Editor editor = prefs.edit();
				editor.putBoolean(PlaybackPreferences.PREF_LAST_IS_STREAM, true);
				editor.commit();
			}
			if (PlaybackPreferences.getLastPlayedId() == media.getId()) {
				context.sendBroadcast(new Intent(
						PlaybackService.ACTION_SHUTDOWN_PLAYBACK_SERVICE));
			}
		}
		if (AppConfig.DEBUG)
			Log.d(TAG, "Deleting File. Result: " + result);
		return result;
	}

	/** Remove a feed with all its items and media files and its image. */
	public void deleteFeed(final Context context, final Feed feed) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context.getApplicationContext());
		if (PlaybackPreferences.getLastPlayedFeedId() == feed.getId()) {
			context.sendBroadcast(new Intent(
					PlaybackService.ACTION_SHUTDOWN_PLAYBACK_SERVICE));
			SharedPreferences.Editor editor = prefs.edit();
			editor.putLong(PlaybackPreferences.PREF_LAST_PLAYED_ID, -1);
			editor.putLong(PlaybackPreferences.PREF_LAST_PLAYED_FEED_ID, -1);
			editor.commit();
		}

		contentChanger.post(new Runnable() {

			@Override
			public void run() {
				feeds.remove(feed);
				eventDist.sendFeedUpdateBroadcast();
				dbExec.execute(new Runnable() {

					@Override
					public void run() {
						PodDBAdapter adapter = new PodDBAdapter(context);
						DownloadRequester requester = DownloadRequester
								.getInstance();
						adapter.open();
						// delete image file
						if (feed.getImage() != null) {
							if (feed.getImage().isDownloaded()
									&& feed.getImage().getFile_url() != null) {
								File imageFile = new File(feed.getImage()
										.getFile_url());
								imageFile.delete();
							} else if (requester.isDownloadingFile(feed
									.getImage())) {
								requester.cancelDownload(context,
										feed.getImage());
							}
						}
						// delete stored media files and mark them as read
						for (FeedItem item : feed.getItems()) {
							if (item.getState() == FeedItem.State.NEW) {
								unreadItems.remove(item);
							}
							if (queue.contains(item)) {
								removeQueueItem(item, adapter);
							}
							removeItemFromPlaybackHistory(context, item);
							if (item.getMedia() != null
									&& item.getMedia().isDownloaded()) {
								File mediaFile = new File(item.getMedia()
										.getFile_url());
								mediaFile.delete();
							} else if (item.getMedia() != null
									&& requester.isDownloadingFile(item
											.getMedia())) {
								requester.cancelDownload(context,
										item.getMedia());
							}
						}

						adapter.removeFeed(feed);
						adapter.close();
					}
				});
			}
		});

	}

	/**
	 * Makes sure that playback history is sorted and is not larger than
	 * PLAYBACK_HISTORY_SIZE.
	 * 
	 * @return an array of all feeditems that were remove from the playback
	 *         history or null if no items were removed.
	 */
	private FeedItem[] cleanupPlaybackHistory() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Cleaning up playback history.");

		Collections.sort(playbackHistory,
				new PlaybackCompletionDateComparator());
		final int initialSize = playbackHistory.size();
		if (initialSize > PLAYBACK_HISTORY_SIZE) {
			FeedItem[] removed = new FeedItem[initialSize
					- PLAYBACK_HISTORY_SIZE];

			for (int i = 0; i < removed.length; i++) {
				removed[i] = playbackHistory.remove(playbackHistory.size() - 1);
			}
			if (AppConfig.DEBUG)
				Log.d(TAG, "Removed " + removed.length
						+ " items from playback history.");
			return removed;
		}
		return null;
	}

	/**
	 * Executes cleanupPlaybackHistory and deletes the playbackCompletionDate of
	 * all item that were removed from the history.
	 */
	private void cleanupPlaybackHistoryWithDBCleanup(final Context context) {
		final FeedItem[] removedItems = cleanupPlaybackHistory();
		if (removedItems != null) {
			dbExec.execute(new Runnable() {

				@Override
				public void run() {
					PodDBAdapter adapter = new PodDBAdapter(context);
					adapter.open();
					for (FeedItem item : removedItems) {
						if (item.getMedia() != null) {
							item.getMedia().setPlaybackCompletionDate(null);
							adapter.setMedia(item.getMedia());
						}
					}
					adapter.close();
				}
			});
		}
	}

	/** Removes all items from the playback history. */
	public void clearPlaybackHistory(final Context context) {
		if (!playbackHistory.isEmpty()) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Clearing playback history.");
			final FeedItem[] items = playbackHistory
					.toArray(new FeedItem[playbackHistory.size()]);
			playbackHistory.clear();
			eventDist.sendPlaybackHistoryUpdateBroadcast();
			dbExec.execute(new Runnable() {

				@Override
				public void run() {
					PodDBAdapter adapter = new PodDBAdapter(context);
					adapter.open();
					for (FeedItem item : items) {
						if (item.getMedia() != null
								&& item.getMedia().getPlaybackCompletionDate() != null) {
							item.getMedia().setPlaybackCompletionDate(null);
							adapter.setMedia(item.getMedia());
						}
					}
					adapter.close();
				}
			});
		}
	}

	/** Adds a FeedItem to the playback history. */
	public void addItemToPlaybackHistory(Context context, FeedItem item) {
		if (item.getMedia() != null
				&& item.getMedia().getPlaybackCompletionDate() != null) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Adding new item to playback history");
			if (!playbackHistory.contains(item)) {
				playbackHistory.add(item);
			}
			cleanupPlaybackHistoryWithDBCleanup(context);
			eventDist.sendPlaybackHistoryUpdateBroadcast();
		}
	}

	private void removeItemFromPlaybackHistory(Context context, FeedItem item) {
		playbackHistory.remove(item);
		eventDist.sendPlaybackHistoryUpdateBroadcast();
	}

	/**
	 * Sets the 'read'-attribute of a FeedItem. Should be used by all Classes
	 * instead of the setters of FeedItem.
	 */
	public void markItemRead(final Context context, final FeedItem item,
			final boolean read, boolean resetMediaPosition) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Setting item with title " + item.getTitle()
					+ " as read/unread");

		item.setRead(read);
		if (item.hasMedia() && resetMediaPosition) {
			item.getMedia().setPosition(0);
		}
		setFeedItem(context, item);
		if (item.hasMedia() && resetMediaPosition)
			setFeedMedia(context, item.getMedia());

		contentChanger.post(new Runnable() {

			@Override
			public void run() {
				if (read == true) {
					unreadItems.remove(item);
				} else {
					unreadItems.add(item);
					Collections.sort(unreadItems,
							new FeedItemPubdateComparator());
				}
				eventDist.sendUnreadItemsUpdateBroadcast();
			}
		});

	}

	/**
	 * Sets the 'read' attribute of all FeedItems of a specific feed to true
	 */
	public void markFeedRead(Context context, Feed feed) {
		for (FeedItem item : feed.getItems()) {
			if (unreadItems.contains(item)) {
				markItemRead(context, item, true, false);
			}
		}
	}

	/** Marks all items in the unread items list as read */
	public void markAllItemsRead(final Context context) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "marking all items as read");
		for (FeedItem item : unreadItems) {
			item.setRead(true);
		}
		final ArrayList<FeedItem> unreadItemsCopy = new ArrayList<FeedItem>(
				unreadItems);
		unreadItems.clear();
		eventDist.sendUnreadItemsUpdateBroadcast();
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				for (FeedItem item : unreadItemsCopy) {
					setFeedItem(item, adapter);
					if (item.hasMedia())
						setFeedMedia(context, item.getMedia());
				}
				adapter.close();
			}
		});

	}

	/** Updates all feeds in the feed list. */
	@SuppressLint("NewApi")
	public void refreshAllFeeds(final Context context) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Refreshing all feeds.");
		if (!isStartingFeedRefresh) {
			isStartingFeedRefresh = true;
			AsyncTask<Void, Void, Void> updateWorker = new AsyncTask<Void, Void, Void>() {

				@Override
				protected void onPostExecute(Void result) {
					if (AppConfig.DEBUG)
						Log.d(TAG,
								"All feeds have been sent to the downloadmanager");
					isStartingFeedRefresh = false;
				}

				@Override
				protected Void doInBackground(Void... params) {
					for (Feed feed : feeds) {
						try {
							refreshFeed(context, feed);
						} catch (DownloadRequestException e) {
							e.printStackTrace();
							addDownloadStatus(
									context,
									new DownloadStatus(feed, feed
											.getHumanReadableIdentifier(),
											DownloadError.ERROR_REQUEST_ERROR,
											false, e.getMessage()));
						}
					}
					return null;
				}

			};
			if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
				updateWorker.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			} else {
				updateWorker.execute();
			}
		}

	}

	/**
	 * Notifies the feed manager that the an image file is invalid. It will try
	 * to redownload it
	 */
	public void notifyInvalidImageFile(Context context, FeedImage image) {
		Log.i(TAG,
				"The feedmanager was notified about an invalid image download. It will now try to redownload the image file");
		try {
			requester.downloadImage(context, image);
		} catch (DownloadRequestException e) {
			e.printStackTrace();
			Log.w(TAG, "Failed to download invalid feed image");
		}
	}

	/**
	 * Notifies the feed manager that a downloaded episode doesn't exist
	 * anymore. It will update the values of the FeedMedia object accordingly.
	 */
	public void notifyMissingFeedMediaFile(Context context, FeedMedia media) {
		Log.i(TAG,
				"The feedmanager was notified about a missing episode. It will update its database now.");
		media.setDownloaded(false);
		media.setFile_url(null);
		setFeedMedia(context, media);
		eventDist.sendFeedUpdateBroadcast();
	}

	/** Updates a specific feed. */
	public void refreshFeed(Context context, Feed feed)
			throws DownloadRequestException {
		requester.downloadFeed(context, new Feed(feed.getDownload_url(),
				new Date(), feed.getTitle()));
	}

	/** Adds a download status object to the download log. */
	public void addDownloadStatus(final Context context,
			final DownloadStatus status) {
		contentChanger.post(new Runnable() {

			@Override
			public void run() {
				downloadLog.add(status);
				Collections.sort(downloadLog, new DownloadStatusComparator());
				final DownloadStatus removedStatus;
				if (downloadLog.size() > DOWNLOAD_LOG_SIZE) {
					removedStatus = downloadLog.remove(downloadLog.size() - 1);
				} else {
					removedStatus = null;
				}
				eventDist.sendDownloadLogUpdateBroadcast();
				dbExec.execute(new Runnable() {

					@Override
					public void run() {
						PodDBAdapter adapter = new PodDBAdapter(context);
						adapter.open();
						if (removedStatus != null) {
							adapter.removeDownloadStatus(removedStatus);
						}
						adapter.setDownloadStatus(status);
						adapter.close();
					}
				});
			}
		});

	}

	/** Downloads all items in the queue that have not been downloaded yet. */
	public void downloadAllItemsInQueue(final Context context) {
		if (!queue.isEmpty()) {
			try {
				downloadFeedItem(context,
						queue.toArray(new FeedItem[queue.size()]));
			} catch (DownloadRequestException e) {
				e.printStackTrace();
			}
		}
	}

	/** Downloads FeedItems if they have not been downloaded yet. */
	public void downloadFeedItem(final Context context, FeedItem... items)
			throws DownloadRequestException {
		List<FeedItem> addToQueue = new ArrayList<FeedItem>();

		for (FeedItem item : items) {
			if (item.getMedia() != null
					&& !requester.isDownloadingFile(item.getMedia())
					&& !item.getMedia().isDownloaded()) {
				if (items.length > 1) {
					try {
						requester.downloadMedia(context, item.getMedia());
					} catch (DownloadRequestException e) {
						e.printStackTrace();
						addDownloadStatus(context,
								new DownloadStatus(item.getMedia(), item
										.getMedia()
										.getHumanReadableIdentifier(),
										DownloadError.ERROR_REQUEST_ERROR,
										false, e.getMessage()));
					}
				} else {
					requester.downloadMedia(context, item.getMedia());
				}
				addToQueue.add(item);
			}
		}
		if (UserPreferences.isAutoQueue()) {
			addQueueItem(context,
					addToQueue.toArray(new FeedItem[addToQueue.size()]));
		}
	}

	/**
	 * Enqueues all items that are currently in the unreadItems list and marks
	 * them as 'read'.
	 */
	public void enqueueAllNewItems(final Context context) {
		if (!unreadItems.isEmpty()) {
			addQueueItem(context,
					unreadItems.toArray(new FeedItem[unreadItems.size()]));
			markAllItemsRead(context);
		}
	}

	/** Adds FeedItems to the queue if they are not in the queue yet. */
	public void addQueueItem(final Context context, final FeedItem... items) {
		if (items.length > 0) {
			contentChanger.post(new Runnable() {

				@Override
				public void run() {
					for (FeedItem item : items) {
						if (!queue.contains(item)) {
							queue.add(item);
						}
					}
					eventDist.sendQueueUpdateBroadcast();
					dbExec.execute(new Runnable() {

						@Override
						public void run() {
							PodDBAdapter adapter = new PodDBAdapter(context);
							adapter.open();
							adapter.setQueue(queue);
							adapter.close();
						}
					});
				}
			});
		}

	}

	/**
	 * Return the item that comes after this item in the queue or null if this
	 * item is not in the queue or if this item has no successor.
	 */
	public FeedItem getQueueSuccessorOfItem(FeedItem item) {
		if (isInQueue(item)) {
			int itemIndex = queue.indexOf(item);
			if (itemIndex != -1 && itemIndex < (queue.size() - 1)) {
				return queue.get(itemIndex + 1);
			}
		}
		return null;
	}

	/** Removes all items in queue */
	public void clearQueue(final Context context) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Clearing queue");
		queue.clear();
		eventDist.sendQueueUpdateBroadcast();
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setQueue(queue);
				adapter.close();
			}
		});

	}

	/** Removes a FeedItem from the queue. Uses external PodDBAdapter. */
	private void removeQueueItem(FeedItem item, PodDBAdapter adapter) {
		boolean removed = queue.remove(item);
		if (removed) {
			adapter.setQueue(queue);
		}

	}

	/** Removes a FeedItem from the queue. */
	public void removeQueueItem(final Context context, FeedItem item) {
		boolean removed = queue.remove(item);
		if (removed) {
			autoDeleteIfPossible(context, item.getMedia());
			dbExec.execute(new Runnable() {

				@Override
				public void run() {
					PodDBAdapter adapter = new PodDBAdapter(context);
					adapter.open();
					adapter.setQueue(queue);
					adapter.close();
				}
			});

		}
		eventDist.sendQueueUpdateBroadcast();
	}

	/**
	 * Delete the episode of this FeedMedia object if auto-delete is enabled and
	 * it is not the last played media or it is the last played media and
	 * playback has been completed.
	 */
	public void autoDeleteIfPossible(Context context, FeedMedia media) {
		if (media != null) {
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(context
							.getApplicationContext());
			if (UserPreferences.isAutoDelete()) {

				if ((media.getId() != PlaybackPreferences.getLastPlayedId())
						&& ((media.getId() != PlaybackPreferences
								.getAutoDeleteMediaId()) || (media.getId() == PlaybackPreferences
								.getAutoDeleteMediaId() && PlaybackPreferences
								.isAutoDeleteMediaPlaybackCompleted()))) {
					if (AppConfig.DEBUG)
						Log.d(TAG, "Performing auto-cleanup");
					deleteFeedMedia(context, media);

					SharedPreferences.Editor editor = prefs.edit();
					editor.putLong(
							PlaybackPreferences.PREF_AUTODELETE_MEDIA_ID, -1);
					editor.commit();
				} else {
					if (AppConfig.DEBUG)
						Log.d(TAG, "Didn't do auto-cleanup");
				}
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Auto-delete preference is disabled");
			}
		} else {
			Log.e(TAG, "Could not do auto-cleanup: media was null");
		}
	}

	/**
	 * Moves the queue item at the specified index to another position. If the
	 * indices are out of range, no operation will be performed.
	 * 
	 * @param from
	 *            index of the item that is going to be moved
	 * @param to
	 *            destination index of item
	 * @param broadcastUpdate
	 *            true if the method should send a queue update broadcast after
	 *            the operation has been performed. This should be set to false
	 *            if the order of the queue is changed through drag & drop
	 *            reordering to avoid visual glitches.
	 */
	public void moveQueueItem(final Context context, int from, int to,
			boolean broadcastUpdate) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Moving queue item from index " + from + " to index "
					+ to);
		if (from >= 0 && from < queue.size() && to >= 0 && to < queue.size()) {
			FeedItem item = queue.remove(from);
			queue.add(to, item);
			dbExec.execute(new Runnable() {
				@Override
				public void run() {
					PodDBAdapter adapter = new PodDBAdapter(context);
					adapter.open();
					adapter.setQueue(queue);
					adapter.close();
				}
			});
			if (broadcastUpdate) {
				eventDist.sendQueueUpdateBroadcast();
			}
		}
	}

	/** Returns true if the specified item is in the queue. */
	public boolean isInQueue(FeedItem item) {
		return queue.contains(item);
	}

	/**
	 * Returns the FeedItem at the beginning of the queue or null if the queue
	 * is empty.
	 */
	public FeedItem getFirstQueueItem() {
		if (queue.isEmpty()) {
			return null;
		} else {
			return queue.get(0);
		}
	}

	private void addNewFeed(final Context context, final Feed feed) {
		contentChanger.post(new Runnable() {

			@Override
			public void run() {
				feeds.add(feed);
				Collections.sort(feeds, new FeedtitleComparator());
				eventDist.sendFeedUpdateBroadcast();
			}
		});
		setCompleteFeed(context, feed);
	}

	/**
	 * Updates an existing feed or adds it as a new one if it doesn't exist.
	 * 
	 * @return The saved Feed with a database ID
	 */
	public Feed updateFeed(Context context, final Feed newFeed) {
		// Look up feed in the feedslist
		final Feed savedFeed = searchFeedByIdentifyingValue(newFeed
				.getIdentifyingValue());
		if (savedFeed == null) {
			if (AppConfig.DEBUG)
				Log.d(TAG,
						"Found no existing Feed with title "
								+ newFeed.getTitle() + ". Adding as new one.");
			// Add a new Feed
			addNewFeed(context, newFeed);
			return newFeed;
		} else {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Feed with title " + newFeed.getTitle()
						+ " already exists. Syncing new with existing one.");
			if (savedFeed.compareWithOther(newFeed)) {
				if (AppConfig.DEBUG)
					Log.d(TAG,
							"Feed has updated attribute values. Updating old feed's attributes");
				savedFeed.updateFromOther(newFeed);
			}
			// Look for new or updated Items
			for (int idx = 0; idx < newFeed.getItems().size(); idx++) {
				final FeedItem item = newFeed.getItems().get(idx);
				FeedItem oldItem = searchFeedItemByIdentifyingValue(savedFeed,
						item.getIdentifyingValue());
				if (oldItem == null) {
					// item is new
					final int i = idx;
					item.setFeed(savedFeed);
					contentChanger.post(new Runnable() {
						@Override
						public void run() {
							savedFeed.getItems().add(i, item);

						}
					});
					markItemRead(context, item, false, false);
				} else {
					oldItem.updateFromOther(item);
				}
			}
			// update attributes
			savedFeed.setLastUpdate(newFeed.getLastUpdate());
			savedFeed.setType(newFeed.getType());
			setCompleteFeed(context, savedFeed);
			return savedFeed;
		}

	}

	/** Get a Feed by its identifying value. */
	private Feed searchFeedByIdentifyingValue(String identifier) {
		for (Feed feed : feeds) {
			if (feed.getIdentifyingValue().equals(identifier)) {
				return feed;
			}
		}
		return null;
	}

	/**
	 * Returns true if a feed with the given download link is already in the
	 * feedlist.
	 */
	public boolean feedExists(String downloadUrl) {
		for (Feed feed : feeds) {
			if (feed.getDownload_url().equals(downloadUrl)) {
				return true;
			}
		}
		return false;
	}

	/** Get a FeedItem by its identifying value. */
	private FeedItem searchFeedItemByIdentifyingValue(Feed feed,
			String identifier) {
		for (FeedItem item : feed.getItems()) {
			if (item.getIdentifyingValue().equals(identifier)) {
				return item;
			}
		}
		return null;
	}

	/** Updates Information of an existing Feed. Uses external adapter. */
	private void setFeed(Feed feed, PodDBAdapter adapter) {
		if (adapter != null) {
			adapter.setFeed(feed);
			feed.cacheDescriptionsOfItems();
		} else {
			Log.w(TAG, "Adapter in setFeed was null");
		}
	}

	/** Updates Information of an existing Feeditem. Uses external adapter. */
	private void setFeedItem(FeedItem item, PodDBAdapter adapter) {
		if (adapter != null) {
			adapter.setSingleFeedItem(item);
		} else {
			Log.w(TAG, "Adapter in setFeedItem was null");
		}
	}

	/** Updates Information of an existing Feedimage. Uses external adapter. */
	private void setFeedImage(FeedImage image, PodDBAdapter adapter) {
		if (adapter != null) {
			adapter.setImage(image);
		} else {
			Log.w(TAG, "Adapter in setFeedImage was null");
		}
	}

	/**
	 * Updates Information of an existing Feedmedia object. Uses external
	 * adapter.
	 */
	private void setFeedImage(FeedMedia media, PodDBAdapter adapter) {
		if (adapter != null) {
			adapter.setMedia(media);
		} else {
			Log.w(TAG, "Adapter in setFeedMedia was null");
		}
	}

	/**
	 * Updates Information of an existing Feed. Creates and opens its own
	 * adapter.
	 */
	public void setFeed(final Context context, final Feed feed) {
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setFeed(feed);
				feed.cacheDescriptionsOfItems();
				adapter.close();
			}
		});

	}

	/**
	 * Updates Information of an existing Feed and its FeedItems. Creates and
	 * opens its own adapter.
	 */
	public void setCompleteFeed(final Context context, final Feed feed) {
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setCompleteFeed(feed);
				feed.cacheDescriptionsOfItems();
				adapter.close();
			}
		});

	}

	/**
	 * Updates information of an existing FeedItem. Creates and opens its own
	 * adapter.
	 */
	public void setFeedItem(final Context context, final FeedItem item) {
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setSingleFeedItem(item);
				adapter.close();
			}
		});

	}

	/**
	 * Updates information of an existing FeedImage. Creates and opens its own
	 * adapter.
	 */
	public void setFeedImage(final Context context, final FeedImage image) {
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setImage(image);
				adapter.close();
			}
		});

	}

	/**
	 * Updates information of an existing FeedMedia object. Creates and opens
	 * its own adapter.
	 */
	public void setFeedMedia(final Context context, final FeedMedia media) {
		dbExec.execute(new Runnable() {

			@Override
			public void run() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				adapter.setMedia(media);
				adapter.close();
			}
		});

	}

	/** Get a Feed by its id */
	public Feed getFeed(long id) {
		for (Feed f : feeds) {
			if (f.id == id) {
				return f;
			}
		}
		Log.e(TAG, "Couldn't find Feed with id " + id);
		return null;
	}

	/** Get a Feed Image by its id */
	public FeedImage getFeedImage(long id) {
		for (Feed f : feeds) {
			FeedImage image = f.getImage();
			if (image != null && image.getId() == id) {
				return image;
			}
		}
		return null;
	}

	/** Get a Feed Item by its id and its feed */
	public FeedItem getFeedItem(long id, Feed feed) {
		if (feed != null) {
			for (FeedItem item : feed.getItems()) {
				if (item.getId() == id) {
					return item;
				}
			}
		}
		Log.e(TAG, "Couldn't find FeedItem with id " + id);
		return null;
	}

	/** Get a FeedItem by its id and the id of its feed. */
	public FeedItem getFeedItem(long itemId, long feedId) {
		Feed feed = getFeed(feedId);
		if (feed != null && feed.getItems() != null) {
			for (FeedItem item : feed.getItems()) {
				if (item.getId() == itemId) {
					return item;
				}
			}
		}
		return null;
	}

	/** Get a FeedMedia object by the id of the Media object and the feed object */
	public FeedMedia getFeedMedia(long id, Feed feed) {
		if (feed != null) {
			for (FeedItem item : feed.getItems()) {
				if (item.getMedia() != null && item.getMedia().getId() == id) {
					return item.getMedia();
				}
			}
		}
		Log.e(TAG, "Couldn't find FeedMedia with id " + id);
		if (feed == null)
			Log.e(TAG, "Feed was null");
		return null;
	}

	/** Get a FeedMedia object by the id of the Media object. */
	public FeedMedia getFeedMedia(long id) {
		for (Feed feed : feeds) {
			for (FeedItem item : feed.getItems()) {
				if (item.getMedia() != null && item.getMedia().getId() == id) {
					return item.getMedia();
				}
			}
		}
		Log.w(TAG, "Couldn't find FeedMedia with id " + id);
		return null;
	}

	/** Get a download status object from the download log by its FeedFile. */
	public DownloadStatus getDownloadStatus(FeedFile feedFile) {
		for (DownloadStatus status : downloadLog) {
			if (status.getFeedFile() == feedFile) {
				return status;
			}
		}
		return null;
	}

	/** Reads the database */
	public void loadDBData(Context context) {
		feeds.clear();
		PodDBAdapter adapter = new PodDBAdapter(context);
		adapter.open();
		extractFeedlistFromCursor(context, adapter);
		extractDownloadLogFromCursor(context, adapter);
		extractQueueFromCursor(context, adapter);
		adapter.close();
		Collections.sort(feeds, new FeedtitleComparator());
		Collections.sort(unreadItems, new FeedItemPubdateComparator());
		cleanupPlaybackHistory();
	}

	private void extractFeedlistFromCursor(Context context, PodDBAdapter adapter) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Extracting Feedlist");
		Cursor feedlistCursor = adapter.getAllFeedsCursor();
		if (feedlistCursor.moveToFirst()) {
			do {
				Date lastUpdate = new Date(
						feedlistCursor
								.getLong(PodDBAdapter.KEY_LAST_UPDATE_INDEX));
				Feed feed = new Feed(lastUpdate);

				feed.id = feedlistCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
				feed.setTitle(feedlistCursor
						.getString(PodDBAdapter.KEY_TITLE_INDEX));
				feed.setLink(feedlistCursor
						.getString(PodDBAdapter.KEY_LINK_INDEX));
				feed.setDescription(feedlistCursor
						.getString(PodDBAdapter.KEY_DESCRIPTION_INDEX));
				feed.setPaymentLink(feedlistCursor
						.getString(PodDBAdapter.KEY_PAYMENT_LINK_INDEX));
				feed.setAuthor(feedlistCursor
						.getString(PodDBAdapter.KEY_AUTHOR_INDEX));
				feed.setLanguage(feedlistCursor
						.getString(PodDBAdapter.KEY_LANGUAGE_INDEX));
				feed.setType(feedlistCursor
						.getString(PodDBAdapter.KEY_TYPE_INDEX));
				feed.setFeedIdentifier(feedlistCursor
						.getString(PodDBAdapter.KEY_FEED_IDENTIFIER_INDEX));
				long imageIndex = feedlistCursor
						.getLong(PodDBAdapter.KEY_IMAGE_INDEX);
				if (imageIndex != 0) {
					feed.setImage(adapter.getFeedImage(imageIndex));
					feed.getImage().setFeed(feed);
				}
				feed.file_url = feedlistCursor
						.getString(PodDBAdapter.KEY_FILE_URL_INDEX);
				feed.download_url = feedlistCursor
						.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX);
				feed.setDownloaded(feedlistCursor
						.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0);
				// Get FeedItem-Object
				Cursor itemlistCursor = adapter.getAllItemsOfFeedCursor(feed);
				feed.setItems(extractFeedItemsFromCursor(context, feed,
						itemlistCursor, adapter));
				itemlistCursor.close();

				feeds.add(feed);
			} while (feedlistCursor.moveToNext());
		}
		feedlistCursor.close();

	}

	private ArrayList<FeedItem> extractFeedItemsFromCursor(Context context,
			Feed feed, Cursor itemlistCursor, PodDBAdapter adapter) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Extracting Feeditems of feed " + feed.getTitle());
		ArrayList<FeedItem> items = new ArrayList<FeedItem>();
		ArrayList<String> mediaIds = new ArrayList<String>();

		if (itemlistCursor.moveToFirst()) {
			do {
				FeedItem item = new FeedItem();

				item.id = itemlistCursor.getLong(PodDBAdapter.IDX_FI_SMALL_ID);
				item.setFeed(feed);
				item.setTitle(itemlistCursor
						.getString(PodDBAdapter.IDX_FI_SMALL_TITLE));
				item.setLink(itemlistCursor
						.getString(PodDBAdapter.IDX_FI_SMALL_LINK));
				item.setPubDate(new Date(itemlistCursor
						.getLong(PodDBAdapter.IDX_FI_SMALL_PUBDATE)));
				item.setPaymentLink(itemlistCursor
						.getString(PodDBAdapter.IDX_FI_SMALL_PAYMENT_LINK));
				long mediaId = itemlistCursor
						.getLong(PodDBAdapter.IDX_FI_SMALL_MEDIA);
				if (mediaId != 0) {
					mediaIds.add(String.valueOf(mediaId));
					item.setMedia(new FeedMedia(mediaId, item));
				}
				item.setRead((itemlistCursor
						.getInt(PodDBAdapter.IDX_FI_SMALL_READ) > 0) ? true
						: false);
				item.setItemIdentifier(itemlistCursor
						.getString(PodDBAdapter.IDX_FI_SMALL_ITEM_IDENTIFIER));
				if (item.getState() == FeedItem.State.NEW) {
					unreadItems.add(item);
				}

				// extract chapters
				boolean hasSimpleChapters = itemlistCursor
						.getInt(PodDBAdapter.IDX_FI_SMALL_HAS_CHAPTERS) > 0;
				if (hasSimpleChapters) {
					Cursor chapterCursor = adapter
							.getSimpleChaptersOfFeedItemCursor(item);
					if (chapterCursor.moveToFirst()) {
						item.setChapters(new ArrayList<Chapter>());
						do {
							int chapterType = chapterCursor
									.getInt(PodDBAdapter.KEY_CHAPTER_TYPE_INDEX);
							Chapter chapter = null;
							long start = chapterCursor
									.getLong(PodDBAdapter.KEY_CHAPTER_START_INDEX);
							String title = chapterCursor
									.getString(PodDBAdapter.KEY_TITLE_INDEX);
							String link = chapterCursor
									.getString(PodDBAdapter.KEY_CHAPTER_LINK_INDEX);

							switch (chapterType) {
							case SimpleChapter.CHAPTERTYPE_SIMPLECHAPTER:
								chapter = new SimpleChapter(start, title, item,
										link);
								break;
							case ID3Chapter.CHAPTERTYPE_ID3CHAPTER:
								chapter = new ID3Chapter(start, title, item,
										link);
								break;
							case VorbisCommentChapter.CHAPTERTYPE_VORBISCOMMENT_CHAPTER:
								chapter = new VorbisCommentChapter(start,
										title, item, link);
								break;
							}
							chapter.setId(chapterCursor
									.getLong(PodDBAdapter.KEY_ID_INDEX));
							item.getChapters().add(chapter);
						} while (chapterCursor.moveToNext());
					}
					chapterCursor.close();
				}
				items.add(item);
			} while (itemlistCursor.moveToNext());
		}
		extractMediafromFeedItemlist(adapter, items, mediaIds);
		Collections.sort(items, new FeedItemPubdateComparator());
		return items;
	}

	private void extractMediafromFeedItemlist(PodDBAdapter adapter,
			ArrayList<FeedItem> items, ArrayList<String> mediaIds) {
		ArrayList<FeedItem> itemsCopy = new ArrayList<FeedItem>(items);
		Cursor cursor = adapter.getFeedMediaCursor(mediaIds
				.toArray(new String[mediaIds.size()]));
		if (cursor.moveToFirst()) {
			do {
				long mediaId = cursor.getLong(PodDBAdapter.KEY_ID_INDEX);
				// find matching feed item
				FeedItem item = getMatchingItemForMedia(mediaId, itemsCopy);
				itemsCopy.remove(item);
				if (item != null) {
					Date playbackCompletionDate = null;
					long playbackCompletionTime = cursor
							.getLong(PodDBAdapter.KEY_PLAYBACK_COMPLETION_DATE_INDEX);
					if (playbackCompletionTime > 0) {
						playbackCompletionDate = new Date(
								playbackCompletionTime);
					}

					item.setMedia(new FeedMedia(
							mediaId,
							item,
							cursor.getInt(PodDBAdapter.KEY_DURATION_INDEX),
							cursor.getInt(PodDBAdapter.KEY_POSITION_INDEX),
							cursor.getLong(PodDBAdapter.KEY_SIZE_INDEX),
							cursor.getString(PodDBAdapter.KEY_MIME_TYPE_INDEX),
							cursor.getString(PodDBAdapter.KEY_FILE_URL_INDEX),
							cursor.getString(PodDBAdapter.KEY_DOWNLOAD_URL_INDEX),
							cursor.getInt(PodDBAdapter.KEY_DOWNLOADED_INDEX) > 0,
							playbackCompletionDate));
					if (playbackCompletionDate != null) {
						playbackHistory.add(item);
					}

				}
			} while (cursor.moveToNext());
			cursor.close();
		}
	}

	private FeedItem getMatchingItemForMedia(long mediaId,
			ArrayList<FeedItem> items) {
		for (FeedItem item : items) {
			if (item.getMedia() != null && item.getMedia().getId() == mediaId) {
				return item;
			}
		}
		return null;
	}

	private void extractDownloadLogFromCursor(Context context,
			PodDBAdapter adapter) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Extracting DownloadLog");
		Cursor logCursor = adapter.getDownloadLogCursor();
		if (logCursor.moveToFirst()) {
			do {
				long id = logCursor.getLong(PodDBAdapter.KEY_ID_INDEX);
				FeedFile feedfile = null;

				long feedfileId = logCursor
						.getLong(PodDBAdapter.KEY_FEEDFILE_INDEX);
				int feedfileType = logCursor
						.getInt(PodDBAdapter.KEY_FEEDFILETYPE_INDEX);
				if (feedfileId != 0) {
					switch (feedfileType) {
					case Feed.FEEDFILETYPE_FEED:
						feedfile = getFeed(feedfileId);
						break;
					case FeedImage.FEEDFILETYPE_FEEDIMAGE:
						feedfile = getFeedImage(feedfileId);
						break;
					case FeedMedia.FEEDFILETYPE_FEEDMEDIA:
						feedfile = getFeedMedia(feedfileId);
					}
				}
				boolean successful = logCursor
						.getInt(PodDBAdapter.KEY_SUCCESSFUL_INDEX) > 0;
				int reason = logCursor.getInt(PodDBAdapter.KEY_REASON_INDEX);
				String reasonDetailed = logCursor
						.getString(PodDBAdapter.KEY_REASON_DETAILED_INDEX);
				String title = logCursor
						.getString(PodDBAdapter.KEY_DOWNLOADSTATUS_TITLE_INDEX);
				Date completionDate = new Date(
						logCursor
								.getLong(PodDBAdapter.KEY_COMPLETION_DATE_INDEX));
				downloadLog.add(new DownloadStatus(id, title, feedfile,
						feedfileType, successful, reason, completionDate,
						reasonDetailed));

			} while (logCursor.moveToNext());
		}
		logCursor.close();
		Collections.sort(downloadLog, new DownloadStatusComparator());
	}

	private void extractQueueFromCursor(Context context, PodDBAdapter adapter) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Extracting Queue");
		Cursor cursor = adapter.getQueueCursor();
		if (cursor.moveToFirst()) {
			do {
				int index = cursor.getInt(PodDBAdapter.KEY_ID_INDEX);
				Feed feed = getFeed(cursor
						.getLong(PodDBAdapter.KEY_QUEUE_FEED_INDEX));
				if (feed != null) {
					FeedItem item = getFeedItem(
							cursor.getLong(PodDBAdapter.KEY_FEEDITEM_INDEX),
							feed);
					if (item != null) {
						queue.add(index, item);
					}
				}

			} while (cursor.moveToNext());
		}
		cursor.close();
	}

	/**
	 * Loads description and contentEncoded values from the database and caches
	 * it in the feeditem. The task callback will contain a String-array with
	 * the description at index 0 and the value of contentEncoded at index 1.
	 */
	public void loadExtraInformationOfItem(final Context context,
			final FeedItem item, FeedManager.TaskCallback<String[]> callback) {
		if (AppConfig.DEBUG) {
			Log.d(TAG,
					"Loading extra information of item with id " + item.getId());
			if (item.getTitle() != null) {
				Log.d(TAG, "Title: " + item.getTitle());
			}
		}
		dbExec.execute(new FeedManager.Task<String[]>(new Handler(), callback) {

			@Override
			public void execute() {
				PodDBAdapter adapter = new PodDBAdapter(context);
				adapter.open();
				Cursor extraCursor = adapter.getExtraInformationOfItem(item);
				if (extraCursor.moveToFirst()) {
					String description = extraCursor
							.getString(PodDBAdapter.IDX_FI_EXTRA_DESCRIPTION);
					String contentEncoded = extraCursor
							.getString(PodDBAdapter.IDX_FI_EXTRA_CONTENT_ENCODED);
					item.setCachedDescription(description);
					item.setCachedContentEncoded(contentEncoded);
					setResult(new String[] { description, contentEncoded });
				}
				adapter.close();
			}
		});
	}

	/**
	 * Searches the descriptions of FeedItems of a specific feed for a given
	 * string.
	 * 
	 * @param feed
	 *            The feed whose items should be searched.
	 * @param query
	 *            The search string
	 * @param callback
	 *            A callback which will be used to return the search result
	 * */
	public void searchFeedItemDescription(final Context context,
			final Feed feed, final String query,
			FeedManager.QueryTaskCallback callback) {
		dbExec.execute(new FeedManager.QueryTask(context, new Handler(),
				callback) {

			@Override
			public void execute(PodDBAdapter adapter) {
				Cursor searchResult = adapter.searchItemDescriptions(feed,
						query);
				setResult(searchResult);
			}
		});
	}

	/**
	 * Searches the 'contentEncoded' field of FeedItems of a specific feed for a
	 * given string.
	 * 
	 * @param feed
	 *            The feed whose items should be searched.
	 * @param query
	 *            The search string
	 * @param callback
	 *            A callback which will be used to return the search result
	 * */
	public void searchFeedItemContentEncoded(final Context context,
			final Feed feed, final String query,
			FeedManager.QueryTaskCallback callback) {
		dbExec.execute(new FeedManager.QueryTask(context, new Handler(),
				callback) {

			@Override
			public void execute(PodDBAdapter adapter) {
				Cursor searchResult = adapter.searchItemContentEncoded(feed,
						query);
				setResult(searchResult);
			}
		});
	}

	/** Returns the number of feeds that are currently in the feeds list. */
	public int getFeedsSize() {
		return feeds.size();
	}

	/** Returns the feed at the specified index of the feeds list. */
	public Feed getFeedAtIndex(int index) {
		return feeds.get(index);
	}

	/** Returns an array that contains all feeds of the feed manager. */
	public Feed[] getFeedsArray() {
		return feeds.toArray(new Feed[feeds.size()]);
	}

	List<Feed> getFeeds() {
		return feeds;
	}

	/**
	 * Returns the number of items that are currently in the queue.
	 * 
	 * @param enableEpisodeFilter
	 *            true if items without episodes should be ignored by this
	 *            method if the episode filter was enabled by the user.
	 * */
	public int getQueueSize(boolean enableEpisodeFilter) {
		if (UserPreferences.isDisplayOnlyEpisodes() && enableEpisodeFilter) {
			return EpisodeFilter.countItemsWithEpisodes(queue);
		} else {
			return queue.size();
		}
	}

	/**
	 * Returns the FeedItem at the specified index of the queue.
	 * 
	 * @param enableEpisodeFilter
	 *            true if items without episodes should be ignored by this
	 *            method if the episode filter was enabled by the user.
	 * 
	 * @throws IndexOutOfBoundsException
	 *             if index is out of range
	 * */
	public FeedItem getQueueItemAtIndex(int index, boolean enableEpisodeFilter) {
		if (UserPreferences.isDisplayOnlyEpisodes() && enableEpisodeFilter) {
			return EpisodeFilter.accessEpisodeByIndex(queue, index);
		} else {
			return queue.get(index);
		}
	}

	/**
	 * Returns the number of unread items.
	 * 
	 * @param enableEpisodeFilter
	 *            true if items without episodes should be ignored by this
	 *            method if the episode filter was enabled by the user.
	 * */
	public int getUnreadItemsSize(boolean enableEpisodeFilter) {
		if (UserPreferences.isDisplayOnlyEpisodes() && enableEpisodeFilter) {
			return EpisodeFilter.countItemsWithEpisodes(unreadItems);
		} else {
			return unreadItems.size();
		}
	}

	/**
	 * Returns the FeedItem at the specified index of the unread items list.
	 * 
	 * @param enableEpisodeFilter
	 *            true if items without episodes should be ignored by this
	 *            method if the episode filter was enabled by the user.
	 * 
	 * @throws IndexOutOfBoundsException
	 *             if index is out of range
	 * */
	public FeedItem getUnreadItemAtIndex(int index, boolean enableEpisodeFilter) {
		if (UserPreferences.isDisplayOnlyEpisodes() && enableEpisodeFilter) {
			return EpisodeFilter.accessEpisodeByIndex(unreadItems, index);
		} else {
			return unreadItems.get(index);
		}
	}

	/**
	 * Returns the number of items in the playback history.
	 * */
	public int getPlaybackHistorySize() {
		return playbackHistory.size();
	}

	/**
	 * Returns the FeedItem at the specified index of the playback history.
	 * 
	 * @throws IndexOutOfBoundsException
	 *             if index is out of range
	 * */
	public FeedItem getPlaybackHistoryItemIndex(int index) {
		return playbackHistory.get(index);
	}

	/** Returns the number of items in the download log */
	public int getDownloadLogSize() {
		return downloadLog.size();
	}

	/** Returns the download status at the specified index of the download log. */
	public DownloadStatus getDownloadStatusFromLogAtIndex(int index) {
		return downloadLog.get(index);
	}

	/** Is called by a FeedManagerTask after completion. */
	public interface TaskCallback<V> {
		void onCompletion(V result);
	}

	/** Is called by a FeedManager.QueryTask after completion. */
	public interface QueryTaskCallback {
		void handleResult(Cursor result);

		void onCompletion();
	}

	/** A runnable that can post a callback to a handler after completion. */
	abstract class Task<V> implements Runnable {
		private Handler handler;
		private TaskCallback<V> callback;
		private V result;

		/**
		 * Standard contructor. No callbacks are going to be posted to a
		 * handler.
		 */
		public Task() {
			super();
		}

		/**
		 * The Task will post a Runnable to 'handler' that will execute the
		 * 'callback' after completion.
		 */
		public Task(Handler handler, TaskCallback<V> callback) {
			super();
			this.handler = handler;
			this.callback = callback;
		}

		@Override
		public final void run() {
			execute();
			if (handler != null && callback != null) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						callback.onCompletion(result);
					}
				});
			}
		}

		/** This method will be executed in the same thread as the run() method. */
		public abstract void execute();

		public void setResult(V result) {
			this.result = result;
		}
	}

	/**
	 * A runnable which should be used for database queries. The onCompletion
	 * method is executed on the database executor to handle Cursors correctly.
	 * This class automatically creates a PodDBAdapter object and closes it when
	 * it is no longer in use.
	 */
	abstract class QueryTask implements Runnable {
		private QueryTaskCallback callback;
		private Cursor result;
		private Context context;
		private Handler handler;

		public QueryTask(Context context, Handler handler,
				QueryTaskCallback callback) {
			this.callback = callback;
			this.context = context;
			this.handler = handler;
		}

		@Override
		public final void run() {
			PodDBAdapter adapter = new PodDBAdapter(context);
			adapter.open();
			execute(adapter);
			callback.handleResult(result);
			if (result != null && !result.isClosed()) {
				result.close();
			}
			adapter.close();
			if (handler != null && callback != null) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						callback.onCompletion();
					}

				});
			}
		}

		public abstract void execute(PodDBAdapter adapter);

		protected void setResult(Cursor c) {
			result = c;
		}
	}

}