diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3e0248f..e4e433b 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -19,8 +19,8 @@ android { applicationId = "com.podbelly" minSdk = 26 targetSdk = 37 - versionCode = 119 - versionName = "1.6.71" + versionCode = 125 + versionName = "1.6.77" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/podbelly/AppViewModel.kt b/app/src/main/java/com/podbelly/AppViewModel.kt index 991f533..3d868cc 100644 --- a/app/src/main/java/com/podbelly/AppViewModel.kt +++ b/app/src/main/java/com/podbelly/AppViewModel.kt @@ -10,6 +10,7 @@ import com.podbelly.core.common.PreferencesManager import com.podbelly.core.common.RefreshProgress import com.podbelly.core.common.shouldAutoDownload import com.podbelly.core.database.dao.EpisodeDao +import com.podbelly.core.database.dao.FeedItemKey import com.podbelly.core.database.dao.ListeningSessionDao import com.podbelly.core.database.dao.PodcastDao import com.podbelly.core.database.entity.EpisodeEntity @@ -166,7 +167,13 @@ class AppViewModel @Inject constructor( } // insertAll ignores episodes that already exist (by podcastId+guid), - // so re-subscribing to a known show is safe. + // so re-subscribing to a known show is safe — once episodes whose GUID + // the host changed since are re-keyed rather than inserted again. + if (existing != null) { + episodeDao.repairChangedGuids(podcastId, feed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }) + } episodeDao.insertAll( feed.episodes.map { episode -> EpisodeEntity( @@ -201,7 +208,7 @@ class AppViewModel @Inject constructor( // Most of a feed fetch is server latency, not bandwidth, so wide // parallelism nearly divides refresh time by the concurrency. 32 is // safe now that feeds stream straight into the parser (memory per - // in-flight feed is just its parsed episodes, bounded by the 10MB + // in-flight feed is just its parsed episodes, bounded by the feed // read cap) — buffering whole documents was the old reason for 5. // Smart auto-download: new arrivals from engaged shows (or per-show // Always overrides) start downloading as soon as the refresh finds @@ -225,6 +232,13 @@ class AppViewModel @Inject constructor( semaphore.withPermit { try { val rssFeed = searchRepository.fetchFeed(podcast.feedUrl) + // Before matching by GUID: re-key episodes whose GUID the host changed. + episodeDao.repairChangedGuids( + podcast.id, + rssFeed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }, + ) // Insert new episodes; refresh feed-derived fields on // existing ones so publisher corrections propagate. diff --git a/app/src/main/java/com/podbelly/navigation/PodbellNavHost.kt b/app/src/main/java/com/podbelly/navigation/PodbellNavHost.kt index a48e5f9..e728b03 100644 --- a/app/src/main/java/com/podbelly/navigation/PodbellNavHost.kt +++ b/app/src/main/java/com/podbelly/navigation/PodbellNavHost.kt @@ -279,7 +279,10 @@ fun PodbellNavHost( DiscoverScreen( onPodcastClick = { podcastId -> navController.navigate(Screen.PodcastDetail.createRoute(podcastId)) - } + }, + onEpisodeClick = { episodeId -> + navController.navigate(Screen.EpisodeDetail.createRoute(episodeId)) + }, ) } diff --git a/app/src/main/java/com/podbelly/ui/WhatsNew.kt b/app/src/main/java/com/podbelly/ui/WhatsNew.kt index d54e18a..c17759c 100644 --- a/app/src/main/java/com/podbelly/ui/WhatsNew.kt +++ b/app/src/main/java/com/podbelly/ui/WhatsNew.kt @@ -13,9 +13,32 @@ object WhatsNew { // 107 was a dependency-catalog refresh (build/test only); no changelog entry. // 108-113 were a build-toolchain upgrade (AGP 9, Gradle 9); no changelog entries. // 114-115 were the Coil 2 -> 3 image-loader upgrade (internal); no changelog entries. - const val LATEST_VERSION_CODE = 118 + // 119 was CI-only (Gradle download retries); no changelog entry. + const val LATEST_VERSION_CODE = 125 val changelog: Map> = mapOf( + 125 to listOf( + "Episode show notes are shown in full — just scroll down to read them, no more Show more / Show less", + ), + 124 to listOf( + "Search episodes, not just shows: tap Episodes under the search box to find every episode with a guest or topic, and open one straight from the results", + "Narrow a show search to titles or hosts with the In title and By host filters", + "Searches now cover your chart region's store and return up to 100 shows", + "Charts go deeper: every category has its sub-categories (Sport → Rugby, News → Politics, and dozens more), and each chart now shows the top 200", + "New Trending episodes chart for your region, plus the Arts, Fiction, Kids & Family, Leisure, Religion & Spirituality and Government categories", + ), + 123 to listOf( + "Old episodes no longer reappear as new (or show up twice) when a podcast's host reshuffles its feed, as Blocked and Reported's did — and any copies that already slipped in are tidied up on the next refresh, keeping your progress and downloads", + ), + 122 to listOf( + "Opening a podcast you're not subscribed to — from search or the charts — now loads its latest episodes, instead of the list from the first time you looked at it", + ), + 121 to listOf( + "You can now subscribe to podcasts with very large feeds, such as Latent Space and other long-running Substack shows, which used to fail with \"Feed exceeds 10MB limit\"", + ), + 120 to listOf( + "Episodes a show releases ahead of their listed date no longer show as \"In 4 hr\" and stay stuck at the top of Home — they're dated from when they arrived until their listed date comes round", + ), 118 to listOf( "The Now Playing visualizer now moves in time with what you hear — it no longer runs ahead of the audio or stutters, including on Bluetooth headphones", ), diff --git a/app/src/main/java/com/podbelly/worker/FeedRefreshWorker.kt b/app/src/main/java/com/podbelly/worker/FeedRefreshWorker.kt index c0dde5d..9e80412 100644 --- a/app/src/main/java/com/podbelly/worker/FeedRefreshWorker.kt +++ b/app/src/main/java/com/podbelly/worker/FeedRefreshWorker.kt @@ -15,6 +15,7 @@ import com.podbelly.core.common.DownloadManager import com.podbelly.core.common.PreferencesManager import com.podbelly.core.common.shouldAutoDownload import com.podbelly.core.database.dao.EpisodeDao +import com.podbelly.core.database.dao.FeedItemKey import com.podbelly.core.database.dao.ListeningSessionDao import com.podbelly.core.database.dao.PodcastDao import com.podbelly.core.database.entity.EpisodeEntity @@ -69,6 +70,10 @@ class FeedRefreshWorker @AssistedInject constructor( for (podcast in podcasts) { try { val feed = searchRepository.fetchFeed(podcast.feedUrl) + // Before matching by GUID: re-key episodes whose GUID the host changed. + episodeDao.repairChangedGuids(podcast.id, feed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }) // Insert truly new episodes; refresh feed-derived fields on ones we // already have so publisher corrections (e.g. a changed audioUrl) propagate. diff --git a/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeDao.kt b/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeDao.kt index debfcaa..c51b6c7 100644 --- a/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeDao.kt +++ b/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeDao.kt @@ -4,6 +4,7 @@ import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query +import androidx.room.Transaction import androidx.room.Update import com.podbelly.core.database.entity.EpisodeEntity import kotlinx.coroutines.flow.Flow @@ -45,6 +46,12 @@ interface EpisodeDao { * episode is downloaded its fileSize holds the real on-disk byte count (written by * [setDownloadPath]); the RSS enclosure length is frequently 0 or inaccurate, so * overwriting it would corrupt storage accounting (getTotalDownloadedBytes). + * + * A publicationDate still in the future is not taken yet (see [insertAll]): the + * stored date is kept, a stored future date (saved before this rule existed) + * falls back to when the episode was discovered, and the feed's real date is + * adopted once it has passed. Otherwise every refresh would re-pin a + * pre-scheduled episode to the top of date-sorted lists. */ @Query( """ @@ -52,7 +59,12 @@ interface EpisodeDao { SET title = :title, description = :description, audioUrl = :audioUrl, - publicationDate = :publicationDate, + publicationDate = CASE + WHEN :publicationDate <= $NOW_MS THEN :publicationDate + WHEN publicationDate BETWEEN 1 AND $NOW_MS THEN publicationDate + WHEN addedAt BETWEEN 1 AND $NOW_MS THEN addedAt + ELSE $NOW_MS + END, durationSeconds = :durationSeconds, artworkUrl = :artworkUrl, fileSize = CASE WHEN downloadPath != '' THEN fileSize ELSE :fileSize END, @@ -142,8 +154,25 @@ interface EpisodeDao { ) fun getLibraryStats(): Flow + /** + * Inserts new episodes, ignoring ones already stored. Some publishers put an episode + * in the feed with a pubDate hours or days ahead (e.g. scheduled for tomorrow but + * already live); taken at face value it shows as "In 4 hr" and sits above every + * genuinely newer episode until that date passes. Like AntennaPod (which discards a + * future pubDate and falls back to the time the item was first seen), such an + * episode is dated when it was discovered instead. [updateFeedFields] adopts the + * feed's date once it's no longer in the future. + */ + suspend fun insertAll(episodes: List): List { + val now = System.currentTimeMillis() + return insertAllAsIs( + episodes.map { if (it.publicationDate > now) it.copy(publicationDate = now) else it } + ) + } + + /** Raw insert behind [insertAll]; call that instead so future dates get clamped. */ @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertAll(episodes: List): List + suspend fun insertAllAsIs(episodes: List): List @Update suspend fun update(episode: EpisodeEntity) @@ -187,6 +216,126 @@ interface EpisodeDao { @Query("DELETE FROM episodes WHERE podcastId = :podcastId") suspend fun deleteByPodcastId(podcastId: Long) + /** + * Repairs episodes whose GUID the publisher changed. Run before a refresh matches + * the feed against stored episodes by GUID. Some hosts rewrite GUIDs across a whole + * back catalogue (Substack added an ":unlocked" suffix to most of Blocked and + * Reported's episodes), and every rewritten episode then looked brand new: it was + * inserted a second time and flooded Home's New section. + * + * Adapted from AntennaPod's FeedDatabaseWriter + FeedItemDuplicateGuesser. A + * stored episode whose GUID is gone from the feed, and which [seemsSameEpisodeAs] + * a feed item, takes that item's GUID, keeping its play state, download and + * addedAt, so the refresh updates it instead of inserting a copy. If an earlier + * refresh already inserted that copy, the copy's play state, download and + * listening history move to the original and the copy is deleted. Episodes still + * in the feed under their own GUID are never matched, so two genuinely separate + * episodes with the same title are left alone. + * + * @return how many episodes were repaired. + */ + @Transaction + suspend fun repairChangedGuids(podcastId: Long, feedItems: List): Int { + val feedGuids = feedItems.mapTo(HashSet()) { it.guid } + val storedGuids = getGuidsForPodcast(podcastId) + // Fast path: nearly every refresh, every stored GUID is still in the feed. + if (storedGuids.all { it in feedGuids }) return 0 + + val stored = getMatchRowsForPodcast(podcastId) + val storedByGuid = stored.associateBy { it.guid } + val stale = stored.filter { it.guid !in feedGuids } + val staleByAudioUrl = stale.filter { it.audioUrl.isNotEmpty() }.groupBy { it.audioUrl } + val staleByTitle = stale.groupBy { normalizeTitleForMatch(it.title) } + val claimed = HashSet() + var repaired = 0 + + for (item in feedItems) { + val candidates = staleByAudioUrl[item.audioUrl].orEmpty() + + staleByTitle[normalizeTitleForMatch(item.title)].orEmpty() + val original = candidates.firstOrNull { it.id !in claimed && it.seemsSameEpisodeAs(item) } + ?: continue + + val copy = storedByGuid[item.guid] + if (copy != null) { + // Both downloaded: deleting the copy's row would orphan its file. + if (copy.downloadPath.isNotBlank() && original.downloadPath.isNotBlank()) continue + if (copy.played || copy.playbackPosition > 0L || copy.lastPlayedAt > 0L) { + mergePlayState( + id = original.id, + played = copy.played, + position = copy.playbackPosition, + lastPlayedAt = copy.lastPlayedAt, + ) + } + if (copy.downloadPath.isNotBlank()) { + adoptDownloadIfNone( + id = original.id, + path = copy.downloadPath, + downloadedAt = copy.downloadedAt, + fileSize = copy.fileSize, + autoDownloaded = copy.autoDownloaded, + ) + } + moveListeningSessions(fromEpisodeId = copy.id, toEpisodeId = original.id) + // Frees the GUID before the original takes it (unique per podcast). + deleteById(copy.id) + } + setGuid(original.id, item.guid) + claimed += original.id + repaired++ + } + return repaired + } + + @Query("SELECT guid FROM episodes WHERE podcastId = :podcastId") + suspend fun getGuidsForPodcast(podcastId: Long): List + + @Query( + """ + SELECT id, guid, title, audioUrl, publicationDate, durationSeconds, played, + playbackPosition, lastPlayedAt, downloadPath, downloadedAt, fileSize, autoDownloaded + FROM episodes WHERE podcastId = :podcastId + """ + ) + suspend fun getMatchRowsForPodcast(podcastId: Long): List + + /** Play state only moves forward: played can only turn on, position/lastPlayedAt only grow. */ + @Query( + """ + UPDATE episodes + SET played = CASE WHEN :played THEN 1 ELSE played END, + playbackPosition = MAX(playbackPosition, :position), + lastPlayedAt = MAX(lastPlayedAt, :lastPlayedAt) + WHERE id = :id + """ + ) + suspend fun mergePlayState(id: Long, played: Boolean, position: Long, lastPlayedAt: Long) + + @Query( + """ + UPDATE episodes + SET downloadPath = :path, downloadedAt = :downloadedAt, fileSize = :fileSize, + autoDownloaded = :autoDownloaded + WHERE id = :id AND downloadPath = '' + """ + ) + suspend fun adoptDownloadIfNone( + id: Long, + path: String, + downloadedAt: Long, + fileSize: Long, + autoDownloaded: Boolean, + ) + + @Query("UPDATE listening_sessions SET episodeId = :toEpisodeId WHERE episodeId = :fromEpisodeId") + suspend fun moveListeningSessions(fromEpisodeId: Long, toEpisodeId: Long) + + @Query("UPDATE episodes SET guid = :guid WHERE id = :id") + suspend fun setGuid(id: Long, guid: String) + + @Query("DELETE FROM episodes WHERE id = :id") + suspend fun deleteById(id: Long) + @Query("SELECT * FROM episodes WHERE played = 1 AND downloadPath != ''") suspend fun getPlayedDownloadedEpisodes(): List @@ -271,3 +420,6 @@ data class LibraryStat( val episodeCount: Int, val playedCount: Int, ) + +/** SQLite's current time in epoch millis, for queries comparing against stored dates. */ +private const val NOW_MS = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)" diff --git a/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeGuidRepair.kt b/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeGuidRepair.kt new file mode 100644 index 0000000..df02ba9 --- /dev/null +++ b/core/database/src/main/java/com/podbelly/core/database/dao/EpisodeGuidRepair.kt @@ -0,0 +1,52 @@ +package com.podbelly.core.database.dao + +import androidx.room.ColumnInfo +import kotlin.math.abs + +/** What a feed item says about itself, for [EpisodeDao.repairChangedGuids]. */ +data class FeedItemKey( + val guid: String, + val title: String, + val audioUrl: String, + val publicationDate: Long, + val durationSeconds: Int, +) + +/** + * The stored columns [EpisodeDao.repairChangedGuids] needs: enough to match an + * episode and carry its user state over, without loading every description (a + * long-running Substack feed stores megabytes of show notes). + */ +data class EpisodeMatchRow( + @ColumnInfo(name = "id") val id: Long, + @ColumnInfo(name = "guid") val guid: String, + @ColumnInfo(name = "title") val title: String, + @ColumnInfo(name = "audioUrl") val audioUrl: String, + @ColumnInfo(name = "publicationDate") val publicationDate: Long, + @ColumnInfo(name = "durationSeconds") val durationSeconds: Int, + @ColumnInfo(name = "played") val played: Boolean, + @ColumnInfo(name = "playbackPosition") val playbackPosition: Long, + @ColumnInfo(name = "lastPlayedAt") val lastPlayedAt: Long, + @ColumnInfo(name = "downloadPath") val downloadPath: String, + @ColumnInfo(name = "downloadedAt") val downloadedAt: Long, + @ColumnInfo(name = "fileSize") val fileSize: Long, + @ColumnInfo(name = "autoDownloaded") val autoDownloaded: Boolean, +) + +/** + * Whether a stored episode and a feed item look like the same episode even though + * their GUIDs differ. Same rules as AntennaPod's FeedItemDuplicateGuesser: the same + * audio URL, or the same title published the same day at about the same length. + */ +internal fun EpisodeMatchRow.seemsSameEpisodeAs(item: FeedItemKey): Boolean { + if (audioUrl.isNotEmpty() && audioUrl == item.audioUrl) return true + val normalizedTitle = normalizeTitleForMatch(title) + return normalizedTitle.isNotEmpty() && + normalizedTitle == normalizeTitleForMatch(item.title) && + publicationDate > 0L && item.publicationDate > 0L && + publicationDate / DAY_MS == item.publicationDate / DAY_MS && + abs(durationSeconds - item.durationSeconds) < MAX_DURATION_DIFF_SECONDS +} + +private const val DAY_MS = 24 * 60 * 60 * 1000L +private const val MAX_DURATION_DIFF_SECONDS = 10 * 60 diff --git a/core/database/src/main/java/com/podbelly/core/database/entity/EpisodeEntity.kt b/core/database/src/main/java/com/podbelly/core/database/entity/EpisodeEntity.kt index 5373f12..cd9b687 100644 --- a/core/database/src/main/java/com/podbelly/core/database/entity/EpisodeEntity.kt +++ b/core/database/src/main/java/com/podbelly/core/database/entity/EpisodeEntity.kt @@ -107,7 +107,9 @@ data class EpisodeEntity( * what keeps the UI smooth while a large refresh runs. * * Mirrors updateFeedFields' semantics exactly, including fileSize being ignored - * once the episode is downloaded (the row then holds the real on-disk size). + * once the episode is downloaded (the row then holds the real on-disk size), and + * a still-future publicationDate leaving an already-valid stored date alone (a + * stored future date still needs the write, which repairs it). */ fun EpisodeEntity.hasSameFeedFields( title: String, @@ -119,11 +121,13 @@ fun EpisodeEntity.hasSameFeedFields( fileSize: Long, transcriptUrl: String, transcriptType: String, + now: Long = System.currentTimeMillis(), ): Boolean = this.title == title && this.description == description && this.audioUrl == audioUrl && - this.publicationDate == publicationDate && + (if (publicationDate > now) this.publicationDate in 1..now + else this.publicationDate == publicationDate) && this.durationSeconds == durationSeconds && this.artworkUrl == artworkUrl && this.transcriptUrl == transcriptUrl && diff --git a/core/database/src/test/java/com/podbelly/core/database/dao/EpisodeDaoTest.kt b/core/database/src/test/java/com/podbelly/core/database/dao/EpisodeDaoTest.kt index 864493f..87e52ea 100644 --- a/core/database/src/test/java/com/podbelly/core/database/dao/EpisodeDaoTest.kt +++ b/core/database/src/test/java/com/podbelly/core/database/dao/EpisodeDaoTest.kt @@ -6,7 +6,10 @@ import androidx.test.core.app.ApplicationProvider import app.cash.turbine.test import com.podbelly.core.database.PodbellDatabase import com.podbelly.core.database.entity.EpisodeEntity +import com.podbelly.core.database.entity.ListeningSessionEntity import com.podbelly.core.database.entity.PodcastEntity +import com.podbelly.core.database.entity.hasSameFeedFields +import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertEquals @@ -436,4 +439,242 @@ class EpisodeDaoTest { assertTrue(episodeDao.getAutoDownloadsBeyondNewest(podcastId, 0).isEmpty()) assertEquals(false, episodeDao.getByIdOnce(ids[0])!!.autoDownloaded) } + + private suspend fun refreshFeedDate(guid: String, publicationDate: Long) { + episodeDao.updateFeedFields( + podcastId = podcastId, + guid = guid, + title = "Episode 1", + description = "Episode description", + audioUrl = "https://example.com/audio.mp3", + publicationDate = publicationDate, + durationSeconds = 3600, + artworkUrl = "", + fileSize = 0L, + transcriptUrl = "", + transcriptType = "", + ) + } + + @Test + fun `insertAll dates a future-dated episode when it was discovered`() = runTest { + val before = System.currentTimeMillis() + val tomorrow = before + DAY_MS + episodeDao.insertAll(listOf(createEpisode(guid = "early", publicationDate = tomorrow))) + val after = System.currentTimeMillis() + + val date = episodeDao.getByGuid("early")!!.publicationDate + assertTrue("expected discovery time, was $date", date in before..after) + } + + @Test + fun `insertAll keeps past publication dates as published`() = runTest { + val yesterday = System.currentTimeMillis() - DAY_MS + episodeDao.insertAll(listOf(createEpisode(guid = "old", publicationDate = yesterday))) + + assertEquals(yesterday, episodeDao.getByGuid("old")!!.publicationDate) + } + + @Test + fun `updateFeedFields keeps the stored date while the feed date is still in the future`() = runTest { + val discovered = System.currentTimeMillis() - 60_000L + episodeDao.insertAll(listOf(createEpisode(guid = "early", publicationDate = discovered))) + + refreshFeedDate("early", System.currentTimeMillis() + DAY_MS) + + assertEquals(discovered, episodeDao.getByGuid("early")!!.publicationDate) + } + + @Test + fun `updateFeedFields adopts the feed date once it has passed`() = runTest { + val discovered = System.currentTimeMillis() - 60_000L + episodeDao.insertAll(listOf(createEpisode(guid = "early", publicationDate = discovered))) + + val published = System.currentTimeMillis() - 1_000L + refreshFeedDate("early", published) + + assertEquals(published, episodeDao.getByGuid("early")!!.publicationDate) + } + + @Test + fun `updateFeedFields repairs a stored future date to when the episode was discovered`() = runTest { + // A row saved before future dates were clamped on insert. + val addedAt = System.currentTimeMillis() - 60_000L + val tomorrow = System.currentTimeMillis() + DAY_MS + episodeDao.insertAllAsIs( + listOf(createEpisode(guid = "early", publicationDate = tomorrow, addedAt = addedAt)) + ) + + refreshFeedDate("early", tomorrow) + + assertEquals(addedAt, episodeDao.getByGuid("early")!!.publicationDate) + } + + @Test + fun `hasSameFeedFields ignores a future feed date that would not be applied`() { + val now = 10_000_000L + val stored = createEpisode(publicationDate = now - 1_000L) + + fun same(publicationDate: Long) = stored.hasSameFeedFields( + title = stored.title, + description = stored.description, + audioUrl = stored.audioUrl, + publicationDate = publicationDate, + durationSeconds = stored.durationSeconds, + artworkUrl = stored.artworkUrl, + fileSize = stored.fileSize, + transcriptUrl = stored.transcriptUrl, + transcriptType = stored.transcriptType, + now = now, + ) + + assertTrue(same(now + DAY_MS)) + assertEquals(false, same(now - 2_000L)) + + // A stored future date (saved before clamping) must still be written so the + // update can repair it, even when the feed repeats the same value. + val storedFuture = stored.copy(publicationDate = now + DAY_MS) + assertEquals( + false, + storedFuture.hasSameFeedFields( + title = stored.title, + description = stored.description, + audioUrl = stored.audioUrl, + publicationDate = now + DAY_MS, + durationSeconds = stored.durationSeconds, + artworkUrl = stored.artworkUrl, + fileSize = stored.fileSize, + transcriptUrl = stored.transcriptUrl, + transcriptType = stored.transcriptType, + now = now, + ), + ) + } + + // -- repairChangedGuids -- + + private fun feedItem( + guid: String, + title: String = "Episode 1", + audioUrl: String = "https://example.com/audio.mp3", + publicationDate: Long = 1000L, + durationSeconds: Int = 3600, + ) = FeedItemKey(guid, title, audioUrl, publicationDate, durationSeconds) + + @Test + fun `repairChangedGuids re-keys an episode whose GUID the host changed`() = runTest { + val ids = episodeDao.insertAll( + listOf(createEpisode(guid = "substack:post:1", played = true, addedAt = 500L)) + ) + + val repaired = episodeDao.repairChangedGuids(podcastId, listOf(feedItem("substack:post:1:unlocked"))) + + assertEquals(1, repaired) + val episode = episodeDao.getByPodcastAndGuid(podcastId, "substack:post:1:unlocked")!! + // Same row: play state kept, and its original addedAt keeps it out of New. + assertEquals(ids[0], episode.id) + assertTrue(episode.played) + assertEquals(500L, episode.addedAt) + assertEquals(1, episodeDao.countByPodcastId(podcastId)) + } + + @Test + fun `repairChangedGuids matches by title, day and length when the audio URL changed too`() = runTest { + val day = 20_000L * DAY_MS + episodeDao.insertAll( + listOf( + createEpisode( + guid = "old", + audioUrl = "https://old-host.example/ep.mp3", + publicationDate = day + 1_000L, + durationSeconds = 3600, + ) + ) + ) + + val repaired = episodeDao.repairChangedGuids( + podcastId, + listOf( + feedItem( + guid = "new", + audioUrl = "https://tracker.example/new-host.example/ep.mp3", + publicationDate = day + 5_000L, + durationSeconds = 3540, + ) + ), + ) + + assertEquals(1, repaired) + assertNotNull(episodeDao.getByPodcastAndGuid(podcastId, "new")) + assertNull(episodeDao.getByPodcastAndGuid(podcastId, "old")) + } + + @Test + fun `repairChangedGuids folds a copy already inserted under the new GUID into the original`() = runTest { + val ids = episodeDao.insertAll( + listOf( + createEpisode(guid = "substack:post:1", played = true, addedAt = 500L), + createEpisode( + guid = "substack:post:1:unlocked", + playbackPosition = 9_000L, + downloadPath = "/files/copy.mp3", + downloadedAt = 7_000L, + fileSize = 1234L, + addedAt = 99_000L, + ), + ) + ) + database.listeningSessionDao().insert( + ListeningSessionEntity(episodeId = ids[1], podcastId = podcastId, startedAt = 8_000L) + ) + + val repaired = episodeDao.repairChangedGuids(podcastId, listOf(feedItem("substack:post:1:unlocked"))) + + assertEquals(1, repaired) + assertEquals(1, episodeDao.countByPodcastId(podcastId)) + val episode = episodeDao.getByPodcastAndGuid(podcastId, "substack:post:1:unlocked")!! + assertEquals(ids[0], episode.id) + assertEquals(500L, episode.addedAt) + assertTrue(episode.played) + assertEquals(9_000L, episode.playbackPosition) + assertEquals("/files/copy.mp3", episode.downloadPath) + assertEquals(1234L, episode.fileSize) + // Moved, not cascade-deleted with the copy. + assertEquals(1, database.listeningSessionDao().getSessionCount().first()) + } + + @Test + fun `repairChangedGuids leaves same-titled episodes alone while both are in the feed`() = runTest { + episodeDao.insertAll(listOf(createEpisode(guid = "a"), createEpisode(guid = "b"))) + + val repaired = episodeDao.repairChangedGuids(podcastId, listOf(feedItem("a"), feedItem("b"))) + + assertEquals(0, repaired) + assertEquals(2, episodeDao.countByPodcastId(podcastId)) + } + + @Test + fun `repairChangedGuids does not match an unrelated episode that left the feed`() = runTest { + episodeDao.insertAll( + listOf( + createEpisode( + guid = "dropped", + title = "An Old Episode", + audioUrl = "https://example.com/old.mp3", + ) + ) + ) + + val repaired = episodeDao.repairChangedGuids( + podcastId, + listOf(feedItem("brand-new", title = "A New Episode", audioUrl = "https://example.com/new.mp3")), + ) + + assertEquals(0, repaired) + assertNotNull(episodeDao.getByPodcastAndGuid(podcastId, "dropped")) + } + + private companion object { + const val DAY_MS = 24 * 60 * 60 * 1000L + } } diff --git a/core/network/src/main/java/com/podbelly/core/network/api/ItunesSearchApi.kt b/core/network/src/main/java/com/podbelly/core/network/api/ItunesSearchApi.kt index 7c07fef..2b51a8d 100644 --- a/core/network/src/main/java/com/podbelly/core/network/api/ItunesSearchApi.kt +++ b/core/network/src/main/java/com/podbelly/core/network/api/ItunesSearchApi.kt @@ -5,17 +5,37 @@ import com.squareup.moshi.JsonClass import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query +import retrofit2.http.Url interface ItunesSearchApi { + /** + * [attribute] narrows which field [term] is matched against ("titleTerm", + * "artistTerm"); null searches everything. [country] picks the storefront (shows + * only listed in some countries are missing from the default US one). Null query + * parameters are left out of the request. 200 is iTunes' documented maximum, but + * it returns at most 100 podcasts in practice. + */ @GET("search") suspend fun searchPodcasts( @Query("term") term: String, @Query("media") media: String = "podcast", @Query("entity") entity: String = "podcast", - @Query("limit") limit: Int = 30 + @Query("limit") limit: Int = 100, + @Query("attribute") attribute: String? = null, + @Query("country") country: String? = null, ): ItunesSearchResponse + /** Episode search: every result carries its show's feed URL and the episode GUID. */ + @GET("search") + suspend fun searchEpisodes( + @Query("term") term: String, + @Query("media") media: String = "podcast", + @Query("entity") entity: String = "podcastEpisode", + @Query("limit") limit: Int = 50, + @Query("country") country: String? = null, + ): ItunesEpisodeSearchResponse + /** * Looks up podcasts by their iTunes collection ids ([ids] is comma-separated). * The chart feed below doesn't include feed URLs, so chart entries are enriched @@ -37,6 +57,14 @@ interface ItunesSearchApi { @Path("genre") genre: Int, @Path("limit") limit: Int = 25 ): ItunesTopPodcastsResponse + + /** + * Apple's trending-episodes chart for a country, from the Marketing Tools feed + * service (a different host, hence the full [url]). Entries carry no feed URL + * or GUID, only the episode's Apple Podcasts link, which contains its show id. + */ + @GET + suspend fun trendingEpisodes(@Url url: String): AppleChartResponse } @JsonClass(generateAdapter = true) @@ -83,3 +111,41 @@ data class ItunesTopEntryId( data class ItunesTopEntryIdAttributes( @Json(name = "im:id") val imId: String? ) + +@JsonClass(generateAdapter = true) +data class ItunesEpisodeSearchResponse( + @Json(name = "resultCount") val resultCount: Int, + @Json(name = "results") val results: List +) + +@JsonClass(generateAdapter = true) +data class ItunesEpisode( + @Json(name = "trackName") val trackName: String?, + @Json(name = "collectionName") val collectionName: String?, + @Json(name = "feedUrl") val feedUrl: String?, + @Json(name = "episodeGuid") val episodeGuid: String?, + /** ISO-8601, e.g. "2026-10-11T10:00:00Z". */ + @Json(name = "releaseDate") val releaseDate: String?, + @Json(name = "trackTimeMillis") val trackTimeMillis: Long?, + @Json(name = "artworkUrl600") val artworkUrl600: String?, + @Json(name = "episodeUrl") val episodeUrl: String?, +) + +@JsonClass(generateAdapter = true) +data class AppleChartResponse( + @Json(name = "feed") val feed: AppleChartFeed +) + +@JsonClass(generateAdapter = true) +data class AppleChartFeed( + @Json(name = "results") val results: List? +) + +@JsonClass(generateAdapter = true) +data class AppleChartEntry( + @Json(name = "name") val name: String?, + @Json(name = "artistName") val artistName: String?, + @Json(name = "artworkUrl100") val artworkUrl100: String?, + /** Apple Podcasts link, e.g. ".../podcast/some-title/id1692381473?i=1000798385938". */ + @Json(name = "url") val url: String?, +) diff --git a/core/network/src/main/java/com/podbelly/core/network/api/PodcastSearchRepository.kt b/core/network/src/main/java/com/podbelly/core/network/api/PodcastSearchRepository.kt index 394b942..fd585d5 100644 --- a/core/network/src/main/java/com/podbelly/core/network/api/PodcastSearchRepository.kt +++ b/core/network/src/main/java/com/podbelly/core/network/api/PodcastSearchRepository.kt @@ -1,6 +1,8 @@ package com.podbelly.core.network.api +import com.podbelly.core.network.model.EpisodeSearchResult import com.podbelly.core.network.model.RssFeed +import com.podbelly.core.network.model.SearchField import com.podbelly.core.network.model.SearchResult import com.podbelly.core.network.rss.RssParser import kotlinx.coroutines.Dispatchers @@ -10,6 +12,7 @@ import okhttp3.Request import java.io.FilterInputStream import java.io.IOException import java.io.InputStream +import java.time.Instant import javax.inject.Inject class PodcastSearchRepository @Inject constructor( @@ -21,20 +24,86 @@ class PodcastSearchRepository @Inject constructor( /** * Searches for podcasts using the iTunes Search API and maps * the results to our domain [SearchResult] model. + * + * @param field which field to match [query] against. + * @param country storefront to search ("ie", "gb", …); null uses iTunes' default (US). */ - suspend fun search(query: String): List { - val response = itunesSearchApi.searchPodcasts(term = query) + suspend fun search( + query: String, + field: SearchField = SearchField.ANYTHING, + country: String? = null, + ): List { + val attribute = when (field) { + SearchField.ANYTHING -> null + SearchField.TITLE -> "titleTerm" + SearchField.AUTHOR -> "artistTerm" + } + val response = itunesSearchApi.searchPodcasts( + term = query, + attribute = attribute, + country = country, + ) return response.results .filter { !it.feedUrl.isNullOrBlank() } - .map { podcast -> - SearchResult( - feedUrl = podcast.feedUrl.orEmpty().trim(), - title = (podcast.trackName ?: podcast.collectionName).orEmpty(), - author = podcast.artistName.orEmpty(), - artworkUrl = podcast.artworkUrl600.orEmpty() + .map { it.toSearchResult() } + .distinctBy { it.feedUrl } + } + + /** + * Searches episodes across all podcasts (e.g. a guest's name finds every show + * they appeared on). Results without a feed URL can't be opened and are dropped. + */ + suspend fun searchEpisodes(query: String, country: String? = null): List { + val response = itunesSearchApi.searchEpisodes(term = query, country = country) + return response.results + .filter { !it.feedUrl.isNullOrBlank() && !it.trackName.isNullOrBlank() } + .map { episode -> + EpisodeSearchResult( + title = episode.trackName.orEmpty(), + podcastTitle = episode.collectionName.orEmpty(), + feedUrl = episode.feedUrl.orEmpty().trim(), + artworkUrl = episode.artworkUrl600.orEmpty(), + episodeGuid = episode.episodeGuid?.takeIf { it.isNotBlank() }, + audioUrl = episode.episodeUrl?.takeIf { it.isNotBlank() }, + publishedAt = episode.releaseDate?.let(::parseInstantMillis) ?: 0L, + durationSeconds = ((episode.trackTimeMillis ?: 0L) / 1000).toInt(), ) } - .distinctBy { it.feedUrl } + } + + /** + * Apple's trending-episodes chart for [country]. Entries only name the episode + * and link to it on Apple Podcasts, so their shows' feed URLs come from one + * batched lookup of the show ids in those links; entries whose show can't be + * resolved are dropped. Chart order is preserved. + */ + suspend fun trendingEpisodes(country: String, limit: Int = 50): List { + val chart = itunesSearchApi.trendingEpisodes( + "$APPLE_CHARTS_BASE_URL/$country/podcasts/top/$limit/podcast-episodes.json" + ) + val entries = chart.feed.results.orEmpty().mapNotNull { entry -> + val showId = entry.url?.let { SHOW_ID_IN_URL.find(it)?.groupValues?.get(1) } + if (showId == null || entry.name.isNullOrBlank()) null else showId to entry + } + if (entries.isEmpty()) return emptyList() + + val shows = itunesSearchApi + .lookupPodcasts(ids = entries.map { it.first }.distinct().joinToString(",")) + .results + .filter { !it.feedUrl.isNullOrBlank() } + .associateBy { it.collectionId?.toString() } + + return entries.mapNotNull { (showId, entry) -> + val show = shows[showId] ?: return@mapNotNull null + EpisodeSearchResult( + title = entry.name.orEmpty(), + podcastTitle = (show.collectionName ?: show.trackName ?: entry.artistName).orEmpty(), + feedUrl = show.feedUrl.orEmpty().trim(), + // The chart links 100px artwork; Apple serves other sizes from the same path. + artworkUrl = entry.artworkUrl100?.replace("100x100", "600x600") + ?: show.artworkUrl600.orEmpty(), + ) + } } /** @@ -59,17 +128,24 @@ class PodcastSearchRepository @Inject constructor( return lookup.results .filter { !it.feedUrl.isNullOrBlank() } .sortedBy { rankById[it.collectionId?.toString()] ?: Int.MAX_VALUE } - .map { podcast -> - SearchResult( - feedUrl = podcast.feedUrl.orEmpty().trim(), - title = (podcast.trackName ?: podcast.collectionName).orEmpty(), - author = podcast.artistName.orEmpty(), - artworkUrl = podcast.artworkUrl600.orEmpty() - ) - } + .map { it.toSearchResult() } .distinctBy { it.feedUrl } } + private fun ItunesPodcast.toSearchResult() = SearchResult( + feedUrl = feedUrl.orEmpty().trim(), + title = (trackName ?: collectionName).orEmpty(), + author = artistName.orEmpty(), + artworkUrl = artworkUrl600.orEmpty() + ) + + private fun parseInstantMillis(iso: String): Long? = + try { + Instant.parse(iso).toEpochMilli() + } catch (_: Exception) { + null + } + /** * Fetches the RSS feed at the given [feedUrl] and parses it into * an [RssFeed] domain model. Follows redirects and sets a proper User-Agent. @@ -148,7 +224,19 @@ class PodcastSearchRepository @Inject constructor( private const val USER_AGENT = "Podbelly/1.0 (Android; Podcast App) OkHttp" - /** Maximum bytes we will read from a single feed (10 MB). */ - private const val MAX_FEED_BYTES = 10L * 1024 * 1024 + private const val APPLE_CHARTS_BASE_URL = "https://rss.marketingtools.apple.com/api/v2" + + /** The show id in an Apple Podcasts link: ".../id1692381473?i=…". */ + private val SHOW_ID_IN_URL = Regex("""/id(\d+)""") + + /** + * Maximum bytes we will read from a single feed (50 MB). Only a guard against + * runaway or hostile streams, not a sanity check on real feeds: Substack + * embeds every episode's full show notes, so a long-running show's feed + * passes 10 MB (Latent Space: ~14 MB for 231 episodes) and keeps growing. + * AntennaPod has no cap at all. Streaming parsing keeps memory to the + * parsed episodes, not the document. + */ + internal const val MAX_FEED_BYTES = 50L * 1024 * 1024 } } diff --git a/core/network/src/main/java/com/podbelly/core/network/model/SearchResult.kt b/core/network/src/main/java/com/podbelly/core/network/model/SearchResult.kt index 3d2c25d..5ea8d48 100644 --- a/core/network/src/main/java/com/podbelly/core/network/model/SearchResult.kt +++ b/core/network/src/main/java/com/podbelly/core/network/model/SearchResult.kt @@ -7,3 +7,28 @@ data class SearchResult( val artworkUrl: String, val description: String = "" ) + +/** Which field a podcast search matches the query against. */ +enum class SearchField { + /** Title, author, description and keywords. */ + ANYTHING, + TITLE, + /** The podcast's creator / host ("artist" in iTunes terms). */ + AUTHOR, +} + +/** + * An episode found by episode search or the trending-episodes chart. [episodeGuid], + * [publishedAt] and [durationSeconds] are unknown (null / 0) for trending entries, + * which only give a title and show. + */ +data class EpisodeSearchResult( + val title: String, + val podcastTitle: String, + val feedUrl: String, + val artworkUrl: String, + val episodeGuid: String? = null, + val audioUrl: String? = null, + val publishedAt: Long = 0L, + val durationSeconds: Int = 0, +) diff --git a/core/network/src/main/java/com/podbelly/core/network/transcript/TranscriptParser.kt b/core/network/src/main/java/com/podbelly/core/network/transcript/TranscriptParser.kt index a73f0f5..d941a17 100644 --- a/core/network/src/main/java/com/podbelly/core/network/transcript/TranscriptParser.kt +++ b/core/network/src/main/java/com/podbelly/core/network/transcript/TranscriptParser.kt @@ -222,7 +222,7 @@ class TranscriptParser @Inject constructor( companion object { private val moshi: Moshi = Moshi.Builder().build() - /** Maximum bytes we will read from a transcript (same 10MB cap as feeds). */ + /** Maximum bytes we will read from a transcript (10 MB). */ private const val MAX_TRANSCRIPT_BYTES = 10L * 1024 * 1024 // Optional hours, then MM:SS with optional .mmm or ,mmm — covers VTT diff --git a/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryIntegrationTest.kt b/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryIntegrationTest.kt index cec2a29..3540543 100644 --- a/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryIntegrationTest.kt +++ b/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryIntegrationTest.kt @@ -1,5 +1,6 @@ package com.podbelly.core.network.api +import com.podbelly.core.network.model.SearchField import com.podbelly.core.network.rss.RssParser import com.squareup.moshi.Moshi import kotlinx.coroutines.Dispatchers @@ -13,6 +14,8 @@ import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -602,4 +605,137 @@ class PodcastSearchRepositoryIntegrationTest { // When is missing, the parser falls back to using feedUrl assertEquals(feedUrl, feed.link) } + + @Test + fun `fetchFeed loads a feed larger than 10MB`() = runTest { + // Substack embeds full show notes per episode; Latent Space's feed is ~14MB. + val showNotes = "

" + "Show notes paragraph. ".repeat(3_000) + "

" + val items = (1..250).joinToString("") { i -> + """ + + Episode $i + ep-$i + Mon, 01 Jan 2024 00:00:00 +0000 + + + + """ + } + val rssXml = """ + Big Feed$items""" + assertTrue(rssXml.length > 15 * 1024 * 1024) + assertTrue(rssXml.length < PodcastSearchRepository.MAX_FEED_BYTES) + + mockWebServer.enqueue(MockResponse().setResponseCode(HttpURLConnection.HTTP_OK).setBody(rssXml)) + + val feed = repository.fetchFeed(mockWebServer.url("/feed.xml").toString()) + + assertEquals(250, feed.episodes.size) + } + + @Test + fun `search by host sends artistTerm and the storefront country`() = runTest { + mockWebServer.enqueue( + MockResponse() + .setBody("""{"resultCount": 0, "results": []}""") + .setHeader("Content-Type", "application/json") + ) + + repository.search("rogan", SearchField.AUTHOR, "ie") + + val path = mockWebServer.takeRequest().path!! + assertTrue(path.contains("attribute=artistTerm")) + assertTrue(path.contains("country=ie")) + assertTrue(path.contains("limit=100")) + } + + @Test + fun `search anywhere sends no attribute`() = runTest { + mockWebServer.enqueue( + MockResponse() + .setBody("""{"resultCount": 0, "results": []}""") + .setHeader("Content-Type", "application/json") + ) + + repository.search("rogan") + + val path = mockWebServer.takeRequest().path!! + assertFalse(path.contains("attribute=")) + assertFalse(path.contains("country=")) + } + + @Test + fun `searchEpisodes maps episode results and drops ones without a feed`() = runTest { + val json = """ + { + "resultCount": 2, + "results": [ + { + "wrapperType": "podcastEpisode", + "kind": "podcast-episode", + "trackName": "#2525 - Nick Bostrom", + "collectionName": "The Joe Rogan Experience", + "feedUrl": "https://feeds.example.com/jre", + "episodeGuid": "guid-2525", + "releaseDate": "2026-07-14T17:00:00Z", + "trackTimeMillis": 8400000, + "artworkUrl600": "https://img.example.com/jre.jpg", + "episodeUrl": "https://audio.example.com/2525.mp3" + }, + { + "wrapperType": "podcastEpisode", + "trackName": "Orphan Episode" + } + ] + } + """.trimIndent() + mockWebServer.enqueue( + MockResponse() + .setBody(json) + .setHeader("Content-Type", "application/json") + ) + + val results = repository.searchEpisodes("nick bostrom", "gb") + + assertEquals(1, results.size) + val episode = results[0] + assertEquals("#2525 - Nick Bostrom", episode.title) + assertEquals("The Joe Rogan Experience", episode.podcastTitle) + assertEquals("https://feeds.example.com/jre", episode.feedUrl) + assertEquals("guid-2525", episode.episodeGuid) + assertEquals("https://audio.example.com/2525.mp3", episode.audioUrl) + assertEquals(java.time.Instant.parse("2026-07-14T17:00:00Z").toEpochMilli(), episode.publishedAt) + assertEquals(8400, episode.durationSeconds) + + val path = mockWebServer.takeRequest().path!! + assertTrue(path.contains("entity=podcastEpisode")) + assertTrue(path.contains("country=gb")) + } + + @Test + fun `searchEpisodes tolerates a missing or malformed release date`() = runTest { + val json = """ + { + "resultCount": 1, + "results": [ + { + "trackName": "Undated", + "feedUrl": "https://feeds.example.com/x", + "releaseDate": "not a date" + } + ] + } + """.trimIndent() + mockWebServer.enqueue( + MockResponse() + .setBody(json) + .setHeader("Content-Type", "application/json") + ) + + val episode = repository.searchEpisodes("x").single() + + assertEquals(0L, episode.publishedAt) + assertEquals(0, episode.durationSeconds) + assertNull(episode.episodeGuid) + } } diff --git a/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryTrendingTest.kt b/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryTrendingTest.kt new file mode 100644 index 0000000..2d2e42c --- /dev/null +++ b/core/network/src/test/java/com/podbelly/core/network/api/PodcastSearchRepositoryTrendingTest.kt @@ -0,0 +1,77 @@ +package com.podbelly.core.network.api + +import com.podbelly.core.network.rss.RssParser +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.mockk +import kotlinx.coroutines.test.runTest +import okhttp3.OkHttpClient +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class PodcastSearchRepositoryTrendingTest { + + private val api = mockk() + private val repository = PodcastSearchRepository(api, OkHttpClient(), RssParser()) + + private fun entry(name: String, showId: String) = AppleChartEntry( + name = name, + artistName = "Publisher", + artworkUrl100 = "https://is1.example.com/art/100x100bb.png", + url = "https://podcasts.apple.com/ie/podcast/some-show/id$showId?i=1000000000001", + ) + + private fun show(id: Long, title: String, feedUrl: String?) = ItunesPodcast( + collectionId = id, + trackName = title, + artistName = "Publisher", + feedUrl = feedUrl, + artworkUrl600 = "https://is1.example.com/art/600x600bb.png", + collectionName = title, + ) + + @Test + fun `trending episodes resolve their shows' feeds in one lookup, keeping chart order`() = runTest { + coEvery { api.trendingEpisodes(any()) } returns AppleChartResponse( + AppleChartFeed( + listOf( + entry("Episode B", "222"), + entry("Episode A", "111"), + entry("Episode B2", "222"), + entry("No Feed", "333"), + AppleChartEntry(name = "No Link", artistName = null, artworkUrl100 = null, url = null), + ) + ) + ) + coEvery { api.lookupPodcasts(any(), any()) } returns ItunesSearchResponse( + resultCount = 3, + results = listOf( + show(111, "Show A", "https://feeds.example.com/a"), + show(222, "Show B", "https://feeds.example.com/b"), + show(333, "Show C", null), + ), + ) + + val results = repository.trendingEpisodes("ie", 25) + + assertEquals(listOf("Episode B", "Episode A", "Episode B2"), results.map { it.title }) + assertEquals("https://feeds.example.com/b", results[0].feedUrl) + assertEquals("Show B", results[0].podcastTitle) + assertEquals("https://is1.example.com/art/600x600bb.png", results[0].artworkUrl) + coVerify(exactly = 1) { api.lookupPodcasts("222,111,333", any()) } + coVerify { + api.trendingEpisodes( + match { it.endsWith("/ie/podcasts/top/25/podcast-episodes.json") && it.startsWith("https://") } + ) + } + } + + @Test + fun `an empty trending chart makes no lookup`() = runTest { + coEvery { api.trendingEpisodes(any()) } returns AppleChartResponse(AppleChartFeed(null)) + + assertTrue(repository.trendingEpisodes("ie").isEmpty()) + coVerify(exactly = 0) { api.lookupPodcasts(any(), any()) } + } +} diff --git a/feature/discover/src/main/java/com/podbelly/feature/discover/ChartCategories.kt b/feature/discover/src/main/java/com/podbelly/feature/discover/ChartCategories.kt new file mode 100644 index 0000000..be34077 --- /dev/null +++ b/feature/discover/src/main/java/com/podbelly/feature/discover/ChartCategories.kt @@ -0,0 +1,180 @@ +package com.podbelly.feature.discover + +/** + * Apple Podcasts' category tree: every top-level category with its sub-categories, + * each mapping a chip label to an iTunes genre id (any of which can be charted). + * Taken from Apple's genre service (itunes.apple.com/WebObjects/MZStoreServices.woa/ws/genres?id=26), + * unchanged since Apple's 2019 category overhaul. + */ +internal val APPLE_PODCAST_CATEGORIES: List = listOf( + ChartCategory( + "Comedy", 1303, + listOf( + ChartCategory("Comedy Interviews", 1496), + ChartCategory("Improv", 1495), + ChartCategory("Stand-Up", 1497), + ), + ), + ChartCategory( + "News", 1489, + listOf( + ChartCategory("Business News", 1490), + ChartCategory("Daily News", 1526), + ChartCategory("Entertainment News", 1531), + ChartCategory("News Commentary", 1530), + ChartCategory("Politics", 1527), + ChartCategory("Sports News", 1529), + ChartCategory("Tech News", 1528), + ), + ), + ChartCategory("True Crime", 1488), + ChartCategory("Technology", 1318), + ChartCategory( + "Society & Culture", 1324, + listOf( + ChartCategory("Documentary", 1543), + ChartCategory("Personal Journals", 1302), + ChartCategory("Philosophy", 1443), + ChartCategory("Places & Travel", 1320), + ChartCategory("Relationships", 1544), + ), + ), + ChartCategory( + "Sport", 1545, + listOf( + ChartCategory("Baseball", 1549), + ChartCategory("Basketball", 1548), + ChartCategory("Cricket", 1554), + ChartCategory("Fantasy Sports", 1560), + ChartCategory("Football", 1547), + ChartCategory("Golf", 1553), + ChartCategory("Hockey", 1550), + ChartCategory("Rugby", 1552), + ChartCategory("Running", 1551), + ChartCategory("Soccer", 1546), + ChartCategory("Swimming", 1558), + ChartCategory("Tennis", 1556), + ChartCategory("Volleyball", 1557), + ChartCategory("Wilderness", 1559), + ChartCategory("Wrestling", 1555), + ), + ), + ChartCategory( + "Business", 1321, + listOf( + ChartCategory("Careers", 1410), + ChartCategory("Entrepreneurship", 1493), + ChartCategory("Investing", 1412), + ChartCategory("Management", 1491), + ChartCategory("Marketing", 1492), + ChartCategory("Non-Profit", 1494), + ), + ), + ChartCategory("History", 1487), + ChartCategory( + "Science", 1533, + listOf( + ChartCategory("Astronomy", 1538), + ChartCategory("Chemistry", 1539), + ChartCategory("Earth Sciences", 1540), + ChartCategory("Life Sciences", 1541), + ChartCategory("Mathematics", 1536), + ChartCategory("Natural Sciences", 1534), + ChartCategory("Nature", 1537), + ChartCategory("Physics", 1542), + ChartCategory("Social Sciences", 1535), + ), + ), + ChartCategory( + "Health & Fitness", 1512, + listOf( + ChartCategory("Alternative Health", 1513), + ChartCategory("Fitness", 1514), + ChartCategory("Medicine", 1518), + ChartCategory("Mental Health", 1517), + ChartCategory("Nutrition", 1515), + ChartCategory("Sexuality", 1516), + ), + ), + ChartCategory( + "Music", 1310, + listOf( + ChartCategory("Music Commentary", 1523), + ChartCategory("Music History", 1524), + ChartCategory("Music Interviews", 1525), + ), + ), + ChartCategory( + "TV & Film", 1309, + listOf( + ChartCategory("After Shows", 1562), + ChartCategory("Film History", 1564), + ChartCategory("Film Interviews", 1565), + ChartCategory("Film Reviews", 1563), + ChartCategory("TV Reviews", 1561), + ), + ), + ChartCategory( + "Education", 1304, + listOf( + ChartCategory("Courses", 1501), + ChartCategory("How To", 1499), + ChartCategory("Language Learning", 1498), + ChartCategory("Self-Improvement", 1500), + ), + ), + ChartCategory( + "Arts", 1301, + listOf( + ChartCategory("Books", 1482), + ChartCategory("Design", 1402), + ChartCategory("Fashion & Beauty", 1459), + ChartCategory("Food", 1306), + ChartCategory("Performing Arts", 1405), + ChartCategory("Visual Arts", 1406), + ), + ), + ChartCategory( + "Fiction", 1483, + listOf( + ChartCategory("Comedy Fiction", 1486), + ChartCategory("Drama", 1484), + ChartCategory("Science Fiction", 1485), + ), + ), + ChartCategory( + "Kids & Family", 1305, + listOf( + ChartCategory("Education for Kids", 1519), + ChartCategory("Parenting", 1521), + ChartCategory("Pets & Animals", 1522), + ChartCategory("Stories for Kids", 1520), + ), + ), + ChartCategory( + "Leisure", 1502, + listOf( + ChartCategory("Animation & Manga", 1510), + ChartCategory("Automotive", 1503), + ChartCategory("Aviation", 1504), + ChartCategory("Crafts", 1506), + ChartCategory("Games", 1507), + ChartCategory("Hobbies", 1505), + ChartCategory("Home & Garden", 1508), + ChartCategory("Video Games", 1509), + ), + ), + ChartCategory( + "Religion & Spirituality", 1314, + listOf( + ChartCategory("Buddhism", 1438), + ChartCategory("Christianity", 1439), + ChartCategory("Hinduism", 1463), + ChartCategory("Islam", 1440), + ChartCategory("Judaism", 1441), + ChartCategory("Religion", 1532), + ChartCategory("Spirituality", 1444), + ), + ), + ChartCategory("Government", 1511), +) diff --git a/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverScreen.kt b/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverScreen.kt index 85f0b3e..472eb46 100644 --- a/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverScreen.kt +++ b/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverScreen.kt @@ -42,6 +42,7 @@ import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextButton +import androidx.compose.material3.VerticalDivider import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -65,11 +66,15 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import androidx.compose.material.icons.filled.Podcasts import androidx.compose.ui.graphics.vector.rememberVectorPainter +import com.podbelly.core.common.DateUtils +import com.podbelly.core.network.model.EpisodeSearchResult +import com.podbelly.core.network.model.SearchField @Composable fun DiscoverScreen( viewModel: DiscoverViewModel = hiltViewModel(), onPodcastClick: (podcastId: Long) -> Unit = {}, + onEpisodeClick: (episodeId: Long) -> Unit = {}, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() val snackbarHostState = remember { SnackbarHostState() } @@ -81,6 +86,12 @@ fun DiscoverScreen( } } + LaunchedEffect(Unit) { + viewModel.navigateToEpisode.collect { episodeId -> + onEpisodeClick(episodeId) + } + } + LaunchedEffect(uiState.message) { uiState.message?.let { message -> snackbarHostState.showSnackbar( @@ -117,66 +128,143 @@ fun DiscoverScreen( HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp)) - when { - uiState.isSearching -> { - Box( - modifier = Modifier - .fillMaxWidth() - .weight(1f), - contentAlignment = Alignment.Center, - ) { - CircularProgressIndicator() - } - } + if (uiState.searchQuery.isBlank()) { + ChartsSection( + categories = uiState.chartCategories, + selectedGenreId = uiState.selectedChartGenreId, + onCategorySelected = viewModel::selectChartCategory, + results = uiState.chartResults, + isLoading = uiState.isLoadingChart, + error = uiState.chartError, + onRetry = viewModel::retryChart, + subscribingFeedUrls = uiState.subscribingFeedUrls, + onSubscribe = viewModel::subscribeToPodcast, + onPodcastClick = viewModel::onPodcastClick, + regions = uiState.chartRegions, + selectedCountry = uiState.selectedChartCountry, + onRegionSelected = viewModel::selectChartRegion, + selectedSubgenreId = uiState.selectedChartSubgenreId, + onSubcategorySelected = viewModel::selectChartSubcategory, + episodeResults = uiState.chartEpisodeResults, + openingEpisodes = uiState.openingEpisodes, + onEpisodeClick = viewModel::onEpisodeClick, + modifier = Modifier.weight(1f), + ) + } else { + SearchFilters( + scope = uiState.searchScope, + field = uiState.searchField, + onScopeSelected = viewModel::selectSearchScope, + onFieldSelected = viewModel::selectSearchField, + ) - uiState.searchResults.isEmpty() && uiState.searchQuery.isBlank() -> { - ChartsSection( - categories = uiState.chartCategories, - selectedGenreId = uiState.selectedChartGenreId, - onCategorySelected = viewModel::selectChartCategory, - results = uiState.chartResults, - isLoading = uiState.isLoadingChart, - error = uiState.chartError, - onRetry = viewModel::retryChart, - subscribingFeedUrls = uiState.subscribingFeedUrls, - onSubscribe = viewModel::subscribeToPodcast, - onPodcastClick = viewModel::onPodcastClick, - regions = uiState.chartRegions, - selectedCountry = uiState.selectedChartCountry, - onRegionSelected = viewModel::selectChartRegion, - modifier = Modifier.weight(1f), - ) + val noResults = when (uiState.searchScope) { + SearchScope.SHOWS -> uiState.searchResults.isEmpty() + SearchScope.EPISODES -> uiState.episodeResults.isEmpty() } + when { + uiState.isSearching -> { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator() + } + } - uiState.searchResults.isEmpty() && uiState.searchQuery.isNotBlank() -> { - Box( - modifier = Modifier - .fillMaxWidth() - .weight(1f), - contentAlignment = Alignment.Center, - ) { - Text( - text = "No results found", - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, + noResults -> { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + contentAlignment = Alignment.Center, + ) { + Text( + text = "No results found", + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + uiState.searchScope == SearchScope.EPISODES -> { + EpisodeResultsList( + results = uiState.episodeResults, + openingEpisodes = uiState.openingEpisodes, + onEpisodeClick = viewModel::onEpisodeClick, + modifier = Modifier.weight(1f), ) } - } - else -> { - SearchResultsList( - results = uiState.searchResults, - subscribingFeedUrls = uiState.subscribingFeedUrls, - onSubscribe = viewModel::subscribeToPodcast, - onPodcastClick = viewModel::onPodcastClick, - modifier = Modifier.weight(1f), - ) + else -> { + SearchResultsList( + results = uiState.searchResults, + subscribingFeedUrls = uiState.subscribingFeedUrls, + onSubscribe = viewModel::subscribeToPodcast, + onPodcastClick = viewModel::onPodcastClick, + modifier = Modifier.weight(1f), + ) + } } } } } } +/** + * Chips under the search box: search shows or episodes, and for shows, which field + * to match (anywhere, the title only, or the host / creator only). + */ +@Composable +internal fun SearchFilters( + scope: SearchScope, + field: SearchField, + onScopeSelected: (SearchScope) -> Unit, + onFieldSelected: (SearchField) -> Unit, +) { + LazyRow( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + item { + FilterChip( + selected = scope == SearchScope.SHOWS, + onClick = { onScopeSelected(SearchScope.SHOWS) }, + label = { Text("Shows") }, + ) + } + item { + FilterChip( + selected = scope == SearchScope.EPISODES, + onClick = { onScopeSelected(SearchScope.EPISODES) }, + label = { Text("Episodes") }, + ) + } + if (scope == SearchScope.SHOWS) { + item { + VerticalDivider(modifier = Modifier.height(24.dp)) + } + items(SEARCH_FIELDS) { (option, label) -> + FilterChip( + selected = field == option, + onClick = { onFieldSelected(option) }, + label = { Text(label) }, + ) + } + } + } +} + +private val SEARCH_FIELDS = listOf( + SearchField.ANYTHING to "Anywhere", + SearchField.TITLE to "In title", + SearchField.AUTHOR to "By host", +) + @Composable internal fun SearchSection( query: String, @@ -307,9 +395,15 @@ internal fun ChartsSection( regions: List = emptyList(), selectedCountry: String = "", onRegionSelected: (String) -> Unit = {}, + selectedSubgenreId: Int? = null, + onSubcategorySelected: (Int?) -> Unit = {}, + episodeResults: List = emptyList(), + openingEpisodes: Set = emptySet(), + onEpisodeClick: (EpisodeSearchResult) -> Unit = {}, modifier: Modifier = Modifier, ) { var showRegionDialog by rememberSaveable { mutableStateOf(false) } + val subcategories = categories.firstOrNull { it.genreId == selectedGenreId }?.subcategories.orEmpty() if (showRegionDialog) { ChartRegionDialog( @@ -361,6 +455,34 @@ internal fun ChartsSection( } } + // Second row: narrow the chosen category to one of Apple's sub-categories + // (e.g. Sport -> Rugby), or "All" for the whole category. + if (subcategories.isNotEmpty()) { + LazyRow( + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + item(key = "all") { + FilterChip( + selected = selectedSubgenreId == null, + onClick = { onSubcategorySelected(null) }, + label = { Text("All") }, + ) + } + items( + items = subcategories, + key = { it.genreId }, + ) { subcategory -> + FilterChip( + selected = subcategory.genreId == selectedSubgenreId, + onClick = { onSubcategorySelected(subcategory.genreId) }, + label = { Text(subcategory.label) }, + ) + } + } + } + when { isLoading -> { Box( @@ -394,6 +516,15 @@ internal fun ChartsSection( } } + selectedGenreId == DiscoverViewModel.TRENDING_EPISODES_ID -> { + EpisodeResultsList( + results = episodeResults, + openingEpisodes = openingEpisodes, + onEpisodeClick = onEpisodeClick, + modifier = Modifier.weight(1f), + ) + } + else -> { SearchResultsList( results = results, @@ -564,6 +695,102 @@ internal fun SearchResultItem( } } +@Composable +internal fun EpisodeResultsList( + results: List, + openingEpisodes: Set, + onEpisodeClick: (EpisodeSearchResult) -> Unit, + modifier: Modifier = Modifier, +) { + LazyColumn( + modifier = modifier.fillMaxWidth(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + // Episode results have no reliably unique id (trending entries lack a GUID), + // so they're keyed by position. + items(items = results) { item -> + EpisodeResultItem( + item = item, + isOpening = item in openingEpisodes, + onClick = { onEpisodeClick(item) }, + ) + } + } +} + +/** + * One episode from episode search or the trending chart. Tapping opens the episode's + * page, whose single button downloads and then plays it — no play button here. + */ +@Composable +internal fun EpisodeResultItem( + item: EpisodeSearchResult, + isOpening: Boolean, + onClick: () -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable(enabled = !isOpening, onClick = onClick) + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + AsyncImage( + model = item.artworkUrl.ifBlank { null }, + contentDescription = "${item.podcastTitle} artwork", + placeholder = rememberVectorPainter(Icons.Default.Podcasts), + error = rememberVectorPainter(Icons.Default.Podcasts), + fallback = rememberVectorPainter(Icons.Default.Podcasts), + modifier = Modifier + .size(64.dp) + .clip(RoundedCornerShape(12.dp)), + contentScale = ContentScale.Crop, + ) + + Spacer(modifier = Modifier.width(12.dp)) + + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.title, + style = MaterialTheme.typography.bodyLarge, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (item.podcastTitle.isNotBlank()) { + Text( + text = item.podcastTitle, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + val details = listOfNotNull( + item.publishedAt.takeIf { it > 0L }?.let { DateUtils.relativeDate(it) }, + item.durationSeconds.takeIf { it > 0 }?.let { DateUtils.formatDuration(it) }, + ) + if (details.isNotEmpty()) { + Text( + text = details.joinToString(" · "), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + ) + } + } + + if (isOpening) { + Spacer(modifier = Modifier.width(8.dp)) + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + strokeWidth = 2.dp, + ) + } + } +} + @Composable internal fun DiscoverEmptyState(modifier: Modifier = Modifier) { Box( diff --git a/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverViewModel.kt b/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverViewModel.kt index 8f7e344..ea14e1d 100644 --- a/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverViewModel.kt +++ b/feature/discover/src/main/java/com/podbelly/feature/discover/DiscoverViewModel.kt @@ -7,13 +7,20 @@ import coil3.ImageLoader import coil3.request.CachePolicy import coil3.request.ImageRequest import com.podbelly.core.database.dao.EpisodeDao +import com.podbelly.core.database.dao.FeedItemKey import com.podbelly.core.database.dao.PodcastDao import com.podbelly.core.database.entity.EpisodeEntity import com.podbelly.core.database.entity.PodcastEntity import com.podbelly.core.common.PreferencesManager +import com.podbelly.core.database.dao.normalizeTitleForMatch import com.podbelly.core.network.api.PodcastSearchRepository +import com.podbelly.core.network.model.EpisodeSearchResult +import com.podbelly.core.network.model.RssEpisode +import com.podbelly.core.network.model.RssFeed +import com.podbelly.core.network.model.SearchField import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow @@ -38,15 +45,31 @@ data class DiscoverPodcastItem( val isSubscribed: Boolean, ) -/** A browsable chart category, mapping a chip label to an iTunes genre id. */ -data class ChartCategory(val label: String, val genreId: Int) +/** + * A browsable chart category, mapping a chip label to an iTunes genre id, with the + * category's own sub-categories (each chartable on its own). + */ +data class ChartCategory( + val label: String, + val genreId: Int, + val subcategories: List = emptyList(), +) /** A selectable chart storefront region. */ data class ChartRegion(val code: String, val label: String) +/** Whether a search looks for whole shows or individual episodes. */ +enum class SearchScope { SHOWS, EPISODES } + data class DiscoverUiState( val searchQuery: String = "", val searchResults: List = emptyList(), + val searchScope: SearchScope = SearchScope.SHOWS, + /** Which field a show search matches; episode search always matches everything. */ + val searchField: SearchField = SearchField.ANYTHING, + val episodeResults: List = emptyList(), + /** Episodes being resolved to a stored row after a tap, so their rows can show progress. */ + val openingEpisodes: Set = emptySet(), val isSearching: Boolean = false, val feedUrlInput: String = "", /** Feed URLs with a subscription currently in flight, so each row can spin/disable independently. */ @@ -54,7 +77,11 @@ data class DiscoverUiState( val message: String? = null, val chartCategories: List = DiscoverViewModel.CHART_CATEGORIES, val selectedChartGenreId: Int = DiscoverViewModel.TOP_CHART_GENRE_ID, + /** A sub-category of the selected category, or null for the whole category. */ + val selectedChartSubgenreId: Int? = null, val chartResults: List = emptyList(), + /** The trending-episodes chart, shown instead of [chartResults] when it's selected. */ + val chartEpisodeResults: List = emptyList(), val isLoadingChart: Boolean = false, val chartError: String? = null, val chartRegions: List = DiscoverViewModel.CHART_REGIONS, @@ -78,6 +105,9 @@ class DiscoverViewModel @Inject constructor( private val _navigateToPodcast = Channel(Channel.BUFFERED) val navigateToPodcast = _navigateToPodcast.receiveAsFlow() + private val _navigateToEpisode = Channel(Channel.BUFFERED) + val navigateToEpisode = _navigateToEpisode.receiveAsFlow() + private val searchQueryFlow = MutableStateFlow("") /** Explicit (e.g. IME "Search" action) queries that should run without the debounce. */ @@ -85,6 +115,7 @@ class DiscoverViewModel @Inject constructor( /** Charts already fetched this session, so switching chips back is instant. */ private val chartCache = mutableMapOf>() + private var trendingEpisodesCache: List? = null // Charts are region-specific. The stored preference wins; blank means // "follow the device locale", falling back to the US chart when the locale @@ -123,21 +154,44 @@ class DiscoverViewModel @Inject constructor( chartCountry = countryCode // Cached charts belong to the previous region. chartCache.clear() - _uiState.update { it.copy(selectedChartCountry = countryCode, chartResults = emptyList()) } + trendingEpisodesCache = null + _uiState.update { + it.copy( + selectedChartCountry = countryCode, + chartResults = emptyList(), + chartEpisodeResults = emptyList(), + ) + } viewModelScope.launch { preferencesManager.setChartCountry(countryCode) } - loadChart(_uiState.value.selectedChartGenreId) + loadChart(activeChartGenreId()) + // Search follows the chart region's storefront, so re-run it there too. + rerunSearch() } fun selectChartCategory(genreId: Int) { - _uiState.update { it.copy(selectedChartGenreId = genreId) } + _uiState.update { it.copy(selectedChartGenreId = genreId, selectedChartSubgenreId = null) } loadChart(genreId) } + /** Narrows the selected category's chart to one sub-category; null shows the whole category. */ + fun selectChartSubcategory(subgenreId: Int?) { + _uiState.update { it.copy(selectedChartSubgenreId = subgenreId) } + loadChart(activeChartGenreId()) + } + fun retryChart() { - loadChart(_uiState.value.selectedChartGenreId) + loadChart(activeChartGenreId()) } + /** The genre whose chart is on screen: the sub-category when one is picked. */ + private fun activeChartGenreId(): Int = + _uiState.value.let { it.selectedChartSubgenreId ?: it.selectedChartGenreId } + private fun loadChart(genreId: Int) { + if (genreId == TRENDING_EPISODES_ID) { + loadTrendingEpisodes() + return + } chartCache[genreId]?.let { cached -> _uiState.update { it.copy(chartResults = cached, isLoadingChart = false, chartError = null) } return @@ -147,7 +201,7 @@ class DiscoverViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isLoadingChart = true, chartError = null) } try { - val results = searchRepository.topPodcasts(requestCountry, genreId) + val results = searchRepository.topPodcasts(requestCountry, genreId, CHART_SIZE) val items = results.map { result -> val existing = podcastDao.getByFeedUrl(result.feedUrl) DiscoverPodcastItem( @@ -163,11 +217,11 @@ class DiscoverViewModel @Inject constructor( // must not overwrite or pollute the current chart. if (chartCountry != requestCountry) return@launch chartCache[genreId] = items - if (_uiState.value.selectedChartGenreId == genreId) { + if (activeChartGenreId() == genreId) { _uiState.update { it.copy(chartResults = items, isLoadingChart = false) } } } catch (e: Exception) { - if (chartCountry == requestCountry && _uiState.value.selectedChartGenreId == genreId) { + if (chartCountry == requestCountry && activeChartGenreId() == genreId) { _uiState.update { it.copy( isLoadingChart = false, @@ -179,15 +233,67 @@ class DiscoverViewModel @Inject constructor( } } + private fun loadTrendingEpisodes() { + trendingEpisodesCache?.let { cached -> + _uiState.update { it.copy(chartEpisodeResults = cached, isLoadingChart = false, chartError = null) } + return + } + + val requestCountry = chartCountry + viewModelScope.launch { + _uiState.update { it.copy(isLoadingChart = true, chartError = null) } + try { + val results = searchRepository.trendingEpisodes(requestCountry, TRENDING_EPISODES_SIZE) + // Same staleness rule as loadChart: drop it if the region or chip changed. + if (chartCountry != requestCountry) return@launch + trendingEpisodesCache = results + if (activeChartGenreId() == TRENDING_EPISODES_ID) { + _uiState.update { it.copy(chartEpisodeResults = results, isLoadingChart = false) } + } + } catch (e: Exception) { + if (chartCountry == requestCountry && activeChartGenreId() == TRENDING_EPISODES_ID) { + _uiState.update { + it.copy( + isLoadingChart = false, + chartError = "Couldn't load trending episodes: ${e.message}", + ) + } + } + } + } + } + fun updateSearchQuery(query: String) { _uiState.update { it.copy(searchQuery = query) } searchQueryFlow.value = query if (query.isBlank()) { - _uiState.update { it.copy(searchResults = emptyList(), isSearching = false) } + _uiState.update { + it.copy(searchResults = emptyList(), episodeResults = emptyList(), isSearching = false) + } } } + /** Switches between searching shows and episodes, re-running the current query. */ + fun selectSearchScope(scope: SearchScope) { + if (scope == _uiState.value.searchScope) return + _uiState.update { it.copy(searchScope = scope) } + rerunSearch() + } + + /** Narrows a show search to titles or hosts, re-running the current query. */ + fun selectSearchField(field: SearchField) { + if (field == _uiState.value.searchField) return + _uiState.update { it.copy(searchField = field) } + rerunSearch() + } + + /** Re-runs the current query now (skipping the debounce) after a filter changed. */ + private fun rerunSearch() { + val query = _uiState.value.searchQuery + if (query.isNotBlank()) immediateSearch.trySend(query) + } + fun updateFeedUrl(url: String) { _uiState.update { it.copy(feedUrlInput = url) } } @@ -203,8 +309,18 @@ class DiscoverViewModel @Inject constructor( private suspend fun performSearch(query: String) { _uiState.update { it.copy(isSearching = true) } + val scope = _uiState.value.searchScope + val field = _uiState.value.searchField try { - val results = searchRepository.search(query) + if (scope == SearchScope.EPISODES) { + val episodes = searchRepository.searchEpisodes(query, chartCountry) + if (_uiState.value.searchQuery != query) return + _uiState.update { it.copy(episodeResults = episodes, isSearching = false) } + return + } + // Searches the chart region's storefront: some shows aren't listed in the + // default (US) one at all. + val results = searchRepository.search(query, field, chartCountry) // A blank query is filtered out of the search pipeline, so clearing the box // doesn't cancel this in-flight call via collectLatest. Bail if the query box // no longer matches what we searched, so stale results can't repopulate a @@ -221,6 +337,9 @@ class DiscoverViewModel @Inject constructor( ) } _uiState.update { it.copy(searchResults = items, isSearching = false) } + } catch (e: CancellationException) { + // A newer query or filter superseded this search (collectLatest); not a failure. + throw e } catch (e: Exception) { _uiState.update { it.copy( @@ -249,6 +368,10 @@ class DiscoverViewModel @Inject constructor( val podcastId = if (existing != null) { podcastDao.update(existing.copy(subscribed = true, subscribedAt = now)) + // insertAll below skips stored GUIDs; re-key ones the host changed. + episodeDao.repairChangedGuids(existing.id, feed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }) existing.id } else { podcastDao.insert( @@ -334,54 +457,120 @@ class DiscoverViewModel @Inject constructor( } val feed = searchRepository.fetchFeed(feedUrl) - val now = System.currentTimeMillis() + val podcastId = storePreview(feedUrl, feed) ?: return@launch + _navigateToPodcast.send(podcastId) + } catch (e: Exception) { + _uiState.update { it.copy(message = "Failed to load podcast: ${e.message}") } + } + } + } - // Insert-if-absent (not REPLACE) so a concurrent second tap can't replace - // the row with a new id and CASCADE-delete the episodes we just inserted. - val newId = podcastDao.insertIfAbsent( - PodcastEntity( - feedUrl = feedUrl, - title = feed.title, - author = feed.author, - description = feed.description, - artworkUrl = feed.artworkUrl, - link = feed.link, - language = "", - lastBuildDate = now, - subscribed = false, - subscribedAt = 0L, - lastRefreshedAt = now, - episodeCount = feed.episodes.size, - ) - ) - val podcastId = if (newId != -1L) newId else { - podcastDao.getByFeedUrl(feedUrl)?.id ?: return@launch + /** + * Opens an episode from episode search or the trending chart. Its show is stored + * (unsubscribed) if it isn't already, like a podcast preview, then the episode is + * found among the show's episodes and its page opened; that page offers the usual + * download-then-play button. Falls back to the show's page if the feed no longer + * lists the episode. + */ + fun onEpisodeClick(item: EpisodeSearchResult) { + if (item in _uiState.value.openingEpisodes) return + _uiState.update { it.copy(openingEpisodes = it.openingEpisodes + item) } + viewModelScope.launch { + try { + val existing = podcastDao.getByFeedUrl(item.feedUrl) + existing?.let { podcast -> + findStoredEpisode(podcast.id, item)?.let { episodeId -> + _navigateToEpisode.send(episodeId) + return@launch + } } - val episodes = feed.episodes.map { episode -> - EpisodeEntity( - podcastId = podcastId, - guid = episode.guid, - title = episode.title, - description = episode.description, - audioUrl = episode.audioUrl, - publicationDate = episode.publishedAt, - durationSeconds = (episode.duration / 1000).toInt(), - artworkUrl = episode.artworkUrl ?: "", - transcriptUrl = episode.transcriptUrl ?: "", - transcriptType = episode.transcriptType ?: "", - ) + // New show, or a stored copy older than this episode: fetch the feed. + val feed = searchRepository.fetchFeed(item.feedUrl) + val podcastId = if (existing == null) { + storePreview(item.feedUrl, feed) ?: return@launch + } else { + episodeDao.repairChangedGuids(existing.id, feed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }) + episodeDao.insertAll(feed.episodes.map { it.toEntity(existing.id) }) + existing.id } - episodeDao.insertAll(episodes) - prefetchArtwork(feed.artworkUrl) - _navigateToPodcast.send(podcastId) + val episodeId = findStoredEpisode(podcastId, item) + if (episodeId != null) { + _navigateToEpisode.send(episodeId) + } else { + _navigateToPodcast.send(podcastId) + } } catch (e: Exception) { - _uiState.update { it.copy(message = "Failed to load podcast: ${e.message}") } + _uiState.update { it.copy(message = "Failed to load episode: ${e.message}") } + } finally { + _uiState.update { it.copy(openingEpisodes = it.openingEpisodes - item) } } } } + /** + * The stored episode [item] refers to: by GUID when Apple gave one, else by audio + * URL or title (trending entries carry neither GUID nor audio URL). + */ + private suspend fun findStoredEpisode(podcastId: Long, item: EpisodeSearchResult): Long? { + item.episodeGuid?.let { guid -> + episodeDao.getByPodcastAndGuid(podcastId, guid)?.let { return it.id } + } + val title = normalizeTitleForMatch(item.title) + val rows = episodeDao.getMatchRowsForPodcast(podcastId) + return ( + rows.firstOrNull { item.audioUrl != null && it.audioUrl == item.audioUrl } + ?: rows.firstOrNull { title.isNotEmpty() && normalizeTitleForMatch(it.title) == title } + )?.id + } + + /** + * Stores a show being previewed (not subscribed) with its episodes, returning its + * id. Insert-if-absent (not REPLACE) so a concurrent second tap can't replace the + * row with a new id and CASCADE-delete the episodes just inserted. + */ + private suspend fun storePreview(feedUrl: String, feed: RssFeed): Long? { + val now = System.currentTimeMillis() + val newId = podcastDao.insertIfAbsent( + PodcastEntity( + feedUrl = feedUrl, + title = feed.title, + author = feed.author, + description = feed.description, + artworkUrl = feed.artworkUrl, + link = feed.link, + language = "", + lastBuildDate = now, + subscribed = false, + subscribedAt = 0L, + lastRefreshedAt = now, + episodeCount = feed.episodes.size, + ) + ) + val podcastId = if (newId != -1L) newId else { + podcastDao.getByFeedUrl(feedUrl)?.id ?: return null + } + episodeDao.insertAll(feed.episodes.map { it.toEntity(podcastId) }) + prefetchArtwork(feed.artworkUrl) + return podcastId + } + + private fun RssEpisode.toEntity(podcastId: Long) = EpisodeEntity( + podcastId = podcastId, + guid = guid, + title = title, + description = description, + audioUrl = audioUrl, + publicationDate = publishedAt, + durationSeconds = (duration / 1000).toInt(), + artworkUrl = artworkUrl ?: "", + transcriptUrl = transcriptUrl ?: "", + transcriptType = transcriptType ?: "", + ) + private fun prefetchArtwork(url: String) { if (url.isBlank()) return val request = ImageRequest.Builder(context) @@ -399,6 +588,14 @@ class DiscoverViewModel @Inject constructor( /** iTunes' root "Podcasts" genre — the overall chart. */ const val TOP_CHART_GENRE_ID = 26 + /** Pseudo genre id for the "Trending episodes" chip (not an iTunes genre). */ + const val TRENDING_EPISODES_ID = -1 + + /** Shows per chart; Apple's chart feed serves at most 200. */ + const val CHART_SIZE = 200 + + const val TRENDING_EPISODES_SIZE = 50 + val CHART_REGIONS = listOf( ChartRegion("ie", "Ireland"), ChartRegion("gb", "United Kingdom"), @@ -425,19 +622,7 @@ class DiscoverViewModel @Inject constructor( val CHART_CATEGORIES = listOf( ChartCategory("Top", TOP_CHART_GENRE_ID), - ChartCategory("Comedy", 1303), - ChartCategory("News", 1489), - ChartCategory("True Crime", 1488), - ChartCategory("Technology", 1318), - ChartCategory("Society & Culture", 1324), - ChartCategory("Sport", 1545), - ChartCategory("Business", 1321), - ChartCategory("History", 1487), - ChartCategory("Science", 1533), - ChartCategory("Health & Fitness", 1512), - ChartCategory("Music", 1310), - ChartCategory("TV & Film", 1309), - ChartCategory("Education", 1304), - ) + ChartCategory("Trending episodes", TRENDING_EPISODES_ID), + ) + APPLE_PODCAST_CATEGORIES } } diff --git a/feature/discover/src/test/java/com/podbelly/feature/discover/DiscoverViewModelTest.kt b/feature/discover/src/test/java/com/podbelly/feature/discover/DiscoverViewModelTest.kt index 1197f6c..aa5d465 100644 --- a/feature/discover/src/test/java/com/podbelly/feature/discover/DiscoverViewModelTest.kt +++ b/feature/discover/src/test/java/com/podbelly/feature/discover/DiscoverViewModelTest.kt @@ -4,17 +4,22 @@ import android.content.Context import app.cash.turbine.test import coil3.ImageLoader import com.podbelly.core.database.dao.EpisodeDao +import com.podbelly.core.database.dao.EpisodeMatchRow import com.podbelly.core.database.dao.PodcastDao +import com.podbelly.core.database.entity.EpisodeEntity import com.podbelly.core.database.entity.PodcastEntity import com.podbelly.core.common.PreferencesManager import com.podbelly.core.network.api.PodcastSearchRepository +import com.podbelly.core.network.model.EpisodeSearchResult import com.podbelly.core.network.model.RssEpisode import com.podbelly.core.network.model.RssFeed +import com.podbelly.core.network.model.SearchField import com.podbelly.core.network.model.SearchResult import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.flow.first import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow @@ -99,7 +104,7 @@ class DiscoverViewModelTest { artworkUrl = "https://art2.com/img.jpg", ), ) - coEvery { searchRepository.search("test query") } returns searchResults + coEvery { searchRepository.search("test query", any(), any()) } returns searchResults val viewModel = createViewModel() @@ -201,7 +206,7 @@ class DiscoverViewModelTest { @Test fun `error during search sets error message in state`() = runTest { - coEvery { searchRepository.search("fail query") } throws RuntimeException("Network error") + coEvery { searchRepository.search("fail query", any(), any()) } throws RuntimeException("Network error") val viewModel = createViewModel() @@ -223,7 +228,7 @@ class DiscoverViewModelTest { @Test fun `clearMessage sets message to null`() = runTest { - coEvery { searchRepository.search("fail") } throws RuntimeException("err") + coEvery { searchRepository.search("fail", any(), any()) } throws RuntimeException("err") val viewModel = createViewModel() @@ -296,7 +301,7 @@ class DiscoverViewModelTest { artworkUrl = "https://art.com", ), ) - coEvery { searchRepository.search("test") } returns searchResults + coEvery { searchRepository.search("test", any(), any()) } returns searchResults val viewModel = createViewModel() viewModel.search("test") @@ -494,4 +499,179 @@ class DiscoverViewModelTest { coVerify(exactly = 0) { preferencesManager.setChartCountry(any()) } } + + // -- Episode search, search fields, sub-categories, trending, opening episodes -- + + private fun episodeResult( + title: String = "#2525 - Nick Bostrom", + feedUrl: String = "https://feed.jre", + guid: String? = "guid-2525", + ) = EpisodeSearchResult( + title = title, + podcastTitle = "The Joe Rogan Experience", + feedUrl = feedUrl, + artworkUrl = "", + episodeGuid = guid, + ) + + private fun storedPodcast(id: Long, feedUrl: String) = PodcastEntity( + id = id, + feedUrl = feedUrl, + title = "The Joe Rogan Experience", + author = "Joe Rogan", + description = "", + artworkUrl = "", + link = "", + language = "", + lastBuildDate = 0L, + subscribed = false, + subscribedAt = 0L, + ) + + private fun matchRow(id: Long, title: String) = EpisodeMatchRow( + id = id, guid = "g$id", title = title, audioUrl = "", publicationDate = 0L, + durationSeconds = 0, played = false, playbackPosition = 0L, lastPlayedAt = 0L, + downloadPath = "", downloadedAt = 0L, fileSize = 0L, autoDownloaded = false, + ) + + @Test + fun `episode search fills episode results instead of shows`() = runTest { + coEvery { searchRepository.searchEpisodes("nick bostrom", any()) } returns listOf(episodeResult()) + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.selectSearchScope(SearchScope.EPISODES) + viewModel.search("nick bostrom") + advanceUntilIdle() + + val state = viewModel.uiState.value + assertEquals(listOf(episodeResult()), state.episodeResults) + assertTrue(state.searchResults.isEmpty()) + coVerify(exactly = 0) { searchRepository.search(any(), any(), any()) } + } + + @Test + fun `changing the search field re-runs the query against that field`() = runTest { + coEvery { searchRepository.search(any(), any(), any()) } returns emptyList() + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.search("rogan") + advanceUntilIdle() + viewModel.selectSearchField(SearchField.AUTHOR) + advanceUntilIdle() + + coVerify { searchRepository.search("rogan", SearchField.ANYTHING, any()) } + coVerify { searchRepository.search("rogan", SearchField.AUTHOR, any()) } + } + + @Test + fun `search uses the chart region's storefront`() = runTest { + every { preferencesManager.chartCountry } returns MutableStateFlow("ie") + coEvery { searchRepository.search(any(), any(), any()) } returns emptyList() + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.search("rugby") + advanceUntilIdle() + + coVerify { searchRepository.search("rugby", SearchField.ANYTHING, "ie") } + } + + @Test + fun `selecting a sub-category charts it, and All goes back to the category`() = runTest { + coEvery { searchRepository.topPodcasts(any(), any(), any()) } returns emptyList() + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.selectChartCategory(1545) // Sport + advanceUntilIdle() + viewModel.selectChartSubcategory(1552) // Rugby + advanceUntilIdle() + + assertEquals(1545, viewModel.uiState.value.selectedChartGenreId) + assertEquals(1552, viewModel.uiState.value.selectedChartSubgenreId) + coVerify { searchRepository.topPodcasts(any(), 1552, DiscoverViewModel.CHART_SIZE) } + + viewModel.selectChartSubcategory(null) + advanceUntilIdle() + assertNull(viewModel.uiState.value.selectedChartSubgenreId) + // The whole-category chart was cached from the first load. + coVerify(exactly = 1) { searchRepository.topPodcasts(any(), 1545, any()) } + } + + @Test + fun `every chart category lists Apple's sub-categories`() { + val sport = DiscoverViewModel.CHART_CATEGORIES.first { it.genreId == 1545 } + assertTrue(sport.subcategories.any { it.label == "Rugby" && it.genreId == 1552 }) + // Top, Trending episodes, and Apple's 19 categories. + assertEquals(21, DiscoverViewModel.CHART_CATEGORIES.size) + assertEquals(91, DiscoverViewModel.CHART_CATEGORIES.sumOf { it.subcategories.size }) + } + + @Test + fun `the trending chip loads trending episodes`() = runTest { + coEvery { searchRepository.topPodcasts(any(), any(), any()) } returns emptyList() + coEvery { searchRepository.trendingEpisodes(any(), any()) } returns listOf(episodeResult(guid = null)) + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.selectChartCategory(DiscoverViewModel.TRENDING_EPISODES_ID) + advanceUntilIdle() + + assertEquals(listOf(episodeResult(guid = null)), viewModel.uiState.value.chartEpisodeResults) + coVerify(exactly = 0) { searchRepository.topPodcasts(any(), DiscoverViewModel.TRENDING_EPISODES_ID, any()) } + } + + @Test + fun `opening an episode of a stored show goes straight to it by GUID`() = runTest { + coEvery { podcastDao.getByFeedUrl("https://feed.jre") } returns storedPodcast(7L, "https://feed.jre") + coEvery { episodeDao.getByPodcastAndGuid(7L, "guid-2525") } returns EpisodeEntity( + id = 70L, + podcastId = 7L, + guid = "guid-2525", + title = "#2525 - Nick Bostrom", + description = "", + audioUrl = "", + publicationDate = 0L, + durationSeconds = 0, + ) + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.onEpisodeClick(episodeResult()) + advanceUntilIdle() + + assertEquals(70L, viewModel.navigateToEpisode.first()) + coVerify(exactly = 0) { searchRepository.fetchFeed(any()) } + assertTrue(viewModel.uiState.value.openingEpisodes.isEmpty()) + } + + @Test + fun `opening a trending episode of a new show stores it and finds the episode by title`() = runTest { + coEvery { podcastDao.getByFeedUrl("https://feed.new") } returns null + coEvery { searchRepository.fetchFeed("https://feed.new") } returns RssFeed( + title = "New Show", + description = "", + author = "", + artworkUrl = "", + link = "", + episodes = emptyList(), + ) + coEvery { podcastDao.insertIfAbsent(any()) } returns 9L + coEvery { episodeDao.getMatchRowsForPodcast(9L) } returns listOf( + matchRow(90L, "Some Other Episode"), + matchRow(91L, "Trump's election temper tantrum"), + ) + + val viewModel = createViewModel() + advanceUntilIdle() + viewModel.onEpisodeClick( + episodeResult(title = "Trump\u2019s election temper tantrum", feedUrl = "https://feed.new", guid = null) + ) + advanceUntilIdle() + + assertEquals(91L, viewModel.navigateToEpisode.first()) + coVerify { podcastDao.insertIfAbsent(match { !it.subscribed }) } + } } diff --git a/feature/podcast/src/main/java/com/podbelly/feature/podcast/EpisodeDetailScreen.kt b/feature/podcast/src/main/java/com/podbelly/feature/podcast/EpisodeDetailScreen.kt index 57864cc..e1a5e5a 100644 --- a/feature/podcast/src/main/java/com/podbelly/feature/podcast/EpisodeDetailScreen.kt +++ b/feature/podcast/src/main/java/com/podbelly/feature/podcast/EpisodeDetailScreen.kt @@ -1,6 +1,5 @@ package com.podbelly.feature.podcast -import androidx.compose.animation.animateContentSize import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -367,8 +366,6 @@ fun EpisodeDetailScreen( // Description / show notes if (uiState.description.isNotBlank()) { - var isExpanded by remember { mutableStateOf(false) } - Text( text = "Show Notes", style = MaterialTheme.typography.titleMedium, @@ -379,40 +376,25 @@ fun EpisodeDetailScreen( val notesTextColor = MaterialTheme.colorScheme.onSurfaceVariant.toArgb() val notesLinkColor = MaterialTheme.colorScheme.primary.toArgb() - val notesMaxLines = if (isExpanded) Int.MAX_VALUE else 8 + // Shown in full: the page itself scrolls. No line cap, so the TextView + // never scrolls internally (LinkMovementMethod makes a capped one do so). AndroidView( factory = { ctx -> android.widget.TextView(ctx).apply { setTextColor(notesTextColor) setLinkTextColor(notesLinkColor) textSize = 14f - maxLines = notesMaxLines - ellipsize = android.text.TextUtils.TruncateAt.END movementMethod = android.text.method.LinkMovementMethod.getInstance() } }, update = { textView -> textView.text = ShowNotesHtml.toSpanned(uiState.description) - textView.maxLines = notesMaxLines textView.setTextColor(notesTextColor) textView.setLinkTextColor(notesLinkColor) }, - modifier = Modifier - .fillMaxWidth() - .animateContentSize(), + modifier = Modifier.fillMaxWidth(), ) - - if (uiState.description.length > 200) { - Text( - text = if (isExpanded) "Show less" else "Show more", - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.primary, - modifier = Modifier - .clickable { isExpanded = !isExpanded } - .padding(vertical = 8.dp), - ) - } } Spacer(modifier = Modifier.height(96.dp)) diff --git a/feature/podcast/src/main/java/com/podbelly/feature/podcast/PodcastDetailViewModel.kt b/feature/podcast/src/main/java/com/podbelly/feature/podcast/PodcastDetailViewModel.kt index 9bc545d..b084adb 100644 --- a/feature/podcast/src/main/java/com/podbelly/feature/podcast/PodcastDetailViewModel.kt +++ b/feature/podcast/src/main/java/com/podbelly/feature/podcast/PodcastDetailViewModel.kt @@ -4,9 +4,11 @@ import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.podbelly.core.database.dao.EpisodeDao +import com.podbelly.core.database.dao.FeedItemKey import com.podbelly.core.database.dao.PodcastDao import com.podbelly.core.database.entity.AUTO_DOWNLOAD_SMART import com.podbelly.core.database.entity.EpisodeEntity +import com.podbelly.core.database.entity.hasSameFeedFields import com.podbelly.core.database.entity.withRefreshedMetadata import com.podbelly.core.common.DownloadErrorEvent import com.podbelly.core.common.DownloadManager @@ -14,6 +16,7 @@ import com.podbelly.core.common.PreferencesManager import com.podbelly.core.network.api.PodcastSearchRepository import com.podbelly.core.playback.PlaybackController import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharingStarted @@ -135,12 +138,34 @@ class PodcastDetailViewModel @Inject constructor( initialValue = PodcastDetailUiState() ) - fun refreshFeed() { + private var refreshJob: Job? = null + + init { + // Shows you aren't subscribed to (opened from search or the charts) aren't in the + // background feed refresh, so their stored episodes froze at whenever the show + // was first previewed — reopening it months later still showed that old list. + // Refresh them on open, as Pocket Casts' PodcastViewModel.loadPodcast does. + // Subscribed shows are left to the background refresh: it's what auto-downloads + // and notifies for new episodes, and it would skip any we inserted here first. viewModelScope.launch { + val podcast = podcastDao.getById(podcastId).first() ?: return@launch + val age = System.currentTimeMillis() - podcast.lastRefreshedAt + // Discover fetches the feed just before navigating here for a first preview. + if (!podcast.subscribed && age > OPEN_REFRESH_AFTER_MS) refreshFeed() + } + } + + fun refreshFeed() { + if (refreshJob?.isActive == true) return + refreshJob = viewModelScope.launch { _isRefreshing.value = true try { val podcastEntity = podcastDao.getById(podcastId).first() ?: return@launch val rssFeed = searchRepository.fetchFeed(podcastEntity.feedUrl) + // Before matching by GUID: re-key episodes whose GUID the host changed. + episodeDao.repairChangedGuids(podcastId, rssFeed.episodes.map { + FeedItemKey(it.guid, it.title, it.audioUrl, it.publishedAt, (it.duration / 1000).toInt()) + }) val newEpisodes = mutableListOf() for (rssEpisode in rssFeed.episodes) { @@ -161,8 +186,21 @@ class PodcastDetailViewModel @Inject constructor( transcriptType = rssEpisode.transcriptType ?: "", ) ) - } else { + } else if (!existing.hasSameFeedFields( + title = rssEpisode.title, + description = rssEpisode.description, + audioUrl = rssEpisode.audioUrl, + publicationDate = rssEpisode.publishedAt, + durationSeconds = (rssEpisode.duration / 1000).toInt(), + artworkUrl = rssEpisode.artworkUrl ?: "", + fileSize = rssEpisode.fileSize, + transcriptUrl = rssEpisode.transcriptUrl ?: "", + transcriptType = rssEpisode.transcriptType ?: "", + ) + ) { // Refresh feed-derived fields so publisher corrections propagate. + // Unchanged rows are skipped: each write invalidates the episode + // list, and long-running feeds have thousands of episodes. episodeDao.updateFeedFields( podcastId = podcastId, guid = rssEpisode.guid, @@ -287,4 +325,8 @@ class PodcastDetailViewModel @Inject constructor( } } + private companion object { + /** An unsubscribed show fetched more recently than this isn't re-fetched on open. */ + const val OPEN_REFRESH_AFTER_MS = 15 * 60 * 1000L + } } diff --git a/feature/podcast/src/test/java/com/podbelly/feature/podcast/PodcastDetailViewModelTest.kt b/feature/podcast/src/test/java/com/podbelly/feature/podcast/PodcastDetailViewModelTest.kt index b8bca01..41af12f 100644 --- a/feature/podcast/src/test/java/com/podbelly/feature/podcast/PodcastDetailViewModelTest.kt +++ b/feature/podcast/src/test/java/com/podbelly/feature/podcast/PodcastDetailViewModelTest.kt @@ -590,6 +590,78 @@ class PodcastDetailViewModelTest { job.cancel() } + // -- refresh on open -- + + private val emptyFeed = RssFeed( + title = "Test Podcast", + description = "Desc", + author = "Author", + artworkUrl = "https://example.com/art.jpg", + link = "https://example.com", + episodes = emptyList(), + ) + + @Test + fun `opening an unsubscribed show with a stale cache fetches its feed`() = runTest { + coEvery { searchRepository.fetchFeed(any()) } returns emptyFeed + podcastFlow.value = testPodcast.copy(subscribed = false, lastRefreshedAt = 0L) + + createViewModel() + advanceUntilIdle() + + coVerify(exactly = 1) { searchRepository.fetchFeed("https://example.com/feed.xml") } + } + + @Test + fun `opening an unsubscribed show fetched moments ago does not fetch again`() = runTest { + podcastFlow.value = testPodcast.copy( + subscribed = false, + lastRefreshedAt = System.currentTimeMillis(), + ) + + createViewModel() + advanceUntilIdle() + + coVerify(exactly = 0) { searchRepository.fetchFeed(any()) } + } + + @Test + fun `opening a subscribed show leaves refreshing to the background refresh`() = runTest { + podcastFlow.value = testPodcast.copy(subscribed = true, lastRefreshedAt = 0L) + + createViewModel() + advanceUntilIdle() + + coVerify(exactly = 0) { searchRepository.fetchFeed(any()) } + } + + @Test + fun `refreshFeed skips the write for episodes the feed hasn't changed`() = runTest { + val unchanged = RssEpisode( + guid = testEpisode.guid, + title = testEpisode.title, + description = testEpisode.description, + audioUrl = testEpisode.audioUrl, + publishedAt = testEpisode.publicationDate, + duration = testEpisode.durationSeconds * 1000L, + artworkUrl = testEpisode.artworkUrl, + fileSize = testEpisode.fileSize, + ) + coEvery { searchRepository.fetchFeed(any()) } returns emptyFeed.copy(episodes = listOf(unchanged)) + coEvery { episodeDao.getByPodcastAndGuid(1L, testEpisode.guid) } returns testEpisode + podcastFlow.value = testPodcast + + val viewModel = createViewModel() + advanceUntilIdle() + + viewModel.refreshFeed() + advanceUntilIdle() + + coVerify(exactly = 0) { + episodeDao.updateFeedFields(any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()) + } + } + // -- downloadProgress tests -- @Test