summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/storage/DBTasks.java
blob: bf615776df60672778b1f5e07d670b452da2473e (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
package de.danoeh.antennapod.storage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReentrantLock;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.feed.EventDistributor;
import de.danoeh.antennapod.feed.Feed;
import de.danoeh.antennapod.feed.FeedImage;
import de.danoeh.antennapod.feed.FeedItem;
import de.danoeh.antennapod.feed.FeedMedia;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.service.download.DownloadStatus;
import de.danoeh.antennapod.util.DownloadError;
import de.danoeh.antennapod.util.NetworkUtils;
import de.danoeh.antennapod.util.QueueAccess;
import de.danoeh.antennapod.util.exception.MediaFileNotFoundException;

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

    private DBTasks() {
    }

    public static void playMedia(final Context context, final 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_PLAYABLE, media);
            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));
            }
            DBWriter.addQueueItemAt(context, media.getItem().getId(), 0, false);
        } catch (MediaFileNotFoundException e) {
            e.printStackTrace();
            if (media.isPlaying()) {
                context.sendBroadcast(new Intent(
                        PlaybackService.ACTION_SHUTDOWN_PLAYBACK_SERVICE));
            }
            notifyMissingFeedMediaFile(context, media);
        }
    }

    private static ReentrantLock refreshAllFeedsLock = new ReentrantLock();

    public static void refreshAllFeeds(final Context context,
                                       final List<Feed> feeds) {
        if (refreshAllFeedsLock.tryLock()) {
            new Thread() {
                public void run() {
                    if (feeds != null) {
                        refreshFeeds(context, feeds);
                    } else {
                        refreshFeeds(context, DBReader.getFeedList(context));
                    }
                    refreshAllFeedsLock.unlock();
                }
            }.start();
        } else {
            if (AppConfig.DEBUG)
                Log.d(TAG,
                        "Ignoring request to refresh all feeds: Refresh lock is locked");
        }
    }

    public static void refreshExpiredFeeds(final Context context) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Refreshing expired feeds");

        new Thread() {
            public void run() {
                long millis = UserPreferences.getUpdateInterval();

                if (millis > 0) {
                    long now = Calendar.getInstance().getTime().getTime();

                    // Allow a 10 minute window
                    millis -= 10 * 60 * 1000;
                    List<Feed> feedList = DBReader.getExpiredFeedsList(context,
                            now - millis);
                    if (feedList.size() > 0) {
                        refreshFeeds(context, feedList);
                    }
                }
            }
        }.start();
    }

    private static void refreshFeeds(final Context context,
                                     final List<Feed> feedList) {

        for (Feed feed : feedList) {
            try {
                refreshFeed(context, feed);
            } catch (DownloadRequestException e) {
                e.printStackTrace();
                DBWriter.addDownloadStatus(
                        context,
                        new DownloadStatus(feed, feed
                                .getHumanReadableIdentifier(),
                                DownloadError.ERROR_REQUEST_ERROR, false, e
                                .getMessage()));
            }
        }

    }

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

    public static void notifyInvalidImageFile(final Context context,
                                              final FeedImage image) {
        Log.i(TAG,
                "The feedmanager was notified about an invalid image download. It will now try to redownload the image file");
        try {
            DownloadRequester.getInstance().downloadImage(context, image);
        } catch (DownloadRequestException e) {
            e.printStackTrace();
            Log.w(TAG, "Failed to download invalid feed image");
        }
    }

    public static void notifyMissingFeedMediaFile(final Context context,
                                                  final 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);
        DBWriter.setFeedMedia(context, media);
        EventDistributor.getInstance().sendFeedUpdateBroadcast();
    }

    public static void downloadAllItemsInQueue(final Context context) {
        new Thread() {
            public void run() {
                List<FeedItem> queue = DBReader.getQueue(context);
                if (!queue.isEmpty()) {
                    try {
                        downloadFeedItems(context,
                                queue.toArray(new FeedItem[queue.size()]));
                    } catch (DownloadRequestException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public static void downloadFeedItems(final Context context,
                                         FeedItem... items) throws DownloadRequestException {
        downloadFeedItems(true, context, items);
    }

    private static void downloadFeedItems(boolean performAutoCleanup,
                                          final Context context, final FeedItem... items)
            throws DownloadRequestException {
        final DownloadRequester requester = DownloadRequester.getInstance();

        if (performAutoCleanup) {
            new Thread() {

                @Override
                public void run() {
                    performAutoCleanup(context,
                            getPerformAutoCleanupArgs(context, items.length));
                }

            }.start();
        }
        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();
                        DBWriter.addDownloadStatus(context,
                                new DownloadStatus(item.getMedia(), item
                                        .getMedia()
                                        .getHumanReadableIdentifier(),
                                        DownloadError.ERROR_REQUEST_ERROR,
                                        false, e.getMessage()));
                    }
                } else {
                    requester.downloadMedia(context, item.getMedia());
                }
            }
        }
    }

    private static int getNumberOfUndownloadedEpisodes(
            final List<FeedItem> queue, final List<FeedItem> unreadItems) {
        int counter = 0;
        for (FeedItem item : queue) {
            if (item.hasMedia() && !item.getMedia().isDownloaded()
                    && !item.getMedia().isPlaying()) {
                counter++;
            }
        }
        for (FeedItem item : unreadItems) {
            if (item.hasMedia() && !item.getMedia().isDownloaded()) {
                counter++;
            }
        }
        return counter;
    }

    public static void autodownloadUndownloadedItems(final Context context) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Performing auto-dl of undownloaded episodes");
        if (NetworkUtils.autodownloadNetworkAvailable(context)
                && UserPreferences.isEnableAutodownload()) {
            final List<FeedItem> queue = DBReader.getQueue(context);
            final List<FeedItem> unreadItems = DBReader
                    .getUnreadItemsList(context);

            int undownloadedEpisodes = getNumberOfUndownloadedEpisodes(queue,
                    unreadItems);
            int downloadedEpisodes = DBReader
                    .getNumberOfDownloadedEpisodes(context);
            int deletedEpisodes = performAutoCleanup(context,
                    getPerformAutoCleanupArgs(context, undownloadedEpisodes));
            int episodeSpaceLeft = undownloadedEpisodes;
            boolean cacheIsUnlimited = UserPreferences.getEpisodeCacheSize() == UserPreferences
                    .getEpisodeCacheSizeUnlimited();

            if (!cacheIsUnlimited
                    && UserPreferences.getEpisodeCacheSize() < downloadedEpisodes
                    + undownloadedEpisodes) {
                episodeSpaceLeft = UserPreferences.getEpisodeCacheSize()
                        - (downloadedEpisodes - deletedEpisodes);
            }

            List<FeedItem> itemsToDownload = new ArrayList<FeedItem>();
            if (episodeSpaceLeft > 0 && undownloadedEpisodes > 0) {
                for (int i = 0; i < queue.size(); i++) { // ignore playing item
                    FeedItem item = queue.get(i);
                    if (item.hasMedia() && !item.getMedia().isDownloaded()
                            && !item.getMedia().isPlaying()) {
                        itemsToDownload.add(item);
                        episodeSpaceLeft--;
                        undownloadedEpisodes--;
                        if (episodeSpaceLeft == 0 || undownloadedEpisodes == 0) {
                            break;
                        }
                    }
                }
            }
            if (episodeSpaceLeft > 0 && undownloadedEpisodes > 0) {
                for (FeedItem item : unreadItems) {
                    if (item.hasMedia() && !item.getMedia().isDownloaded()) {
                        itemsToDownload.add(item);
                        episodeSpaceLeft--;
                        undownloadedEpisodes--;
                        if (episodeSpaceLeft == 0 || undownloadedEpisodes == 0) {
                            break;
                        }
                    }
                }
            }
            if (AppConfig.DEBUG)
                Log.d(TAG, "Enqueueing " + itemsToDownload.size()
                        + " items for download");

            try {
                downloadFeedItems(false, context,
                        itemsToDownload.toArray(new FeedItem[itemsToDownload
                                .size()]));
            } catch (DownloadRequestException e) {
                e.printStackTrace();
            }

        }
    }

    private static int getPerformAutoCleanupArgs(Context context,
                                                 final int episodeNumber) {
        if (episodeNumber >= 0
                && UserPreferences.getEpisodeCacheSize() != UserPreferences
                .getEpisodeCacheSizeUnlimited()) {
            int downloadedEpisodes = DBReader
                    .getNumberOfDownloadedEpisodes(context);
            if (downloadedEpisodes + episodeNumber >= UserPreferences
                    .getEpisodeCacheSize()) {

                return downloadedEpisodes + episodeNumber
                        - UserPreferences.getEpisodeCacheSize();
            }
        }
        return 0;
    }

    public static void performAutoCleanup(final Context context) {
        performAutoCleanup(context, getPerformAutoCleanupArgs(context, 0));
    }

    private static int performAutoCleanup(final Context context,
                                          final int episodeNumber) {
        List<FeedItem> candidates = DBReader.getDownloadedItems(context);
        List<FeedItem> queue = DBReader.getQueue(context);
        List<FeedItem> delete;
        for (FeedItem item : candidates) {
            if (item.hasMedia() && item.getMedia().isDownloaded()
                    && !queue.contains(item) && item.isRead()) {
                candidates.add(item);
            }

        }

        Collections.sort(candidates, new Comparator<FeedItem>() {
            @Override
            public int compare(FeedItem lhs, FeedItem rhs) {
                Date l = lhs.getMedia().getPlaybackCompletionDate();
                Date r = rhs.getMedia().getPlaybackCompletionDate();

                if (l == null) {
                    l = new Date(0);
                }
                if (r == null) {
                    r = new Date(0);
                }
                return l.compareTo(r);
            }
        });

        if (candidates.size() > episodeNumber) {
            delete = candidates.subList(0, episodeNumber);
        } else {
            delete = candidates;
        }

        for (FeedItem item : delete) {
            DBWriter.deleteFeedMediaOfItem(context, item.getId());
        }

        int counter = delete.size();

        if (AppConfig.DEBUG)
            Log.d(TAG, String.format(
                    "Auto-delete deleted %d episodes (%d requested)", counter,
                    episodeNumber));

        return counter;
    }

    public static void enqueueAllNewItems(final Context context) {
        long[] unreadItems = DBReader.getUnreadItemIds(context);
        DBWriter.addQueueItem(context, unreadItems);
    }

    public static FeedItem getQueueSuccessorOfItem(Context context,
                                                   final long itemId, List<FeedItem> queue) {
        FeedItem result = null;
        if (queue == null) {
            queue = DBReader.getQueue(context);
        }
        if (queue != null) {
            Iterator<FeedItem> iterator = queue.iterator();
            while (iterator.hasNext()) {
                FeedItem item = iterator.next();
                if (item.getId() == itemId) {
                    if (iterator.hasNext()) {
                        result = iterator.next();
                    }
                    break;
                }
            }
        }
        return result;
    }

    public static boolean isInQueue(Context context, final long feedItemId) {
        List<Long> queue = DBReader.getQueueIDList(context);
        return QueueAccess.IDListAccess(queue).contains(feedItemId);
    }

    private static Feed searchFeedByIdentifyingValue(Context context,
                                                     String identifier) {
        List<Feed> feeds = DBReader.getFeedList(context);
        for (Feed feed : feeds) {
            if (feed.getIdentifyingValue().equals(identifier)) {
                return feed;
            }
        }
        return null;
    }

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

    public static synchronized Feed updateFeed(final Context context,
                                               final Feed newFeed) {
        // Look up feed in the feedslist
        final Feed savedFeed = searchFeedByIdentifyingValue(context,
                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
            try {
                DBWriter.addNewFeed(context, newFeed).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return newFeed;
        } else {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Feed with title " + newFeed.getTitle()
                        + " already exists. Syncing new with existing one.");

            savedFeed.setItems(DBReader.getFeedItemList(context, savedFeed));
            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);
                    savedFeed.getItems().add(i, item);
                    DBWriter.markItemRead(context, item.getId(), false);
                } else {
                    oldItem.updateFromOther(item);
                }
            }
            // update attributes
            savedFeed.setLastUpdate(newFeed.getLastUpdate());
            savedFeed.setType(newFeed.getType());
            try {
                DBWriter.setCompleteFeed(context, savedFeed).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            new Thread() {
                @Override
                public void run() {
                    autodownloadUndownloadedItems(context);
                }
            }.start();
            return savedFeed;
        }
    }

    /**
     * Searches the titles of FeedItems of a specific feed for a given
     * string.
     *
     * @param feedID  The id of the feed whose items should be searched.
     * @param query The search string
     */
    public static FutureTask<List<FeedItem>> searchFeedItemTitle(final Context context,
                                                                 final long feedID, final String query) {
        return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) {
            @Override
            public void execute(PodDBAdapter adapter) {
                Cursor searchResult = adapter.searchItemTitles(feedID,
                        query);
                List<FeedItem> items = DBReader.extractItemlistFromCursor(context, searchResult);
                DBReader.loadFeedDataOfFeedItemlist(context, items);
                setResult(items);
                searchResult.close();
            }
        });
    }

    /**
     * Searches the descriptions of FeedItems of a specific feed for a given
     * string.
     *
     * @param feedID The id of the feed whose items should be searched.
     * @param query The search string
     */
    public static FutureTask<List<FeedItem>> searchFeedItemDescription(final Context context,
                                                                       final long feedID, final String query) {
        return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) {
            @Override
            public void execute(PodDBAdapter adapter) {
                Cursor searchResult = adapter.searchItemDescriptions(feedID,
                        query);
                List<FeedItem> items = DBReader.extractItemlistFromCursor(context, searchResult);
                DBReader.loadFeedDataOfFeedItemlist(context, items);
                setResult(items);
                searchResult.close();
            }
        });
    }

    /**
     * Searches the 'contentEncoded' field of FeedItems of a specific feed for a
     * given string.
     *
     * @param feedID  The id of the feed whose items should be searched.
     * @param query The search string
     */
    public static FutureTask<List<FeedItem>> searchFeedItemContentEncoded(final Context context,
                                                                          final long feedID, final String query) {
        return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) {
            @Override
            public void execute(PodDBAdapter adapter) {
                Cursor searchResult = adapter.searchItemContentEncoded(feedID,
                        query);
                List<FeedItem> items = DBReader.extractItemlistFromCursor(context, searchResult);
                DBReader.loadFeedDataOfFeedItemlist(context, items);
                setResult(items);
                searchResult.close();
            }
        });
    }

    /**
     * Searches chapters for a given string.
     *
     * @param feedID  The id of the feed whose items should be searched.
     * @param query The search string
     */
    public static FutureTask<List<FeedItem>> searchFeedItemChapters(final Context context,
                                                                    final long feedID, final String query) {
        return new FutureTask<List<FeedItem>>(new QueryTask<List<FeedItem>>(context) {
            @Override
            public void execute(PodDBAdapter adapter) {
                Cursor searchResult = adapter.searchItemChapters(feedID,
                        query);
                List<FeedItem> items = DBReader.extractItemlistFromCursor(context, searchResult);
                DBReader.loadFeedDataOfFeedItemlist(context, items);
                setResult(items);
                searchResult.close();
            }
        });
    }

    /**
     * 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.
     */
    static abstract class QueryTask<T> implements Callable<T> {
        private T result;
        private Context context;

        public QueryTask(Context context) {
            this.context = context;
        }

        @Override
        public T call() throws Exception {
            PodDBAdapter adapter = new PodDBAdapter(context);
            adapter.open();
            execute(adapter);
            adapter.close();
            return result;
        }

        public abstract void execute(PodDBAdapter adapter);

        protected void setResult(T result) {
            this.result = result;
        }
    }

}