Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}

Expand Down
18 changes: 16 additions & 2 deletions app/src/main/java/com/podbelly/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion app/src/main/java/com/podbelly/navigation/PodbellNavHost.kt
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,10 @@ fun PodbellNavHost(
DiscoverScreen(
onPodcastClick = { podcastId ->
navController.navigate(Screen.PodcastDetail.createRoute(podcastId))
}
},
onEpisodeClick = { episodeId ->
navController.navigate(Screen.EpisodeDetail.createRoute(episodeId))
},
)
}

Expand Down
25 changes: 24 additions & 1 deletion app/src/main/java/com/podbelly/ui/WhatsNew.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int, List<String>> = 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",
),
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/com/podbelly/worker/FeedRefreshWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -45,14 +46,25 @@ 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(
"""
UPDATE episodes
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,
Expand Down Expand Up @@ -142,8 +154,25 @@ interface EpisodeDao {
)
fun getLibraryStats(): Flow<LibraryStat>

/**
* 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<EpisodeEntity>): List<Long> {
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<EpisodeEntity>): List<Long>
suspend fun insertAllAsIs(episodes: List<EpisodeEntity>): List<Long>

@Update
suspend fun update(episode: EpisodeEntity)
Expand Down Expand Up @@ -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<FeedItemKey>): 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<Long>()
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<String>

@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<EpisodeMatchRow>

/** 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<EpisodeEntity>

Expand Down Expand Up @@ -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)"
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 &&
Expand Down
Loading
Loading