From a5c2b0b439e42728a3a3c6f94d751edbad07320b Mon Sep 17 00:00:00 2001
From: The-R0 <2861295907@qq.com>
Date: Wed, 25 Nov 2026 19:33:02 +0800
Subject: [PATCH 1/2] feat(space,db): track collection watch progress and show
continue-watching banner
---
.../composeResources/values-en/strings.xml | 5 ++
.../composeResources/values/strings.xml | 5 ++
.../kotlin/dev/bilby/AppContainer.kt | 6 ++
.../data/CollectionProgressRepository.kt | 76 +++++++++++++++++
.../kotlin/dev/bilby/data/db/BilbyDatabase.kt | 34 +++++++-
.../kotlin/dev/bilby/data/db/Entities.kt | 33 +++++++
.../kotlin/dev/bilby/ui/BilbyApp.kt | 61 ++++++++++++-
.../dev/bilby/ui/space/CollectionScreen.kt | 85 +++++++++++++++++++
.../kotlin/dev/bilby/ui/space/SpaceScreen.kt | 10 ++-
9 files changed, 312 insertions(+), 3 deletions(-)
create mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
diff --git a/shared/src/commonMain/composeResources/values-en/strings.xml b/shared/src/commonMain/composeResources/values-en/strings.xml
index a569f448..1f6b4261 100644
--- a/shared/src/commonMain/composeResources/values-en/strings.xml
+++ b/shared/src/commonMain/composeResources/values-en/strings.xml
@@ -998,6 +998,11 @@
Show %1$d more uploads
%1$d live
%1$d videos
+ Continue watching
+ Left off at %1$s
+ Last watched
+ Last watched
+ Watched
%1$d steps searched
Search watch history
diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml
index 6e3b5277..b671d5fe 100644
--- a/shared/src/commonMain/composeResources/values/strings.xml
+++ b/shared/src/commonMain/composeResources/values/strings.xml
@@ -1060,6 +1060,11 @@
展开其余 %1$d 条连发
%1$d 直播
共 %1$d 个视频
+ 继续观看
+ 上次看到 %1$s
+ 上次观看
+ 上次看到
+ 已看
已检索 %1$d 步
搜索历史记录
diff --git a/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt b/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
index d87a8470..5340f7c5 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
@@ -9,6 +9,7 @@ import dev.bilby.api.DeviceFingerprint
import dev.bilby.api.WbiSigner
import dev.bilby.data.AccountRepository
import dev.bilby.data.ArticleRepository
+import dev.bilby.data.CollectionProgressRepository
import dev.bilby.data.DanmakusRepository
import dev.bilby.data.DynamicFeedStore
import dev.bilby.data.DynamicRepository
@@ -138,6 +139,11 @@ class AppContainer(
FeedCacheRepository(database.feedCacheItemDao())
}
+ /** 合集/系列观看进度与已看记录。 */
+ val collectionProgressRepository: CollectionProgressRepository by lazy {
+ CollectionProgressRepository(database)
+ }
+
/**
* 关注动态流。**挂在容器上而不是某个 ViewModel 上**:首页和"其他动态"是同一条流的两个
* 视图,而它们分属不同的导航目的地,ViewModel 的作用域套不住两边(见 DynamicFeedStore)。
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
new file mode 100644
index 00000000..9d6d4603
--- /dev/null
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
@@ -0,0 +1,76 @@
+package dev.bilby.data
+
+import dev.bilby.data.db.BilbyDatabase
+import dev.bilby.data.db.CollectionProgressEntity
+import dev.bilby.data.db.CollectionWatchedEntity
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+/**
+ * 合集/系列追更进度仓库:记录每个合集最后观看的视频、进度与已看条目集合。
+ */
+class CollectionProgressRepository(private val db: BilbyDatabase) {
+ private val dao get() = db.collectionProgressDao()
+
+ fun observeProgress(mid: Long, collectionId: Long, isSeason: Boolean): Flow =
+ dao.observeProgress(mid, collectionId, isSeason)
+
+ fun observeWatchedBvids(mid: Long, collectionId: Long, isSeason: Boolean): Flow> =
+ dao.observeWatchedBvids(mid, collectionId, isSeason).map { it.toSet() }
+
+ suspend fun recordPlay(
+ mid: Long,
+ collectionId: Long,
+ isSeason: Boolean,
+ bvid: String,
+ title: String,
+ coverUrl: String = "",
+ positionMillis: Long = 0L,
+ durationMillis: Long = 0L,
+ ) {
+ if (mid <= 0L || collectionId <= 0L || bvid.isBlank()) return
+ val now = System.currentTimeMillis()
+ dao.upsertProgress(
+ CollectionProgressEntity(
+ mid = mid,
+ collectionId = collectionId,
+ isSeason = isSeason,
+ lastBvid = bvid,
+ lastTitle = title,
+ lastCoverUrl = coverUrl,
+ lastPositionMillis = positionMillis.coerceAtLeast(0L),
+ durationMillis = durationMillis.coerceAtLeast(0L),
+ updatedAt = now,
+ ),
+ )
+ dao.upsertWatched(
+ CollectionWatchedEntity(
+ mid = mid,
+ collectionId = collectionId,
+ isSeason = isSeason,
+ bvid = bvid,
+ watchedAt = now,
+ ),
+ )
+ }
+
+ suspend fun updatePosition(
+ mid: Long,
+ collectionId: Long,
+ isSeason: Boolean,
+ bvid: String,
+ positionMillis: Long,
+ durationMillis: Long,
+ ) {
+ if (mid <= 0L || collectionId <= 0L || bvid.isBlank()) return
+ dao.updatePositionIfMatches(
+ mid = mid,
+ collectionId = collectionId,
+ isSeason = isSeason,
+ bvid = bvid,
+ positionMillis = positionMillis.coerceAtLeast(0L),
+ durationMillis = durationMillis.coerceAtLeast(0L),
+ updatedAt = System.currentTimeMillis(),
+ )
+ }
+}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt b/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt
index f5c8e0b5..36792e60 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt
@@ -43,18 +43,50 @@ interface FeedCacheItemDao {
}
}
+@Dao
+interface CollectionProgressDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertProgress(entity: CollectionProgressEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertWatched(entity: CollectionWatchedEntity)
+
+ @Query(
+ "UPDATE collection_progress SET lastPositionMillis = :positionMillis, durationMillis = :durationMillis, " +
+ "updatedAt = :updatedAt WHERE mid = :mid AND collectionId = :collectionId AND isSeason = :isSeason AND lastBvid = :bvid",
+ )
+ suspend fun updatePositionIfMatches(
+ mid: Long,
+ collectionId: Long,
+ isSeason: Boolean,
+ bvid: String,
+ positionMillis: Long,
+ durationMillis: Long,
+ updatedAt: Long,
+ )
+
+ @Query("SELECT * FROM collection_progress WHERE mid = :mid AND collectionId = :collectionId AND isSeason = :isSeason LIMIT 1")
+ fun observeProgress(mid: Long, collectionId: Long, isSeason: Boolean): Flow
+
+ @Query("SELECT bvid FROM collection_watched WHERE mid = :mid AND collectionId = :collectionId AND isSeason = :isSeason")
+ fun observeWatchedBvids(mid: Long, collectionId: Long, isSeason: Boolean): Flow>
+}
+
@Database(
entities = [
FeedReadPositionEntity::class,
FeedCacheItemEntity::class,
+ CollectionProgressEntity::class,
+ CollectionWatchedEntity::class,
],
- version = 9,
+ version = 10,
exportSchema = false,
)
@ConstructedBy(BilbyDatabaseConstructor::class)
abstract class BilbyDatabase : RoomDatabase() {
abstract fun feedReadPositionDao(): FeedReadPositionDao
abstract fun feedCacheItemDao(): FeedCacheItemDao
+ abstract fun collectionProgressDao(): CollectionProgressDao
companion object {
/** 文件位置与 SQLite 驱动由平台给出 [builder],其余配置两端相同。 */
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt b/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt
index 053b9a59..02909c85 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt
@@ -66,3 +66,36 @@ data class FeedCacheItemEntity(
const val KIND_ARTICLE = "article"
}
}
+
+/**
+ * 合集/系列的最后观看记录,用于合集目录顶部「继续观看」卡片。
+ */
+@Entity(
+ tableName = "collection_progress",
+ primaryKeys = ["mid", "collectionId", "isSeason"],
+)
+data class CollectionProgressEntity(
+ val mid: Long,
+ val collectionId: Long,
+ val isSeason: Boolean,
+ val lastBvid: String,
+ val lastTitle: String,
+ val lastCoverUrl: String,
+ val lastPositionMillis: Long = 0L,
+ val durationMillis: Long = 0L,
+ val updatedAt: Long,
+)
+
+/** 合集/系列内已观看过的视频集合,用于在目录列表项中标注已看状态。 */
+@Entity(
+ tableName = "collection_watched",
+ primaryKeys = ["mid", "collectionId", "isSeason", "bvid"],
+ indices = [androidx.room.Index(value = ["mid", "collectionId", "isSeason"])],
+)
+data class CollectionWatchedEntity(
+ val mid: Long,
+ val collectionId: Long,
+ val isSeason: Boolean,
+ val bvid: String,
+ val watchedAt: Long,
+)
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
index 1f92a6fd..f6694b3e 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
@@ -1155,6 +1155,44 @@ private fun BilbyApp(
}
}
+ // 播放合集/系列视频时(含自动连播切集与暂停),自动同步本地合集观看进度。
+ val playingCollectionSource = appAudioState.queue?.source?.takeIf { it.id > 0L }
+ val playingQueueItem = appAudioState.queue?.current
+ LaunchedEffect(playingCollectionSource, playingQueueItem?.bvid) {
+ val source = playingCollectionSource ?: return@LaunchedEffect
+ val item = playingQueueItem ?: return@LaunchedEffect
+ val pos = (playback.currentPositionMillis() ?: 0L).coerceAtLeast(0L)
+ val dur = (item.durationSeconds * 1000L).coerceAtLeast(0L)
+ container.collectionProgressRepository.recordPlay(
+ mid = source.mid,
+ collectionId = source.id,
+ isSeason = source.isSeason,
+ bvid = item.bvid,
+ title = item.title,
+ coverUrl = item.coverUrl,
+ positionMillis = pos,
+ durationMillis = dur,
+ )
+ }
+ LaunchedEffect(playingCollectionSource, playingQueueItem?.bvid, appAudioState.isPlaying) {
+ val source = playingCollectionSource ?: return@LaunchedEffect
+ val item = playingQueueItem ?: return@LaunchedEffect
+ if (!appAudioState.isPlaying) {
+ val pos = (playback.currentPositionMillis() ?: 0L).coerceAtLeast(0L)
+ val dur = (item.durationSeconds * 1000L).coerceAtLeast(0L)
+ if (pos > 0L) {
+ container.collectionProgressRepository.updatePosition(
+ mid = source.mid,
+ collectionId = source.id,
+ isSeason = source.isSeason,
+ bvid = item.bvid,
+ positionMillis = pos,
+ durationMillis = dur,
+ )
+ }
+ }
+ }
+
CompositionLocalProvider(LocalQueueActions provides queueMenuActions) {
Box(
modifier = Modifier
@@ -4535,7 +4573,13 @@ private fun CollectionRoute(
key = "collection-${key.mid}-${key.isSeason}-${key.id}",
factory = viewModelFactory {
initializer {
- CollectionViewModel(key.mid, key.id, key.isSeason, container.spaceRepository)
+ CollectionViewModel(
+ key.mid,
+ key.id,
+ key.isSeason,
+ container.spaceRepository,
+ container.collectionProgressRepository,
+ )
}
},
)
@@ -4546,9 +4590,24 @@ private fun CollectionRoute(
onBack = onBack,
onLoadMore = { vm.loadMore() },
onRefresh = vm::refresh,
+ onResumeBvid = { resumeBvid ->
+ val index = state.items.indexOfFirst { it.bvid == resumeBvid }
+ val page = if (index >= 0) index / SpaceRepository.COLLECTION_PAGE_SIZE + 1 else 1
+ onVideoClick(resumeBvid, QueueContext.Collection(key.mid, key.id, key.isSeason, key.name, page))
+ },
onVideoClick = { item ->
val index = state.items.indexOf(item).coerceAtLeast(0)
val page = index / SpaceRepository.COLLECTION_PAGE_SIZE + 1
+ container.persistScope.launch {
+ container.collectionProgressRepository.recordPlay(
+ mid = key.mid,
+ collectionId = key.id,
+ isSeason = key.isSeason,
+ bvid = item.bvid,
+ title = item.title,
+ coverUrl = item.coverUrl,
+ )
+ }
onVideoClick(item.bvid, QueueContext.Collection(key.mid, key.id, key.isSeason, key.name, page))
},
)
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt
index 5bcaf80b..53147f49 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt
@@ -1,11 +1,15 @@
package dev.bilby.ui.space
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.Icon
@@ -13,6 +17,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MediumFlexibleTopAppBar
import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
@@ -25,8 +30,11 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.bilby.api.BiliResult
import dev.bilby.appendDistinctBy
+import dev.bilby.data.CollectionProgressRepository
import dev.bilby.data.SpaceRepository
import dev.bilby.data.SpaceVideoItem
+import dev.bilby.data.db.CollectionProgressEntity
+import dev.bilby.formatDurationMillis
import dev.bilby.resources.*
import dev.bilby.stringResource
import dev.bilby.ui.CaptionDragHeight
@@ -37,6 +45,7 @@ import dev.bilby.ui.components.TopBarRefreshButton
import dev.bilby.ui.errorTextRes
import dev.bilby.ui.padScaffoldExceptBottom
import dev.bilby.ui.rememberCaptionSlot
+import dev.bilby.ui.theme.Spacing
import dev.bilby.ui.theme.tabular
import dev.bilby.ui.windowDragArea
import kotlinx.coroutines.flow.MutableStateFlow
@@ -57,6 +66,8 @@ data class CollectionUiState(
val hasMore: Boolean = true,
val error: String? = null,
val errorRes: StringResource? = null,
+ val lastProgress: CollectionProgressEntity? = null,
+ val watchedBvids: Set = emptySet(),
)
/**
@@ -67,6 +78,7 @@ class CollectionViewModel(
private val id: Long,
private val isSeason: Boolean,
private val repository: SpaceRepository,
+ private val progressRepository: CollectionProgressRepository? = null,
) : ViewModel() {
private val _state = MutableStateFlow(CollectionUiState())
@@ -77,6 +89,18 @@ class CollectionViewModel(
init {
loadMore()
+ progressRepository?.let { repo ->
+ viewModelScope.launch {
+ repo.observeProgress(mid, id, isSeason).collect { progress ->
+ _state.update { it.copy(lastProgress = progress) }
+ }
+ }
+ viewModelScope.launch {
+ repo.observeWatchedBvids(mid, id, isSeason).collect { watched ->
+ _state.update { it.copy(watchedBvids = watched) }
+ }
+ }
+ }
}
fun refresh() {
@@ -143,6 +167,7 @@ fun CollectionScreen(
onLoadMore: () -> Unit,
onRefresh: () -> Unit,
onVideoClick: (SpaceVideoItem) -> Unit,
+ onResumeBvid: ((String) -> Unit)? = null,
modifier: Modifier = Modifier,
) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
@@ -209,6 +234,7 @@ fun CollectionScreen(
onRefresh = onRefresh,
modifier = Modifier.fillMaxSize().padScaffoldExceptBottom(padding),
) {
+ val progress = state.lastProgress
VideoListTab(
items = state.items,
appending = state.appending,
@@ -218,8 +244,67 @@ fun CollectionScreen(
emptyText = stringResource(Res.string.space_empty_collection_detail),
onLoadMore = onLoadMore,
onVideoClick = onVideoClick,
+ lastWatchedBvid = progress?.lastBvid,
+ watchedBvids = state.watchedBvids,
+ header = if (progress != null && onResumeBvid != null) {
+ {
+ CollectionContinueBanner(
+ progress = progress,
+ onClick = { onResumeBvid(progress.lastBvid) },
+ )
+ }
+ } else {
+ null
+ },
modifier = Modifier.fillMaxSize(),
)
}
}
}
+
+@Composable
+private fun CollectionContinueBanner(
+ progress: CollectionProgressEntity,
+ onClick: () -> Unit,
+) {
+ val subtitle = if (progress.lastPositionMillis > 0L) {
+ stringResource(Res.string.collection_continue_progress, formatDurationMillis(progress.lastPositionMillis))
+ } else {
+ stringResource(Res.string.collection_continue_recent)
+ }
+ Surface(
+ onClick = onClick,
+ shape = MaterialTheme.shapes.large,
+ color = MaterialTheme.colorScheme.secondaryContainer,
+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = Spacing.Tight),
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(Spacing.Cozy),
+ modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Cozy),
+ ) {
+ Icon(
+ imageVector = Icons.Filled.PlayArrow,
+ contentDescription = null,
+ )
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = "${stringResource(Res.string.collection_continue_watching)} $subtitle",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSecondaryContainer,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ text = progress.lastTitle.ifBlank { progress.lastBvid },
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ }
+}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt
index e48bf7cd..556ff8f1 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt
@@ -2341,6 +2341,8 @@ internal fun VideoListTab(
onVideoClick: (SpaceVideoItem) -> Unit,
modifier: Modifier = Modifier,
header: (@Composable () -> Unit)? = null,
+ lastWatchedBvid: String? = null,
+ watchedBvids: Set = emptySet(),
@Suppress("UNUSED_PARAMETER") columns: GridCells = GridCells.Fixed(1),
) {
val density = LocalDensity.current
@@ -2396,7 +2398,13 @@ internal fun VideoListTab(
}
},
) { item ->
- val typeBadge = chargingBadgeText(item.chargingOnly)
+ val typeBadge = chargingBadgeText(item.chargingOnly).ifEmpty {
+ when {
+ item.bvid == lastWatchedBvid -> stringResource(Res.string.collection_badge_last)
+ item.bvid in watchedBvids -> stringResource(Res.string.collection_badge_watched)
+ else -> ""
+ }
+ }
val rowUi = remember(item, typeBadge) {
VideoRowUi(
title = item.title,
From 0074f5857b9db27d3dd2cb2b5c2b9298d3cd9686 Mon Sep 17 00:00:00 2001
From: NihilDigit
Date: Mon, 30 Nov 2026 00:56:36 +0800
Subject: [PATCH 2/2] refactor(collection): persist watch progress in isolated
store via ProgressSession with deep-page resume
---
.../dev/bilby/player/AudioPlaybackService.kt | 151 +++++-
.../bilby/player/BilbyMediaSourceFactory.kt | 11 +
.../composeResources/values-en/strings.xml | 10 +-
.../composeResources/values/strings.xml | 10 +-
.../kotlin/dev/bilby/AppContainer.kt | 20 +-
.../data/CollectionProgressRepository.kt | 76 ---
.../dev/bilby/data/CollectionProgressStore.kt | 449 ++++++++++++++++++
.../dev/bilby/data/TvLoginRepository.kt | 2 +
.../kotlin/dev/bilby/data/VideoRepository.kt | 3 +
.../kotlin/dev/bilby/data/db/BilbyDatabase.kt | 34 +-
.../kotlin/dev/bilby/data/db/Entities.kt | 33 --
.../kotlin/dev/bilby/player/PartRequest.kt | 47 +-
.../dev/bilby/player/ProgressSession.kt | 6 +
.../kotlin/dev/bilby/ui/BilbyApp.kt | 85 ++--
.../dev/bilby/ui/settings/SettingsPages.kt | 44 ++
.../bilby/ui/settings/SettingsViewModel.kt | 16 +
.../dev/bilby/ui/space/CollectionScreen.kt | 290 ++++++++---
.../kotlin/dev/bilby/ui/space/SpaceScreen.kt | 18 +-
.../bilby/data/CollectionProgressStoreTest.kt | 387 +++++++++++++++
.../dev/bilby/player/DesktopPlaybackHost.kt | 146 +++++-
20 files changed, 1525 insertions(+), 313 deletions(-)
delete mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
create mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressStore.kt
create mode 100644 shared/src/commonTest/kotlin/dev/bilby/data/CollectionProgressStoreTest.kt
diff --git a/shared/src/androidMain/kotlin/dev/bilby/player/AudioPlaybackService.kt b/shared/src/androidMain/kotlin/dev/bilby/player/AudioPlaybackService.kt
index 8b9131b6..96583a7a 100644
--- a/shared/src/androidMain/kotlin/dev/bilby/player/AudioPlaybackService.kt
+++ b/shared/src/androidMain/kotlin/dev/bilby/player/AudioPlaybackService.kt
@@ -31,7 +31,11 @@ import dev.bilby.getString
import dev.bilby.getStringBlocking
import dev.bilby.resources.*
import dev.bilby.api.BiliResult
+import dev.bilby.data.CollectionKey
+import dev.bilby.data.CollectionPlaybackTarget
+import dev.bilby.data.CollectionProgressStore
import dev.bilby.data.HeartbeatReporter
+import dev.bilby.data.HistoryRepository
import dev.bilby.data.LiveRepository
import dev.bilby.data.PlayEndMode
import dev.bilby.data.PlayInfo
@@ -45,6 +49,8 @@ import dev.bilby.data.QueueSourceRepository
import dev.bilby.data.SettingsStore
import dev.bilby.data.SubtitleRepository
import dev.bilby.data.VideoRepository
+import dev.bilby.data.resolveCollectionTargets
+import dev.bilby.data.resolveEffectiveResumeMillis
import dev.bilby.data.resumeAtMillisFor
import dev.bilby.offline.OfflineItem
import dev.bilby.offline.OfflineStatus
@@ -150,6 +156,9 @@ class AudioPlaybackService : MediaSessionService() {
/** 进度会话的上报出口,见 [ProgressSession]。 */
private lateinit var heartbeatReporter: HeartbeatReporter
+ private lateinit var collectionProgressStore: CollectionProgressStore
+ private lateinit var historyRepository: HistoryRepository
+ private var historyPauseProbeStarted = false
/** 这次装载放哪一 P、从哪儿起播,一次解析。见 [LoadResolver]。 */
private lateinit var loadResolver: LoadResolver
@@ -326,6 +335,8 @@ class AudioPlaybackService : MediaSessionService() {
persistScope = container.persistScope
partRequest = container.partRequest
heartbeatReporter = container.heartbeatReporter
+ collectionProgressStore = container.collectionProgressStore
+ historyRepository = container.historyRepository
loadResolver = LoadResolver(
localCopy = offlineStore::completedFor,
parts = { bvid ->
@@ -573,18 +584,20 @@ class AudioPlaybackService : MediaSessionService() {
}
// **指名在入口取走。** 它是一次性的:没被取走就一直挂着,等这条视频某次冷装载时再把
// 播放位置推到用户几分钟前点的那一 P(见 [PartRequest])。
- val requestedCid = partRequest.consume(bvid)
+ val startHint = partRequest.consumeHint(bvid)
+ val requestedCid = startHint.cid
+ val fallbackStartMillis = startHint.fallbackPositionMillis.takeIf { it > 0L }
val live = liveFrame
if (live?.id == frameId) {
- resumeFrame(live, bvid, requestedCid)
+ resumeFrame(live, bvid, requestedCid, fallbackStartMillis)
return
}
val context = args.getString(EXTRA_QUEUE_CONTEXT)?.let(::decodeQueueContext) ?: QueueContext.Affiliation
suspendLiveFrame()
val frame = frames.getOrPut(frameId) { Frame(frameId, context) }
val snapshot = frame.snapshot
- if (snapshot != null) restoreFrame(frame, snapshot) else openFrame(frame, bvid, requestedCid)
+ if (snapshot != null) restoreFrame(frame, snapshot) else openFrame(frame, bvid, requestedCid, fallbackStartMillis)
}
/**
@@ -598,12 +611,18 @@ class AudioPlaybackService : MediaSessionService() {
* 解析都不发生:在网页上看到后面某一 P,回到 Bilby 还停在旧位置。核对只摆一条提示,跳不跳由
* 用户点(仓库主人定的,直接落位这个方案被否决过)。
*/
- private fun resumeFrame(frame: Frame, bvid: String, requestedCid: Long) {
+ private fun resumeFrame(frame: Frame, bvid: String, requestedCid: Long, fallbackStartMillis: Long?) {
val current = currentItem()?.bvid
if (current != null) {
// 指名兑现成一次真正的切 P。已经在放的就是那一 P 时什么都不做:重来一遍只会把画面
// 打回这一 P 的开头。
- if (current == bvid && requestedCid != 0L && requestedCid != loadedCid) playPart(requestedCid)
+ if (current == bvid) {
+ if (requestedCid != 0L && requestedCid != loadedCid) {
+ playPart(requestedCid, fallbackStartMillis ?: 0L)
+ } else if (fallbackStartMillis != null && player.currentPosition < 1_000L) {
+ player.seekTo(fallbackStartMillis)
+ }
+ }
reconcileIfLocalCopy(current)
reconcileCloudProgress(current)
}
@@ -680,18 +699,28 @@ class AudioPlaybackService : MediaSessionService() {
* 临时条目只有 bvid:标题与封面由取流时的详情补上(见 [fillDisplayFromDetail]),放哪一 P 由
* [LoadResolver] 在装载时解析。
*/
- private fun openFrame(frame: Frame, bvid: String, requestedCid: Long) {
+ private fun openFrame(frame: Frame, bvid: String, requestedCid: Long, fallbackStartMillis: Long?) {
if (frame.anchorBvid.isEmpty()) frame.anchorBvid = bvid
finishOpenChain("superseded")
openChain = PerfTrace.chain("openVideo").also { it.mark("command") }
frameOrderTouched = false
val temporary = QueueItem(bvid = bvid, title = "", upName = "", coverUrl = "", durationSeconds = 0)
- .toMediaItem(requestedCid = requestedCid, loadNonce = nextLoadNonce())
+ .toMediaItem(
+ requestedCid = requestedCid,
+ fallbackStartPositionMillis = fallbackStartMillis,
+ loadNonce = nextLoadNonce(),
+ )
val kept = replaceQueue(listOf(temporary), 0, playWhenReady = true)
applyQueueOrder(defaultQueueOrder)
openChain?.mark("tempQueue")
liveFrame = frame
- if (kept && requestedCid != 0L && requestedCid != loadedCid) playPart(requestedCid)
+ if (kept) {
+ if (requestedCid != 0L && requestedCid != loadedCid) {
+ playPart(requestedCid, fallbackStartMillis ?: 0L)
+ } else if (fallbackStartMillis != null && player.currentPosition < 1_000L) {
+ player.seekTo(fallbackStartMillis)
+ }
+ }
enrichFrame(frame, bvid)
}
@@ -1345,6 +1374,7 @@ class AudioPlaybackService : MediaSessionService() {
if (mediaItem.isLive) return resolveLiveStream(mediaItem)
val bvid = mediaItem.mediaId
val positionOverrideMillis = mediaItem.startPositionHint
+ val fallbackStartMillis = mediaItem.fallbackStartPositionHint
// 指名的那一 P,全部来自条目自己。页内切 P、切清晰度、重试带着上一次解析出来的那个;
// 缓存列表点某行写进 [PartRequest] 的那份,由 [activateFrame] 在入口取走并放进 cidHint。
//
@@ -1356,7 +1386,7 @@ class AudioPlaybackService : MediaSessionService() {
// 自动连播都不改它,于是缓存库队列里的每一条都走本地。
val preferLocal = liveFrame?.context == QueueContext.Offline
when (val plan = loadResolver.resolve(bvid, requestedCid, preferLocal)) {
- is LoadPlan.LocalCopy -> return localCopySource(mediaItem, plan, positionOverrideMillis)
+ is LoadPlan.LocalCopy -> return localCopySource(mediaItem, plan, positionOverrideMillis, fallbackStartMillis)
LoadPlan.Unresolved -> {
BiliLog.w("解析不出要放哪一 P bvid=$bvid")
@@ -1368,6 +1398,7 @@ class AudioPlaybackService : MediaSessionService() {
bvid,
plan.cid,
positionOverrideMillis,
+ fallbackStartMillis,
mediaItem.loadNonce,
)
} catch (failure: IOException) {
@@ -1375,7 +1406,7 @@ class AudioPlaybackService : MediaSessionService() {
// 它比"本地也没有"更接近原因。
val fallback = loadResolver.localFallback(bvid, plan.cid) ?: throw failure
BiliLog.w("在线取流失败,退到本地副本 bvid=$bvid cid=${plan.cid}")
- localCopySource(mediaItem, fallback, positionOverrideMillis)
+ localCopySource(mediaItem, fallback, positionOverrideMillis, fallbackStartMillis)
}
}
}
@@ -1385,6 +1416,7 @@ class AudioPlaybackService : MediaSessionService() {
mediaItem: MediaItem,
plan: LoadPlan.LocalCopy,
positionOverrideMillis: Long?,
+ fallbackStartMillis: Long?,
): MediaSource {
val cached = plan.item
// 标题/UP/封面从索引里填。离线时这是元数据唯一的来源。
@@ -1395,7 +1427,12 @@ class AudioPlaybackService : MediaSessionService() {
mediaId = cached.bvid,
loadNonce = mediaItem.loadNonce,
cid = cached.cid,
- startPositionMillis = positionOverrideMillis ?: plan.startPositionMillis,
+ startPositionMillis = resolveEffectiveResumeMillis(
+ explicitOverrideMillis = positionOverrideMillis,
+ cloudOrLocalStartMillis = plan.startPositionMillis,
+ fallbackResumeMillis = fallbackStartMillis,
+ durationMillis = cached.durationSeconds * 1000L,
+ ),
localCopy = true,
// 画质菜单留空:本地只有下载时选的那一档,摆一个点了没用的菜单不如不摆。
playInfo = null,
@@ -1463,6 +1500,7 @@ class AudioPlaybackService : MediaSessionService() {
bvid: String,
cid: Long,
positionOverrideMillis: Long?,
+ fallbackStartMillis: Long?,
loadNonce: Int,
): MediaSource {
fillDisplayFromDetail(bvid)
@@ -1501,12 +1539,19 @@ class AudioPlaybackService : MediaSessionService() {
val local = offlineStore.completed(bvid, cid)
?.takeIf { prefersLocalFiles(it.qualityId, playUrl.streams.qualityId, sessionQuality != 0) }
if (local != null) {
+ val localDuration = playUrl.durationMillis.takeIf { it > 0L } ?: local.durationSeconds * 1000L
onResolved(
LoadedItem(
mediaId = bvid,
loadNonce = loadNonce,
cid = cid,
- startPositionMillis = positionOverrideMillis ?: localCopyResumeMillis(local, playUrl, cid),
+ startPositionMillis = resolveEffectiveResumeMillis(
+ explicitOverrideMillis = positionOverrideMillis,
+ cloudOrLocalStartMillis = localCopyResumeMillis(local, playUrl, cid),
+ fallbackResumeMillis = fallbackStartMillis,
+ durationMillis = localDuration,
+ finishedThresholdMillis = playUrl.finishedThresholdMillis,
+ ),
// 这一次是在线装载:云端核对走会话那条(见 [reconcileCloudProgress]),不走
// 本地副本那条,起播位置已经在上面和云端合并过。
localCopy = false,
@@ -1528,7 +1573,13 @@ class AudioPlaybackService : MediaSessionService() {
mediaId = bvid,
loadNonce = loadNonce,
cid = cid,
- startPositionMillis = positionOverrideMillis ?: playUrl.resumeAtMillisFor(cid),
+ startPositionMillis = resolveEffectiveResumeMillis(
+ explicitOverrideMillis = positionOverrideMillis,
+ cloudOrLocalStartMillis = playUrl.resumeAtMillisFor(cid),
+ fallbackResumeMillis = fallbackStartMillis,
+ durationMillis = playUrl.durationMillis,
+ finishedThresholdMillis = playUrl.finishedThresholdMillis,
+ ),
localCopy = false,
playInfo = playUrl,
// **实际选中的那一档,不是请求的那一档。** 请求的是偏好(比如 1080P60),这条
@@ -1789,7 +1840,79 @@ class AudioPlaybackService : MediaSessionService() {
BiliLog.w("建不了进度会话 bvid=$bvid cid=$cid")
return
}
- val session = ProgressSession(aid, cid) { playedTimeSeconds, finished, onConfirmed ->
+ if (historyRepository.lastKnownPaused == null && !historyPauseProbeStarted) {
+ historyPauseProbeStarted = true
+ scope.launch { historyRepository.isPaused() }
+ }
+ fun resolveTargets(): List {
+ val frame = liveFrame
+ val count = player.mediaItemCount
+ val currentIdx = player.currentMediaItemIndex
+ val currentTitle = currentItem()?.takeIf { it.bvid == bvid }?.title.orEmpty()
+ val detached = frame?.detached == true
+ val pos = if (frame != null && !detached && count > 0 && currentIdx in 0 until count) {
+ frame.pagination.sourcePositionFor(currentIdx, count)
+ } else {
+ null
+ }
+ val total = if (frame != null && !detached) frame.pagination.sourceTotal else null
+ return resolveCollectionTargets(
+ bvid = bvid,
+ cachedDetail = videoRepository.cachedVideoDetail(bvid),
+ frameContext = frame?.context,
+ frameSource = frame?.source,
+ sourcePosition = pos,
+ sourceTotal = total,
+ detached = detached,
+ fallbackTitle = currentTitle,
+ )
+ }
+ var cachedTargets = resolveTargets()
+ val fallbackDurationMillis = playInfo?.durationMillis?.takeIf { it > 0L }
+ ?: currentItem()?.takeIf { it.bvid == bvid }?.durationSeconds?.takeIf { it > 0L }?.times(1000L)
+ ?: 0L
+ val session = ProgressSession(
+ aid = aid,
+ cid = cid,
+ onProgressRecorded = { positionMillis, durationMillis, completed ->
+ val latest = resolveTargets()
+ if (latest.isNotEmpty()) {
+ val merged = LinkedHashMap()
+ cachedTargets.forEach { merged[CollectionKey(it.isSeason, it.id)] = it }
+ latest.forEach { target ->
+ val key = CollectionKey(target.isSeason, target.id)
+ val prev = merged[key]
+ merged[key] = target.copy(
+ defaultOrderIndex = target.defaultOrderIndex ?: prev?.defaultOrderIndex,
+ totalCount = target.totalCount.takeIf { it > 0 } ?: prev?.totalCount ?: 0,
+ title = target.title.ifBlank { prev?.title.orEmpty() },
+ )
+ }
+ cachedTargets = merged.values.toList()
+ }
+ val targets = cachedTargets
+ if (targets.isEmpty()) return@ProgressSession
+ val effectiveDuration = durationMillis.takeIf { it > 0L }
+ ?: playInfo?.durationMillis?.takeIf { it > 0L }
+ ?: fallbackDurationMillis
+ persistScope.launch {
+ targets.forEach { target ->
+ collectionProgressStore.recordProgress(
+ isSeason = target.isSeason,
+ id = target.id,
+ bvid = bvid,
+ cid = cid,
+ title = target.title,
+ positionMillis = positionMillis,
+ durationMillis = effectiveDuration,
+ completed = completed,
+ defaultOrderIndex = target.defaultOrderIndex,
+ totalCount = target.totalCount,
+ )
+ }
+ }
+ },
+ ) { playedTimeSeconds, finished, onConfirmed ->
// 缓存条目的进度与 base 由上报方随结果一起记(成功推两者,没发出去只记本地),
// 见 [HeartbeatReporter.report]。这里只把确认送回会话。
heartbeatReporter.report(aid, cid, bvid, playedTimeSeconds, finished) {
diff --git a/shared/src/androidMain/kotlin/dev/bilby/player/BilbyMediaSourceFactory.kt b/shared/src/androidMain/kotlin/dev/bilby/player/BilbyMediaSourceFactory.kt
index 9a2487d8..c9e28e2c 100644
--- a/shared/src/androidMain/kotlin/dev/bilby/player/BilbyMediaSourceFactory.kt
+++ b/shared/src/androidMain/kotlin/dev/bilby/player/BilbyMediaSourceFactory.kt
@@ -45,6 +45,7 @@ class BilbyMediaSourceFactory(
private const val EXTRA_ITEM_CID = "cid"
private const val EXTRA_ITEM_START_MS = "startMs"
+private const val EXTRA_ITEM_FALLBACK_START_MS = "fallbackStartMs"
private const val EXTRA_ITEM_LOAD = "load"
private const val EXTRA_ITEM_ROOM_ID = "roomId"
private const val EXTRA_ITEM_LIVE_QN = "liveQn"
@@ -65,6 +66,10 @@ val MediaItem.cidHint: Long
val MediaItem.startPositionHint: Long?
get() = requestMetadata.extras?.getLong(EXTRA_ITEM_START_MS, -1L)?.takeIf { it >= 0 }
+/** 一次性本机续播兜底位置(毫秒),仅在云端进度缺失或落后时生效。 */
+val MediaItem.fallbackStartPositionHint: Long?
+ get() = requestMetadata.extras?.getLong(EXTRA_ITEM_FALLBACK_START_MS, -1L)?.takeIf { it > 0 }
+
/**
* 第几次装载这一条。**"要不要重新取流"就是靠它表达的。**
*
@@ -111,6 +116,7 @@ val MediaItem.isLive: Boolean
fun QueueItem.toMediaItem(
requestedCid: Long = 0,
startPositionMillis: Long? = null,
+ fallbackStartPositionMillis: Long? = null,
loadNonce: Int = 0,
): MediaItem = MediaItem.Builder()
.setMediaId(bvid)
@@ -118,6 +124,7 @@ fun QueueItem.toMediaItem(
loadParams(
requestedCid = requestedCid,
startPositionMillis = startPositionMillis,
+ fallbackStartPositionMillis = fallbackStartPositionMillis,
loadNonce = loadNonce,
)
)
@@ -158,6 +165,7 @@ fun MediaItem.withLoadParams(
loadNonce: Int,
requestedCid: Long = 0,
startPositionMillis: Long? = null,
+ fallbackStartPositionMillis: Long? = null,
liveQn: Int = this.liveQn,
onlyAudio: Boolean = this.liveOnlyAudio,
): MediaItem = buildUpon()
@@ -165,6 +173,7 @@ fun MediaItem.withLoadParams(
loadParams(
requestedCid = requestedCid,
startPositionMillis = startPositionMillis,
+ fallbackStartPositionMillis = fallbackStartPositionMillis,
loadNonce = loadNonce,
roomId = liveRoomId,
liveQn = liveQn,
@@ -176,6 +185,7 @@ fun MediaItem.withLoadParams(
private fun loadParams(
requestedCid: Long = 0,
startPositionMillis: Long? = null,
+ fallbackStartPositionMillis: Long? = null,
loadNonce: Int = 0,
roomId: Long = 0,
liveQn: Int = 0,
@@ -185,6 +195,7 @@ private fun loadParams(
Bundle().apply {
putLong(EXTRA_ITEM_CID, requestedCid)
putLong(EXTRA_ITEM_START_MS, startPositionMillis ?: -1L)
+ putLong(EXTRA_ITEM_FALLBACK_START_MS, fallbackStartPositionMillis ?: -1L)
putInt(EXTRA_ITEM_LOAD, loadNonce)
putLong(EXTRA_ITEM_ROOM_ID, roomId)
putInt(EXTRA_ITEM_LIVE_QN, liveQn)
diff --git a/shared/src/commonMain/composeResources/values-en/strings.xml b/shared/src/commonMain/composeResources/values-en/strings.xml
index 1f6b4261..f3bbd62d 100644
--- a/shared/src/commonMain/composeResources/values-en/strings.xml
+++ b/shared/src/commonMain/composeResources/values-en/strings.xml
@@ -998,11 +998,15 @@
Show %1$d more uploads
%1$d live
%1$d videos
+ %1$d watched
Continue watching
Left off at %1$s
- Last watched
- Last watched
- Watched
+ Next episode
+ Watched
+ Clear collection watch progress
+ Remove locally saved collection and series progress
+ Remove all locally saved collection and series watch progress?
+ %1$d saved
%1$d steps searched
Search watch history
diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml
index b671d5fe..f41a41b0 100644
--- a/shared/src/commonMain/composeResources/values/strings.xml
+++ b/shared/src/commonMain/composeResources/values/strings.xml
@@ -1060,11 +1060,15 @@
展开其余 %1$d 条连发
%1$d 直播
共 %1$d 个视频
+ 已看 %1$d
继续观看
上次看到 %1$s
- 上次观看
- 上次看到
- 已看
+ 下一集
+ 已看完
+ 清除合集观看记录
+ 清除本机保存的合集与系列观看进度
+ 清除本机保存的所有合集与系列观看进度?
+ %1$d 项
已检索 %1$d 步
搜索历史记录
diff --git a/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt b/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
index 5340f7c5..116f287a 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/AppContainer.kt
@@ -9,12 +9,12 @@ import dev.bilby.api.DeviceFingerprint
import dev.bilby.api.WbiSigner
import dev.bilby.data.AccountRepository
import dev.bilby.data.ArticleRepository
-import dev.bilby.data.CollectionProgressRepository
import dev.bilby.data.DanmakusRepository
import dev.bilby.data.DynamicFeedStore
import dev.bilby.data.DynamicRepository
import dev.bilby.data.FingerprintStore
import dev.bilby.danmaku.DanmakuRepository
+import dev.bilby.data.CollectionProgressStore
import dev.bilby.data.CommentRepository
import dev.bilby.data.EmoteRepository
import dev.bilby.data.FavRepository
@@ -124,7 +124,9 @@ class AppContainer(
*
* 没有 cookie 刷新这一环:凭据过期就重新扫码,理由见 notes/auth-model.md §7。
*/
- val tvLoginRepository: TvLoginRepository by lazy { TvLoginRepository(biliClient, settings, deviceFingerprint) }
+ val tvLoginRepository: TvLoginRepository by lazy {
+ TvLoginRepository(biliClient, settings, deviceFingerprint, collectionProgressStore)
+ }
val dynamicRepository: DynamicRepository by lazy { DynamicRepository(biliClient) }
@@ -139,11 +141,6 @@ class AppContainer(
FeedCacheRepository(database.feedCacheItemDao())
}
- /** 合集/系列观看进度与已看记录。 */
- val collectionProgressRepository: CollectionProgressRepository by lazy {
- CollectionProgressRepository(database)
- }
-
/**
* 关注动态流。**挂在容器上而不是某个 ViewModel 上**:首页和"其他动态"是同一条流的两个
* 视图,而它们分属不同的导航目的地,ViewModel 的作用域套不住两边(见 DynamicFeedStore)。
@@ -179,6 +176,15 @@ class AppContainer(
val historyRepository: HistoryRepository by lazy { HistoryRepository(biliClient) }
+ /** 合集与系列观看进度独立 JSON 存储,脱离 Room 破坏性迁移生命周期。 */
+ val collectionProgressStore: CollectionProgressStore by lazy {
+ CollectionProgressStore(
+ file = java.io.File(platform.filesDir, "collection-progress.json"),
+ json = json,
+ isHistoryPaused = { historyRepository.lastKnownPaused == true },
+ )
+ }
+
/** 消息中心(回复/@/赞/通知)与私信。两组接口分属两个主机,见它自己的说明。 */
val messageRepository: MessageRepository by lazy { MessageRepository(biliClient) }
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
deleted file mode 100644
index 9d6d4603..00000000
--- a/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressRepository.kt
+++ /dev/null
@@ -1,76 +0,0 @@
-package dev.bilby.data
-
-import dev.bilby.data.db.BilbyDatabase
-import dev.bilby.data.db.CollectionProgressEntity
-import dev.bilby.data.db.CollectionWatchedEntity
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.flow.map
-
-/**
- * 合集/系列追更进度仓库:记录每个合集最后观看的视频、进度与已看条目集合。
- */
-class CollectionProgressRepository(private val db: BilbyDatabase) {
- private val dao get() = db.collectionProgressDao()
-
- fun observeProgress(mid: Long, collectionId: Long, isSeason: Boolean): Flow =
- dao.observeProgress(mid, collectionId, isSeason)
-
- fun observeWatchedBvids(mid: Long, collectionId: Long, isSeason: Boolean): Flow> =
- dao.observeWatchedBvids(mid, collectionId, isSeason).map { it.toSet() }
-
- suspend fun recordPlay(
- mid: Long,
- collectionId: Long,
- isSeason: Boolean,
- bvid: String,
- title: String,
- coverUrl: String = "",
- positionMillis: Long = 0L,
- durationMillis: Long = 0L,
- ) {
- if (mid <= 0L || collectionId <= 0L || bvid.isBlank()) return
- val now = System.currentTimeMillis()
- dao.upsertProgress(
- CollectionProgressEntity(
- mid = mid,
- collectionId = collectionId,
- isSeason = isSeason,
- lastBvid = bvid,
- lastTitle = title,
- lastCoverUrl = coverUrl,
- lastPositionMillis = positionMillis.coerceAtLeast(0L),
- durationMillis = durationMillis.coerceAtLeast(0L),
- updatedAt = now,
- ),
- )
- dao.upsertWatched(
- CollectionWatchedEntity(
- mid = mid,
- collectionId = collectionId,
- isSeason = isSeason,
- bvid = bvid,
- watchedAt = now,
- ),
- )
- }
-
- suspend fun updatePosition(
- mid: Long,
- collectionId: Long,
- isSeason: Boolean,
- bvid: String,
- positionMillis: Long,
- durationMillis: Long,
- ) {
- if (mid <= 0L || collectionId <= 0L || bvid.isBlank()) return
- dao.updatePositionIfMatches(
- mid = mid,
- collectionId = collectionId,
- isSeason = isSeason,
- bvid = bvid,
- positionMillis = positionMillis.coerceAtLeast(0L),
- durationMillis = durationMillis.coerceAtLeast(0L),
- updatedAt = System.currentTimeMillis(),
- )
- }
-}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressStore.kt b/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressStore.kt
new file mode 100644
index 00000000..83eef6d5
--- /dev/null
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/CollectionProgressStore.kt
@@ -0,0 +1,449 @@
+package dev.bilby.data
+
+import dev.bilby.BiliLog
+import dev.bilby.player.resumePositionMillis
+import java.io.File
+import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.onStart
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+
+/** 合集/系列唯一键。合集(season)与系列(series)的 id 空间各自独立,必须成对区分。 */
+@Serializable
+data class CollectionKey(
+ val isSeason: Boolean,
+ val id: Long,
+)
+
+/** 单集未完播时的本地进度快照,用于在目录项上绘制封面底部细进度条与断点提示。 */
+@Serializable
+data class EpisodeProgress(
+ val positionMillis: Long = 0L,
+ val durationMillis: Long = 0L,
+)
+
+/**
+ * 单个合集或系列的本机观看进度记录。
+ *
+ * 独立于走 `fallbackToDestructiveMigration` 的 [dev.bilby.data.db.BilbyDatabase] 落盘,
+ * 保证缓存表升级不会丢失用户的合集观看记录。
+ */
+@Serializable
+data class CollectionProgress(
+ val isSeason: Boolean,
+ val id: Long,
+ val lastBvid: String,
+ val lastCid: Long = 0L,
+ val lastTitle: String = "",
+ val positionMillis: Long = 0L,
+ val durationMillis: Long = 0L,
+ val completed: Boolean = false,
+ /** 最近观看条目在默认顺序(非倒序)下的 0-based 下标,未知时为 null。 */
+ val defaultOrderIndex: Int? = null,
+ /** 该合集/系列已知的总集数,未知时为 0。 */
+ val totalCount: Int = 0,
+ val updatedAtMillis: Long = 0L,
+ val watchedBvids: Set = emptySet(),
+ /** 未完播的各集断点位置,完播并进入 [watchedBvids] 后自动移出以保持文件精简。 */
+ val episodePositions: Map = emptyMap(),
+) {
+ val key: CollectionKey get() = CollectionKey(isSeason = isSeason, id = id)
+}
+
+/** 一次播放进度上报对应的目标合集/系列与位置线索。 */
+data class CollectionPlaybackTarget(
+ val isSeason: Boolean,
+ val id: Long,
+ val defaultOrderIndex: Int? = null,
+ val totalCount: Int = 0,
+ val title: String = "",
+)
+
+/**
+ * 合集与系列观看进度的独立 JSON 持久化存储。
+ *
+ * - 落盘于 `platform.filesDir` 下的独立 JSON 文件(先写临时文件再 rename 原子替换),不碰 Room 缓存库。
+ * - 当账号开启「暂停记录观看历史」时停止写入;清空记录或登出时同步清内存并删除文件。
+ * - 与 [dev.bilby.player.ProgressSession] 对齐:忽略不足 1 秒的起播位置,仅在完播或进度达到 85%
+ * 时将条目加入 `watchedBvids`。
+ */
+class CollectionProgressStore(
+ private val file: File,
+ private val json: Json,
+ private val isHistoryPaused: () -> Boolean = { false },
+ private val clock: () -> Long = System::currentTimeMillis,
+) {
+
+ private val lock = Mutex()
+
+ @Volatile
+ private var loaded = false
+
+ private val _entries = MutableStateFlow