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>(emptyMap()) + val entries: StateFlow> = _entries.asStateFlow() + + /** + * 从目录页点开系列(`isSeason == false`)时暂存的正序下标与总集数。 + * 不在此刻写盘也不标记已看,待播放推进到真实位置后再并入持久化记录。 + */ + private val rememberedOrders = ConcurrentHashMap() + + suspend fun ensureLoaded() { + if (loaded) return + lock.withLock { + if (loaded) return + val diskEntries = readFromDisk() + _entries.value = diskEntries + loaded = true + } + } + + fun observe(isSeason: Boolean, id: Long): Flow { + val key = CollectionKey(isSeason = isSeason, id = id) + return _entries + .onStart { ensureLoaded() } + .map { it[key] } + .distinctUntilChanged() + } + + fun observeCount(): Flow = _entries + .onStart { ensureLoaded() } + .map { it.size } + .distinctUntilChanged() + + suspend fun get(isSeason: Boolean, id: Long): CollectionProgress? { + ensureLoaded() + return _entries.value[CollectionKey(isSeason = isSeason, id = id)] + } + + suspend fun snapshot(): Map { + ensureLoaded() + return _entries.value + } + + /** 暂存用户在合集/系列目录点击某集时已知的默认顺序下标,不产生 0 秒观看记录。 */ + fun rememberEpisodeOrder( + isSeason: Boolean, + id: Long, + bvid: String, + defaultOrderIndex: Int?, + totalCount: Int, + ) { + if (id <= 0L || bvid.isBlank()) return + if (defaultOrderIndex == null && totalCount <= 0) return + rememberedOrders[EpisodeOrderKey(isSeason, id, bvid)] = EpisodeOrderHint( + defaultOrderIndex = defaultOrderIndex?.takeIf { it >= 0 }, + totalCount = totalCount.coerceAtLeast(0), + ) + } + + /** + * 记录一次来自播放层的有效观看进度。 + * + * - 暂停历史开启时静默忽略。 + * - 未完播且位置不足 [MIN_RECORD_POSITION_MILLIS](1 秒)时忽略,避免 0 秒起播污染进度或误标已看。 + * - 仅当 [completed] 为真或 `durationMillis > 0 && positionMillis >= (durationMillis * 85) / 100` + * 时加入 `watchedBvids` 并记为已完成。 + */ + suspend fun recordProgress( + isSeason: Boolean, + id: Long, + bvid: String, + cid: Long, + title: String, + positionMillis: Long, + durationMillis: Long, + completed: Boolean, + defaultOrderIndex: Int? = null, + totalCount: Int = 0, + ) { + if (id <= 0L || bvid.isBlank()) return + if (isHistoryPaused()) return + val safePosition = positionMillis.coerceAtLeast(0L) + val safeDuration = durationMillis.coerceAtLeast(0L) + if (safePosition < MIN_RECORD_POSITION_MILLIS && !completed) return + + val watchedNow = completed || isWatchedByProgress(safePosition, safeDuration) + val hint = rememberedOrders[EpisodeOrderKey(isSeason, id, bvid)] + val key = CollectionKey(isSeason = isSeason, id = id) + + lock.withLock { + if (!loaded) { + _entries.value = readFromDisk() + loaded = true + } + val currentMap = _entries.value + val existing = currentMap[key] + + val resolvedOrderIndex = defaultOrderIndex?.takeIf { it >= 0 } + ?: hint?.defaultOrderIndex + ?: existing?.takeIf { it.lastBvid == bvid }?.defaultOrderIndex + val resolvedTotalCount = totalCount.takeIf { it > 0 } + ?: hint?.totalCount?.takeIf { it > 0 } + ?: existing?.totalCount + ?: 0 + val resolvedTitle = title.ifBlank { + existing?.takeIf { it.lastBvid == bvid }?.lastTitle.orEmpty() + } + val nextWatched = if (watchedNow) { + existing?.watchedBvids.orEmpty() + bvid + } else { + existing?.watchedBvids.orEmpty() + } + val nextPositions = existing?.episodePositions.orEmpty().toMutableMap() + if (watchedNow || bvid in nextWatched) { + nextPositions.remove(bvid) + } else { + val prevDuration = nextPositions[bvid]?.durationMillis ?: 0L + nextPositions[bvid] = EpisodeProgress( + positionMillis = safePosition, + durationMillis = safeDuration.takeIf { it > 0L } ?: prevDuration, + ) + } + + val updated = CollectionProgress( + isSeason = isSeason, + id = id, + lastBvid = bvid, + lastCid = cid.takeIf { it > 0L } ?: existing?.takeIf { it.lastBvid == bvid }?.lastCid ?: 0L, + lastTitle = resolvedTitle, + positionMillis = safePosition, + durationMillis = safeDuration.takeIf { it > 0L } + ?: existing?.takeIf { it.lastBvid == bvid }?.durationMillis + ?: 0L, + completed = watchedNow, + defaultOrderIndex = resolvedOrderIndex, + totalCount = resolvedTotalCount, + updatedAtMillis = clock(), + watchedBvids = nextWatched, + episodePositions = nextPositions, + ) + val nextMap = currentMap + (key to updated) + _entries.value = nextMap + writeToDisk(nextMap) + } + } + + /** 清空全部合集与系列观看记录并删除磁盘文件。 */ + suspend fun clearAll() { + rememberedOrders.clear() + lock.withLock { + loaded = true + _entries.value = emptyMap() + writeToDisk(emptyMap()) + } + } + + private suspend fun readFromDisk(): Map = withContext(Dispatchers.IO) { + if (!file.isFile) return@withContext emptyMap() + runCatching { + val catalog = json.decodeFromString(file.readText()) + catalog.items + .filter { it.id > 0L && it.lastBvid.isNotBlank() } + .associateBy { it.key } + }.onFailure { + BiliLog.w("Failed to read collection progress file=${file.name}", it) + }.getOrDefault(emptyMap()) + } + + private suspend fun writeToDisk(entries: Map) = withContext(Dispatchers.IO) { + runCatching { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + if (entries.isEmpty()) { + temp.delete() + file.delete() + return@runCatching + } + val payload = StoredCatalog( + version = CATALOG_VERSION, + items = entries.values.sortedByDescending { it.updatedAtMillis }, + ) + temp.writeText(json.encodeToString(StoredCatalog.serializer(), payload)) + if (!temp.renameTo(file)) { + file.writeText(temp.readText()) + temp.delete() + } + }.onFailure { + BiliLog.w("Failed to write collection progress file=${file.name}", it) + } + } + + @Serializable + private data class StoredCatalog( + val version: Int = CATALOG_VERSION, + val items: List = emptyList(), + ) + + private data class EpisodeOrderKey( + val isSeason: Boolean, + val id: Long, + val bvid: String, + ) + + private data class EpisodeOrderHint( + val defaultOrderIndex: Int?, + val totalCount: Int, + ) + + companion object { + private const val CATALOG_VERSION = 1 + + /** 与 ProgressSession 一致:忽略不足 1 秒的起播位置。 */ + const val MIN_RECORD_POSITION_MILLIS = 1_000L + + /** 达到视频总时长 85% 即视为已看完。 */ + const val WATCHED_THRESHOLD_PERCENT = 85L + } +} + +/** 是否达到 85% 已看阈值。 */ +fun isWatchedByProgress(positionMillis: Long, durationMillis: Long): Boolean = + durationMillis > 0L && + positionMillis >= (durationMillis * CollectionProgressStore.WATCHED_THRESHOLD_PERCENT) / 100L + +/** + * 将列表当前展示顺序下的 0-based 下标换算为默认顺序(非倒序)下的 0-based 下标。 + * 倒序且未知总集数时无法反推,返回 null。 + */ +fun computeDefaultOrderIndex( + displayIndex: Int, + totalCount: Int, + reversed: Boolean, +): Int? { + if (displayIndex < 0) return null + if (!reversed) return displayIndex + if (totalCount <= 0) return null + return (totalCount - 1 - displayIndex).coerceAtLeast(0) +} + +/** + * 根据默认顺序下的 0-based 下标与当前展示方向,计算 `PagedFeed.open()` 应锚定的 1-based 页码。 + */ +fun computeCollectionAnchorPage( + defaultOrderIndex: Int?, + totalCount: Int, + reversed: Boolean, + pageSize: Int = SpaceRepository.COLLECTION_PAGE_SIZE, +): Int { + val idx = defaultOrderIndex ?: return 1 + if (idx < 0 || pageSize <= 0) return 1 + val effectiveIndex = if (reversed) { + if (totalCount <= 0) return 1 + (totalCount - 1 - idx).coerceAtLeast(0) + } else { + idx + } + return effectiveIndex / pageSize + 1 +} + +/** + * 解析当前播放条目归属的合集/系列目标(可同时命中详情里的合集与队列上下文里的系列)。 + * + * 优先级与来源: + * 1. 已缓存的 [VideoDetail](`seasonId > 0`),直接给出 `seasonEpisodes` 的精确默认序号与总数; + * 2. 活帧上下文 [QueueContext.Collection](覆盖系列 `isSeason == false` 与带排序的合集目录); + * 3. 活帧补全后的 [QueueSource](覆盖从归属解析 `fromSeries` / `fromSeason` 进入的场景)。 + */ +fun resolveCollectionTargets( + bvid: String, + cachedDetail: VideoDetail?, + frameContext: QueueContext?, + frameSource: QueueSource?, + sourcePosition: Int?, + sourceTotal: Int?, + detached: Boolean, + fallbackTitle: String = "", +): List { + if (bvid.isBlank()) return emptyList() + val byKey = LinkedHashMap() + val title = cachedDetail?.title?.takeIf { it.isNotBlank() } ?: fallbackTitle + + if (cachedDetail != null && cachedDetail.seasonId > 0L) { + val index = cachedDetail.seasonEpisodes.indexOfFirst { it.bvid == bvid }.takeIf { it >= 0 } + val total = cachedDetail.seasonEpisodes.size + val key = CollectionKey(isSeason = true, id = cachedDetail.seasonId) + byKey[key] = CollectionPlaybackTarget( + isSeason = true, + id = cachedDetail.seasonId, + defaultOrderIndex = index, + totalCount = total, + title = title, + ) + } + + val effectiveTotal = sourceTotal?.takeIf { it > 0 } ?: 0 + val displayIndex = if (!detached && sourcePosition != null && sourcePosition > 0) sourcePosition - 1 else null + + val collectionCtx = frameContext as? QueueContext.Collection + if (collectionCtx != null && collectionCtx.id > 0L) { + val key = CollectionKey(isSeason = collectionCtx.isSeason, id = collectionCtx.id) + val orderIdx = displayIndex?.let { + computeDefaultOrderIndex(it, effectiveTotal, reversed = false) + } + val existing = byKey[key] + byKey[key] = CollectionPlaybackTarget( + isSeason = collectionCtx.isSeason, + id = collectionCtx.id, + defaultOrderIndex = existing?.defaultOrderIndex ?: orderIdx, + totalCount = existing?.totalCount?.takeIf { it > 0 } ?: effectiveTotal, + title = existing?.title?.ifBlank { title } ?: title, + ) + } + + if (frameSource != null && frameSource.id > 0L) { + val key = CollectionKey(isSeason = frameSource.isSeason, id = frameSource.id) + val orderIdx = displayIndex?.let { + computeDefaultOrderIndex(it, effectiveTotal, reversed = false) + } + val existing = byKey[key] + byKey[key] = CollectionPlaybackTarget( + isSeason = frameSource.isSeason, + id = frameSource.id, + defaultOrderIndex = existing?.defaultOrderIndex ?: orderIdx, + totalCount = existing?.totalCount?.takeIf { it > 0 } ?: effectiveTotal, + title = existing?.title?.ifBlank { title } ?: title, + ) + } + + return byKey.values.toList() +} + +/** + * 合并显式起播位置、云端/本地续播位置与一次性合集续播兜底断点。 + * + * - 若调用方显式指定了 [explicitOverrideMillis](如切画质、云端续播提示、帧恢复),直接采用它; + * - 否则当 [fallbackResumeMillis] 有效时,先经 [resumePositionMillis] 做片尾安全裁切(避免跳到片尾之外), + * 再与云端/本地续播点取较大者,确保开启暂停历史或云端未同步时也能精准续播。 + */ +fun resolveEffectiveResumeMillis( + explicitOverrideMillis: Long?, + cloudOrLocalStartMillis: Long, + fallbackResumeMillis: Long?, + durationMillis: Long, + finishedThresholdMillis: Long? = null, +): Long { + if (explicitOverrideMillis != null) return explicitOverrideMillis.coerceAtLeast(0L) + val base = cloudOrLocalStartMillis.coerceAtLeast(0L) + val rawFallback = fallbackResumeMillis?.takeIf { it > 0L } ?: return base + val safeFallback = if (durationMillis > 0L) { + if (finishedThresholdMillis != null) { + resumePositionMillis(rawFallback, durationMillis, finishedThresholdMillis) + } else { + resumePositionMillis(rawFallback, durationMillis) + } + } else { + rawFallback + } + return maxOf(base, safeFallback) +} diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/TvLoginRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/TvLoginRepository.kt index f8825de8..555b7a52 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/TvLoginRepository.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/TvLoginRepository.kt @@ -41,6 +41,7 @@ class TvLoginRepository( private val client: BiliClient, private val settings: SettingsStore, private val fingerprint: DeviceFingerprint, + private val collectionProgressStore: CollectionProgressStore? = null, ) { val credentials: Flow = settings.credentials @@ -109,6 +110,7 @@ class TvLoginRepository( suspend fun logout() { settings.clearCredentials() fingerprint.clearSession() + collectionProgressStore?.clearAll() } /** diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/VideoRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/VideoRepository.kt index 5069336b..f5b91fc2 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/VideoRepository.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/VideoRepository.kt @@ -177,6 +177,9 @@ class VideoRepository(private val client: BiliClient) { /** 正在飞的详情请求,按 bvid 归并。见 [getVideoDetail]。 */ private val detailInFlight = ConcurrentHashMap>() + /** 读取内存缓存中的视频详情(不发起网络请求),供播放层就近获取合集归属与分集序号。 */ + fun cachedVideoDetail(bvid: String): VideoDetail? = detailCache.get(bvid) + /** * 视频详情。**同一条视频的并发请求合并成一次,并在很短的时间内复用结果。** * 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 36792e60..f5c8e0b5 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/db/BilbyDatabase.kt @@ -43,50 +43,18 @@ 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 = 10, + version = 9, 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 02909c85..053b9a59 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/db/Entities.kt @@ -66,36 +66,3 @@ 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/player/PartRequest.kt b/shared/src/commonMain/kotlin/dev/bilby/player/PartRequest.kt index f9698a00..9a4c6671 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/player/PartRequest.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/player/PartRequest.kt @@ -18,26 +18,55 @@ package dev.bilby.player * 写在导航发生之前、读在装载解析时,两处都在主线程,但服务的解析跑在自己的协程上,所以 * 加锁而不是靠时序。 */ +/** + * 打开视频时的一次性起播线索:可选分 P 指名与可选本机续播兜底位置。 + */ +data class PlaybackStartHint( + val cid: Long = 0L, + val fallbackPositionMillis: Long = 0L, +) + class PartRequest { private val lock = Any() private var bvid: String? = null - private var cid: Long = 0 + private var cid: Long = 0L + private var fallbackPositionMillis: Long = 0L /** 记下"这一次要放这条视频的这一 P"。同一时刻只留最后一次,先前没被取走的那条作废。 */ fun request(bvid: String, cid: Long) { + requestResume(bvid = bvid, cid = cid, fallbackPositionMillis = 0L) + } + + /** + * 记下一次性起播分 P 与/或本地续播兜底位置(用于合集「继续观看」在云端进度缺失或落后时精准起播)。 + */ + fun requestResume(bvid: String, cid: Long = 0L, fallbackPositionMillis: Long = 0L) { + val safeCid = cid.coerceAtLeast(0L) + val safePos = fallbackPositionMillis.coerceAtLeast(0L) synchronized(lock) { - this.bvid = bvid.takeIf { cid != 0L } - this.cid = cid + if (bvid.isBlank() || (safeCid == 0L && safePos == 0L)) { + this.bvid = null + this.cid = 0L + this.fallbackPositionMillis = 0L + } else { + this.bvid = bvid + this.cid = safeCid + this.fallbackPositionMillis = safePos + } } } - /** 取走这条视频的指名,没有则 0。**取完即弃**,同一次指名不会生效第二次。 */ - fun consume(bvid: String): Long = synchronized(lock) { - if (this.bvid != bvid) return 0 - val requested = cid + /** 取走这条视频的指名分 P,没有则 0。**取完即弃**,同一次指名不会生效第二次。 */ + fun consume(bvid: String): Long = consumeHint(bvid).cid + + /** 取走这条视频的一次性起播线索(分 P 与续播兜底位置),**取完即弃**。 */ + fun consumeHint(bvid: String): PlaybackStartHint = synchronized(lock) { + if (this.bvid != bvid) return PlaybackStartHint() + val hint = PlaybackStartHint(cid = cid, fallbackPositionMillis = fallbackPositionMillis) this.bvid = null - this.cid = 0 - requested + this.cid = 0L + this.fallbackPositionMillis = 0L + hint } } diff --git a/shared/src/commonMain/kotlin/dev/bilby/player/ProgressSession.kt b/shared/src/commonMain/kotlin/dev/bilby/player/ProgressSession.kt index 08eb27de..2fb1570a 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/player/ProgressSession.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/player/ProgressSession.kt @@ -43,6 +43,11 @@ data class ReportedProgress( class ProgressSession( val aid: Long, val cid: Long, + /** + * 每次有效进度触发上报时同步回调(天然跳过 0 秒起播并融合 PBP 片尾完播判定), + * 供服务层向本地合集进度存储下沉采集。 + */ + private val onProgressRecorded: ((positionMillis: Long, durationMillis: Long, completed: Boolean) -> Unit)? = null, /** * [finished] 为真时发 `played_time=-1`,见 [dev.bilby.data.HeartbeatReporter]。 * @@ -189,6 +194,7 @@ class ProgressSession( report(seconds, completed) { reported = reported?.copy(confirmedSeconds = seconds) } + onProgressRecorded?.invoke(positionMillis.coerceAtLeast(0L), durationMillis, completed) } companion object { diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt index f6694b3e..7387b6ea 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt @@ -1155,44 +1155,6 @@ 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 @@ -3389,6 +3351,7 @@ private fun SettingsPageRoute( onOpenBlacklist = onOpenBlacklist, onOpenExcludedFeed = { onOpenSection(SettingsSection.ExcludedFeed) }, onDanmakusArchiveChange = vm::setDanmakusArchive, + onClearCollectionProgress = vm::clearCollectionProgress, onBack = onBack, ) } @@ -3436,6 +3399,7 @@ private fun rememberSettingsViewModel(container: AppContainer): SettingsViewMode container.historyRepository, container.persistScope, followRepository = container.followRepository, + collectionProgressStore = container.collectionProgressStore, ) } }, @@ -4574,11 +4538,11 @@ private fun CollectionRoute( factory = viewModelFactory { initializer { CollectionViewModel( - key.mid, - key.id, - key.isSeason, - container.spaceRepository, - container.collectionProgressRepository, + mid = key.mid, + id = key.id, + isSeason = key.isSeason, + repository = container.spaceRepository, + progressStore = container.collectionProgressStore, ) } }, @@ -4586,29 +4550,36 @@ private fun CollectionRoute( val state by vm.state.collectAsStateWithLifecycle() CollectionScreen( title = key.name, + isSeason = key.isSeason, state = state, 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, + vm.rememberOrder(item.bvid, index) + onVideoClick(item.bvid, QueueContext.Collection(key.mid, key.id, key.isSeason, key.name, page)) + }, + onResumeClick = { action -> + if (action.cid != 0L || action.fallbackPositionMillis > 0L) { + container.partRequest.requestResume( + bvid = action.bvid, + cid = action.cid, + fallbackPositionMillis = action.fallbackPositionMillis, ) } - onVideoClick(item.bvid, QueueContext.Collection(key.mid, key.id, key.isSeason, key.name, page)) + val loadedIndex = state.items.indexOfFirst { it.bvid == action.bvid } + val anchorPage = if (loadedIndex >= 0) { + loadedIndex / SpaceRepository.COLLECTION_PAGE_SIZE + 1 + } else { + dev.bilby.data.computeCollectionAnchorPage( + defaultOrderIndex = action.defaultOrderIndex, + totalCount = state.total.takeIf { it > 0 } ?: action.totalCount, + reversed = false, + ) + } + onVideoClick(action.bvid, QueueContext.Collection(key.mid, key.id, key.isSeason, key.name, anchorPage)) }, ) } diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt index 9501ff6e..1b1f3eed 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt @@ -67,6 +67,7 @@ import androidx.compose.material.icons.outlined.SwapHoriz import androidx.compose.material.icons.outlined.SwapVert import androidx.compose.material.icons.outlined.ThumbUp import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material.icons.outlined.VideoLibrary import androidx.compose.material.icons.outlined.Wallpaper import androidx.compose.material.icons.outlined.Wifi import androidx.compose.material3.AlertDialog @@ -114,6 +115,7 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll import dev.bilby.stringResource import dev.bilby.AppBuild import dev.bilby.resources.* +import dev.bilby.ui.components.DestructiveConfirmButton import dev.bilby.ui.navigationBarsBottom import dev.bilby.ui.padScaffoldExceptBottom import dev.bilby.data.CodecPreference @@ -1196,8 +1198,10 @@ fun PrivacySettingsPage( onOpenBlacklist: () -> Unit, onOpenExcludedFeed: () -> Unit, onDanmakusArchiveChange: (Boolean) -> Unit, + onClearCollectionProgress: () -> Unit = {}, onBack: (() -> Unit)?, ) { + var confirmingClearCollectionProgress by rememberSaveable { mutableStateOf(false) } SettingsSubPage(stringResource(Res.string.settings_section_privacy), onBack, state.loaded) { SettingsGroup { // 和这一页其余开关不同,它读的是服务端的账号设置,所以读不到是一种真实状态。三档各画 @@ -1234,6 +1238,25 @@ fun PrivacySettingsPage( ) } } + row { position -> + SettingRow( + position = position, + icon = Icons.Outlined.VideoLibrary, + title = stringResource(Res.string.settings_clear_collection_progress), + subtitle = stringResource(Res.string.settings_clear_collection_progress_subtitle), + value = if (state.collectionProgressCount > 0) { + stringResource(Res.string.settings_collection_progress_count, state.collectionProgressCount) + } else { + null + }, + valueAtEnd = true, + onClick = if (state.collectionProgressCount > 0) { + { confirmingClearCollectionProgress = true } + } else { + null + }, + ) + } row { position -> SettingRow( position = position, @@ -1270,6 +1293,27 @@ fun PrivacySettingsPage( } } } + if (confirmingClearCollectionProgress) { + AlertDialog( + onDismissRequest = { confirmingClearCollectionProgress = false }, + title = { Text(stringResource(Res.string.settings_clear_collection_progress)) }, + text = { Text(stringResource(Res.string.settings_clear_collection_progress_message)) }, + confirmButton = { + DestructiveConfirmButton( + text = stringResource(Res.string.action_clear), + onClick = { + confirmingClearCollectionProgress = false + onClearCollectionProgress() + }, + ) + }, + dismissButton = { + TextButton(onClick = { confirmingClearCollectionProgress = false }) { + Text(stringResource(Res.string.action_cancel)) + } + }, + ) + } } /** diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt index 4a52f8b4..a99c966d 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt @@ -4,6 +4,7 @@ import dev.bilby.api.BiliResult import dev.bilby.api.map import dev.bilby.api.toHttpsUrl import dev.bilby.appendDistinctBy +import dev.bilby.data.CollectionProgressStore import dev.bilby.data.FollowOrder import dev.bilby.data.FollowRepository import dev.bilby.data.HistoryRepository @@ -92,6 +93,8 @@ data class SettingsUiState( val nightMode: NightModePrefs = NightModePrefs(), /** 服务端的「暂停记录观看历史」。不是本机偏好,所以有读不到这一档,见 [HistoryPause]。 */ val historyPause: HistoryPause = HistoryPause.Loading, + /** 本机已记录观看进度的合集与系列数量。 */ + val collectionProgressCount: Int = 0, ) /** 夜间模式“添加 UP 主”选择面板的关注列表分页状态。 */ @@ -135,6 +138,7 @@ class SettingsViewModel( private val historyRepository: HistoryRepository, private val persistScope: CoroutineScope, private val followRepository: FollowRepository? = null, + private val collectionProgressStore: CollectionProgressStore? = null, ) : ViewModel() { /** @@ -309,6 +313,17 @@ class SettingsViewModel( _state.update { it.copy(navigationPrefs = prefs) } } } + collectionProgressStore?.let { store -> + viewModelScope.launch { + store.observeCount().collect { count -> + _state.update { it.copy(collectionProgressCount = count) } + } + } + } + } + + fun clearCollectionProgress() { + persist { collectionProgressStore?.clearAll() } } fun clearExcludedFeedMids() { @@ -392,6 +407,7 @@ class SettingsViewModel( fun logout(onDone: () -> Unit) { persist { settings.clearCredentials() + collectionProgressStore?.clearAll() onDone() } } 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 53147f49..34bacad3 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/space/CollectionScreen.kt @@ -1,12 +1,17 @@ package dev.bilby.ui.space +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box 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.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.PlayArrow @@ -17,35 +22,43 @@ 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 import androidx.compose.runtime.Immutable +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp 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.CollectionProgress +import dev.bilby.data.CollectionProgressStore import dev.bilby.data.SpaceRepository import dev.bilby.data.SpaceVideoItem -import dev.bilby.data.db.CollectionProgressEntity +import dev.bilby.data.computeDefaultOrderIndex import dev.bilby.formatDurationMillis +import dev.bilby.parseDurationSeconds import dev.bilby.resources.* import dev.bilby.stringResource import dev.bilby.ui.CaptionDragHeight import dev.bilby.ui.LocalWindowCaption import dev.bilby.ui.components.BilbyTooltip +import dev.bilby.ui.components.MetaSeparator import dev.bilby.ui.components.RefreshBox 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.Dimens import dev.bilby.ui.theme.Spacing +import dev.bilby.ui.theme.interactiveCard import dev.bilby.ui.theme.tabular import dev.bilby.ui.windowDragArea import kotlinx.coroutines.flow.MutableStateFlow @@ -60,14 +73,22 @@ data class CollectionUiState( val items: List = emptyList(), val page: Int = 1, val total: Int = 0, + val progress: CollectionProgress? = null, val loading: Boolean = false, val appending: Boolean = false, val refreshing: Boolean = false, val hasMore: Boolean = true, val error: String? = null, val errorRes: StringResource? = null, - val lastProgress: CollectionProgressEntity? = null, - val watchedBvids: Set = emptySet(), +) + +@Immutable +data class CollectionResumeAction( + val bvid: String, + val cid: Long, + val fallbackPositionMillis: Long, + val defaultOrderIndex: Int?, + val totalCount: Int, ) /** @@ -78,7 +99,7 @@ class CollectionViewModel( private val id: Long, private val isSeason: Boolean, private val repository: SpaceRepository, - private val progressRepository: CollectionProgressRepository? = null, + private val progressStore: CollectionProgressStore? = null, ) : ViewModel() { private val _state = MutableStateFlow(CollectionUiState()) @@ -89,20 +110,28 @@ class CollectionViewModel( init { loadMore() - progressRepository?.let { repo -> + progressStore?.let { store -> 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) } + store.observe(isSeason, id).collect { progress -> + _state.update { it.copy(progress = progress) } } } } } + fun rememberOrder(bvid: String, displayIndex: Int) { + val current = _state.value + val total = current.total.takeIf { it > 0 } ?: current.items.size + val defaultIdx = computeDefaultOrderIndex(displayIndex, total, reversed = false) + progressStore?.rememberEpisodeOrder( + isSeason = isSeason, + id = id, + bvid = bvid, + defaultOrderIndex = defaultIdx, + totalCount = total, + ) + } + fun refresh() { generation++ _state.update { @@ -162,19 +191,32 @@ class CollectionViewModel( @Composable fun CollectionScreen( title: String, + isSeason: Boolean, state: CollectionUiState, onBack: () -> Unit, onLoadMore: () -> Unit, onRefresh: () -> Unit, onVideoClick: (SpaceVideoItem) -> Unit, - onResumeBvid: ((String) -> Unit)? = null, + onResumeClick: ((CollectionResumeAction) -> Unit)? = null, modifier: Modifier = Modifier, ) { val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior() val totalCount = state.total.takeIf { it > 0 } ?: state.items.size - val subtitle = if (totalCount > 0) stringResource(Res.string.collection_total_count, totalCount) else null + val progress = state.progress + val watchedCount = progress?.watchedBvids?.size ?: 0 + val subtitle = buildString { + if (totalCount > 0) append(stringResource(Res.string.collection_total_count, totalCount)) + if (watchedCount > 0) { + if (isNotEmpty()) append(MetaSeparator) + append(stringResource(Res.string.collection_watched_count, watchedCount)) + } + }.takeIf { it.isNotEmpty() } val errorText = state.errorRes?.let { stringResource(it) } ?: state.error + val resumeTarget = remember(progress, state.items, totalCount, isSeason) { + progress?.let { resolveCollectionResumeTarget(it, state.items, isSeason, totalCount) } + } + Scaffold( modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { @@ -234,7 +276,6 @@ fun CollectionScreen( onRefresh = onRefresh, modifier = Modifier.fillMaxSize().padScaffoldExceptBottom(padding), ) { - val progress = state.lastProgress VideoListTab( items = state.items, appending = state.appending, @@ -244,67 +285,208 @@ 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) { + header = if (resumeTarget != null && onResumeClick != null) { { - CollectionContinueBanner( - progress = progress, - onClick = { onResumeBvid(progress.lastBvid) }, - ) + Box( + modifier = Modifier + .fillMaxWidth() + .padding(top = Spacing.Hair, bottom = Spacing.Tight), + ) { + CollectionContinueBanner( + target = resumeTarget, + onClick = { onResumeClick(resumeTarget.action) }, + ) + } } } else { null }, + itemMeta = if (progress != null) { + { item -> collectionItemMeta(item, progress) } + } else { + null + }, + itemProgressFraction = if (progress != null) { + { item -> collectionItemProgressFraction(item, progress) } + } else { + null + }, modifier = Modifier.fillMaxSize(), ) } } } +private enum class ContinueBadgeKind { + InProgress, + NextEpisode, + Finished, +} + +private data class ResolvedContinueTarget( + val title: String, + val badgeKind: ContinueBadgeKind, + val positionMillis: Long, + val action: CollectionResumeAction, +) + +private fun resolveCollectionResumeTarget( + progress: CollectionProgress, + items: List, + isSeason: Boolean, + totalCount: Int, +): ResolvedContinueTarget { + val effectiveTotal = totalCount.takeIf { it > 0 } ?: progress.totalCount + if (!progress.completed) { + return ResolvedContinueTarget( + title = progress.lastTitle.ifBlank { progress.lastBvid }, + badgeKind = ContinueBadgeKind.InProgress, + positionMillis = progress.positionMillis, + action = CollectionResumeAction( + bvid = progress.lastBvid, + cid = progress.lastCid, + fallbackPositionMillis = progress.positionMillis, + defaultOrderIndex = progress.defaultOrderIndex, + totalCount = effectiveTotal, + ), + ) + } + + val lastIdx = items.indexOfFirst { it.bvid == progress.lastBvid } + val nextEpisode = if (lastIdx >= 0) { + if (isSeason) { + items.drop(lastIdx + 1).firstOrNull { it.bvid !in progress.watchedBvids } + } else { + items.take(lastIdx).lastOrNull { it.bvid !in progress.watchedBvids } + } + } else { + null + } + + if (nextEpisode != null) { + val nextIdx = items.indexOfFirst { it.bvid == nextEpisode.bvid } + return ResolvedContinueTarget( + title = nextEpisode.title.ifBlank { nextEpisode.bvid }, + badgeKind = ContinueBadgeKind.NextEpisode, + positionMillis = 0L, + action = CollectionResumeAction( + bvid = nextEpisode.bvid, + cid = 0L, + fallbackPositionMillis = 0L, + defaultOrderIndex = computeDefaultOrderIndex(nextIdx, effectiveTotal, reversed = false), + totalCount = effectiveTotal, + ), + ) + } + + return ResolvedContinueTarget( + title = progress.lastTitle.ifBlank { progress.lastBvid }, + badgeKind = ContinueBadgeKind.Finished, + positionMillis = 0L, + action = CollectionResumeAction( + bvid = progress.lastBvid, + cid = 0L, + fallbackPositionMillis = 0L, + defaultOrderIndex = progress.defaultOrderIndex, + totalCount = effectiveTotal, + ), + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable private fun CollectionContinueBanner( - progress: CollectionProgressEntity, + target: ResolvedContinueTarget, onClick: () -> Unit, ) { - val subtitle = if (progress.lastPositionMillis > 0L) { - stringResource(Res.string.collection_continue_progress, formatDurationMillis(progress.lastPositionMillis)) - } else { - stringResource(Res.string.collection_continue_recent) + val statusDetail = when (target.badgeKind) { + ContinueBadgeKind.InProgress -> if (target.positionMillis > 0L) { + stringResource(Res.string.collection_continue_progress, formatDurationMillis(target.positionMillis)) + } else { + "" + } + + ContinueBadgeKind.NextEpisode -> stringResource(Res.string.collection_continue_next) + ContinueBadgeKind.Finished -> stringResource(Res.string.collection_continue_finished) } - Surface( - onClick = onClick, - shape = MaterialTheme.shapes.large, - color = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + val heading = stringResource(Res.string.collection_continue_watching) + val labelLine = if (statusDetail.isNotEmpty()) "$heading$MetaSeparator$statusDetail" else heading + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.Cozy), modifier = Modifier .fillMaxWidth() - .padding(vertical = Spacing.Tight), + .heightIn(min = Dimens.MinTouchTarget) + .interactiveCard( + shape = MaterialTheme.shapes.large, + baseColor = MaterialTheme.colorScheme.surfaceContainerHigh, + hoverColor = MaterialTheme.colorScheme.surfaceContainerHighest, + ) + .clickable(role = Role.Button, onClick = onClick) + .padding(horizontal = Spacing.Comfortable, vertical = Spacing.Cozy), ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(Spacing.Cozy), - modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Cozy), + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(ContinueIconSize) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primaryContainer), ) { Icon( imageVector = Icons.Filled.PlayArrow, contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } + Column( + verticalArrangement = Arrangement.spacedBy(Spacing.Hair / 2), + modifier = Modifier.weight(1f), + ) { + Text( + text = labelLine, + style = MaterialTheme.typography.labelMedium.tabular, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = target.title, + style = MaterialTheme.typography.bodyLargeEmphasized, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, ) - 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, - ) - } } } } + +@Composable +private fun collectionItemMeta(item: SpaceVideoItem, progress: CollectionProgress): String? { + if (item.bvid in progress.watchedBvids) { + return stringResource(Res.string.history_finished) + } + val episodePos = progress.episodePositions[item.bvid]?.positionMillis + ?: progress.positionMillis.takeIf { item.bvid == progress.lastBvid && !progress.completed } + ?: 0L + if (episodePos > 0L) { + return stringResource(Res.string.history_progress, formatDurationMillis(episodePos)) + } + return null +} + +private fun collectionItemProgressFraction(item: SpaceVideoItem, progress: CollectionProgress): Float? { + if (item.bvid in progress.watchedBvids) return 1f + val ep = progress.episodePositions[item.bvid] + val pos = ep?.positionMillis + ?: progress.positionMillis.takeIf { item.bvid == progress.lastBvid && !progress.completed } + ?: return null + if (pos <= 0L) return null + val durationMillis = ep?.durationMillis?.takeIf { it > 0L } + ?: progress.durationMillis.takeIf { item.bvid == progress.lastBvid && it > 0L } + ?: parseDurationSeconds(item.durationText).takeIf { it > 0L }?.times(1000L) + ?: return null + return (pos.toFloat() / durationMillis.toFloat()).coerceIn(0f, 1f) +} + +private val ContinueIconSize = 36.dp 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 556ff8f1..5d35c088 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/space/SpaceScreen.kt @@ -2341,8 +2341,8 @@ internal fun VideoListTab( onVideoClick: (SpaceVideoItem) -> Unit, modifier: Modifier = Modifier, header: (@Composable () -> Unit)? = null, - lastWatchedBvid: String? = null, - watchedBvids: Set = emptySet(), + itemMeta: (@Composable (SpaceVideoItem) -> String?)? = null, + itemProgressFraction: ((SpaceVideoItem) -> Float?)? = null, @Suppress("UNUSED_PARAMETER") columns: GridCells = GridCells.Fixed(1), ) { val density = LocalDensity.current @@ -2398,14 +2398,10 @@ internal fun VideoListTab( } }, ) { item -> - 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) { + val typeBadge = chargingBadgeText(item.chargingOnly) + val metaText = itemMeta?.invoke(item) + val progressFraction = itemProgressFraction?.invoke(item) + val rowUi = remember(item, typeBadge, metaText, progressFraction) { VideoRowUi( title = item.title, coverUrl = item.coverUrl, @@ -2413,7 +2409,9 @@ internal fun VideoListTab( dateText = formatDate(item.publishedAtEpochSeconds), playText = item.playCountText, danmakuText = item.danmakuCountText, + meta = metaText, typeBadge = typeBadge, + progressFraction = progressFraction, ) } ContextMenuBox( diff --git a/shared/src/commonTest/kotlin/dev/bilby/data/CollectionProgressStoreTest.kt b/shared/src/commonTest/kotlin/dev/bilby/data/CollectionProgressStoreTest.kt new file mode 100644 index 00000000..dc2f2b98 --- /dev/null +++ b/shared/src/commonTest/kotlin/dev/bilby/data/CollectionProgressStoreTest.kt @@ -0,0 +1,387 @@ +package dev.bilby.data + +import dev.bilby.player.PartRequest +import dev.bilby.player.PlaybackStartHint +import java.io.File +import java.nio.file.Files +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class CollectionProgressStoreTest { + + private lateinit var tempDir: File + private lateinit var storeFile: File + private val json = Json { + ignoreUnknownKeys = true + coerceInputValues = true + explicitNulls = false + encodeDefaults = true + } + + @Before + fun setUp() { + tempDir = Files.createTempDirectory("bilby-collection-progress-test").toFile() + storeFile = File(tempDir, "collection-progress.json") + } + + @After + fun tearDown() { + tempDir.deleteRecursively() + } + + @Test + fun `持久化读写跨实例恢复`() = runTest { + var now = 1_700_000_000_000L + val store1 = CollectionProgressStore(storeFile, json, clock = { now }) + + store1.recordProgress( + isSeason = true, + id = 42L, + bvid = "BV1ep01", + cid = 1001L, + title = "第一集", + positionMillis = 120_000L, + durationMillis = 600_000L, + completed = false, + defaultOrderIndex = 3, + totalCount = 120, + ) + now += 10_000L + store1.recordProgress( + isSeason = false, + id = 42L, + bvid = "BV1series01", + cid = 2002L, + title = "系列条目", + positionMillis = 520_000L, + durationMillis = 600_000L, + completed = false, + defaultOrderIndex = 65, + totalCount = 90, + ) + + assertTrue("独立 JSON 文件必须落盘", storeFile.isFile) + + val store2 = CollectionProgressStore(storeFile, json) + val season = store2.observe(isSeason = true, id = 42L).first() + val series = store2.observe(isSeason = false, id = 42L).first() + + assertNotNull(season) + assertEquals("BV1ep01", season?.lastBvid) + assertEquals(1001L, season?.lastCid) + assertEquals("第一集", season?.lastTitle) + assertEquals(120_000L, season?.positionMillis) + assertEquals(3, season?.defaultOrderIndex) + assertEquals(120, season?.totalCount) + assertFalse(season?.completed ?: true) + assertTrue(season?.watchedBvids?.isEmpty() == true) + assertEquals(120_000L, season?.episodePositions?.get("BV1ep01")?.positionMillis) + + assertNotNull(series) + assertEquals("BV1series01", series?.lastBvid) + assertEquals(65, series?.defaultOrderIndex) + assertEquals(90, series?.totalCount) + assertTrue(series?.completed == true) + assertEquals(setOf("BV1series01"), series?.watchedBvids) + assertNull("完播后从进行中映射移除", series?.episodePositions?.get("BV1series01")) + } + + @Test + fun `低于 85 百分比不标已看,达到 85 百分比或完播才加入 watchedBvids`() = runTest { + val store = CollectionProgressStore(storeFile, json) + + // 84% (84_000 / 100_000): 不标已看 + store.recordProgress( + isSeason = true, + id = 10L, + bvid = "BV1a", + cid = 1L, + title = "A", + positionMillis = 84_000L, + durationMillis = 100_000L, + completed = false, + ) + val at84 = store.get(true, 10L)!! + assertFalse(at84.completed) + assertFalse("BV1a" in at84.watchedBvids) + + // 恰好 85% (85_000 / 100_000): 标已看 + store.recordProgress( + isSeason = true, + id = 10L, + bvid = "BV1a", + cid = 1L, + title = "A", + positionMillis = 85_000L, + durationMillis = 100_000L, + completed = false, + ) + val at85 = store.get(true, 10L)!! + assertTrue(at85.completed) + assertTrue("BV1a" in at85.watchedBvids) + + // 时长未知但 ProgressSession 明确报 completed=true(如 PBP 片尾或连播切条): 标已看 + store.recordProgress( + isSeason = true, + id = 10L, + bvid = "BV1b", + cid = 2L, + title = "B", + positionMillis = 30_000L, + durationMillis = 0L, + completed = true, + ) + val byCompleted = store.get(true, 10L)!! + assertTrue(byCompleted.completed) + assertEquals(setOf("BV1a", "BV1b"), byCompleted.watchedBvids) + } + + @Test + fun `第 0 秒起播与不足 1 秒的位置一律忽略`() = runTest { + val store = CollectionProgressStore(storeFile, json) + + store.recordProgress( + isSeason = true, + id = 99L, + bvid = "BV1zero", + cid = 1L, + title = "刚点开", + positionMillis = 0L, + durationMillis = 300_000L, + completed = false, + ) + store.recordProgress( + isSeason = true, + id = 99L, + bvid = "BV1zero", + cid = 1L, + title = "不足一秒", + positionMillis = 999L, + durationMillis = 300_000L, + completed = false, + ) + + assertNull("0 秒与不足 1 秒不应产生记录", store.get(true, 99L)) + assertFalse("未写入有效进度时不应创建文件", storeFile.exists()) + } + + @Test + fun `暂停历史开关开启时不记录`() = runTest { + var paused = true + val store = CollectionProgressStore(storeFile, json, isHistoryPaused = { paused }) + + store.recordProgress( + isSeason = true, + id = 77L, + bvid = "BV1paused", + cid = 1L, + title = "暂停期间观看", + positionMillis = 90_000L, + durationMillis = 100_000L, + completed = true, + ) + assertNull("开启暂停历史时必须拦截写入", store.get(true, 77L)) + assertFalse(storeFile.exists()) + + paused = false + store.recordProgress( + isSeason = true, + id = 77L, + bvid = "BV1resumed", + cid = 2L, + title = "恢复后观看", + positionMillis = 15_000L, + durationMillis = 100_000L, + completed = false, + ) + assertEquals("BV1resumed", store.get(true, 77L)?.lastBvid) + } + + @Test + fun `清空记录同时清空内存与磁盘文件`() = runTest { + val store = CollectionProgressStore(storeFile, json) + store.rememberEpisodeOrder(isSeason = false, id = 5L, bvid = "BV1x", defaultOrderIndex = 70, totalCount = 100) + store.recordProgress( + isSeason = false, + id = 5L, + bvid = "BV1x", + cid = 1L, + title = "测试", + positionMillis = 10_000L, + durationMillis = 60_000L, + completed = false, + ) + assertEquals(70, store.get(false, 5L)?.defaultOrderIndex) + assertEquals(1, store.observeCount().first()) + assertTrue(storeFile.isFile) + + store.clearAll() + + assertNull(store.get(false, 5L)) + assertEquals(0, store.observeCount().first()) + assertFalse("清空后磁盘文件应被删除", storeFile.exists()) + } + + @Test + fun `跨深页与正倒序 anchorPage 换算准确`() { + val pageSize = SpaceRepository.COLLECTION_PAGE_SIZE // 30 + + // 默认顺序:第 0 集 -> 第 1 页,第 29 集 -> 第 1 页,第 30 集 -> 第 2 页,第 85 集 -> 第 3 页,第 95 集 -> 第 4 页 + assertEquals(1, computeCollectionAnchorPage(0, totalCount = 100, reversed = false, pageSize = pageSize)) + assertEquals(1, computeCollectionAnchorPage(29, totalCount = 100, reversed = false, pageSize = pageSize)) + assertEquals(2, computeCollectionAnchorPage(30, totalCount = 100, reversed = false, pageSize = pageSize)) + assertEquals(3, computeCollectionAnchorPage(85, totalCount = 100, reversed = false, pageSize = pageSize)) + assertEquals(4, computeCollectionAnchorPage(95, totalCount = 100, reversed = false, pageSize = pageSize)) + + // 倒序(total = 100): + // defaultOrderIndex = 99 -> reversedIndex = 0 -> page 1 + // defaultOrderIndex = 70 -> reversedIndex = 29 -> page 1 + // defaultOrderIndex = 69 -> reversedIndex = 30 -> page 2 + // defaultOrderIndex = 5 -> reversedIndex = 94 -> page 4 + // defaultOrderIndex = 0 -> reversedIndex = 99 -> page 4 + assertEquals(1, computeCollectionAnchorPage(99, totalCount = 100, reversed = true, pageSize = pageSize)) + assertEquals(1, computeCollectionAnchorPage(70, totalCount = 100, reversed = true, pageSize = pageSize)) + assertEquals(2, computeCollectionAnchorPage(69, totalCount = 100, reversed = true, pageSize = pageSize)) + assertEquals(4, computeCollectionAnchorPage(5, totalCount = 100, reversed = true, pageSize = pageSize)) + assertEquals(4, computeCollectionAnchorPage(0, totalCount = 100, reversed = true, pageSize = pageSize)) + + // 未知序号或倒序未知总数时安全退回第 1 页 + assertEquals(1, computeCollectionAnchorPage(null, totalCount = 100, reversed = false, pageSize = pageSize)) + assertEquals(1, computeCollectionAnchorPage(50, totalCount = 0, reversed = true, pageSize = pageSize)) + + // 反向换算往返一致 + val defaultIdx = computeDefaultOrderIndex(displayIndex = 94, totalCount = 100, reversed = true) + assertEquals(5, defaultIdx) + assertEquals(4, computeCollectionAnchorPage(defaultIdx, totalCount = 100, reversed = true, pageSize = pageSize)) + } + + @Test + fun `resolveCollectionTargets 覆盖详情合集与倒序系列队列`() { + val episodes = (0 until 75).map { idx -> + SeasonEpisode( + cid = idx + 1L, + aid = idx + 100L, + bvid = "BV1ep$idx", + title = "第 $idx 集", + coverUrl = "", + durationSeconds = 300L, + ) + } + val detail = VideoDetail( + bvid = "BV1ep68", + aid = 168L, + cid = 69L, + title = "第 68 集", + description = "", + descriptionSpans = emptyList(), + coverUrl = "", + durationSeconds = 300L, + publishedAtEpochSeconds = 0L, + up = VideoUp(1L, "UP", ""), + staff = emptyList(), + stat = VideoStat(0, 0, 0, 0, 0, 0, 0), + maxCoins = 2, + pages = listOf(VideoPart(69L, 1, "P1", 300L)), + seasonTitle = "长合集", + seasonId = 500L, + seasonMid = 1L, + seasonEpisodes = episodes, + ) + + val seasonTargets = resolveCollectionTargets( + bvid = "BV1ep68", + cachedDetail = detail, + frameContext = QueueContext.Collection(mid = 1L, id = 500L, isSeason = true, name = "长合集", page = 1), + frameSource = QueueSource(mid = 1L, id = 500L, isSeason = true, name = "长合集"), + sourcePosition = 7, + sourceTotal = 75, + detached = false, + ) + assertEquals(1, seasonTargets.size) + assertEquals(true, seasonTargets[0].isSeason) + assertEquals(500L, seasonTargets[0].id) + assertEquals(68, seasonTargets[0].defaultOrderIndex) + assertEquals(75, seasonTargets[0].totalCount) + + // 系列播放:总计 100 集,当前在列表第 10 位(1-based)-> 默认顺序下标 9 + val seriesTargets = resolveCollectionTargets( + bvid = "BV1ser", + cachedDetail = null, + frameContext = QueueContext.Collection(mid = 2L, id = 888L, isSeason = false, name = "系列", page = 1), + frameSource = QueueSource(mid = 2L, id = 888L, isSeason = false, name = "系列"), + sourcePosition = 10, + sourceTotal = 100, + detached = false, + fallbackTitle = "系列第 10 条", + ) + assertEquals(1, seriesTargets.size) + assertEquals(false, seriesTargets[0].isSeason) + assertEquals(888L, seriesTargets[0].id) + assertEquals(9, seriesTargets[0].defaultOrderIndex) + assertEquals(100, seriesTargets[0].totalCount) + assertEquals("系列第 10 条", seriesTargets[0].title) + } + + @Test + fun `本地续播兜底在云端缺失或落后时生效且防越界`() { + // 云端为 0 时,本地兜底 12:34 生效 + assertEquals( + 754_000L, + resolveEffectiveResumeMillis( + explicitOverrideMillis = null, + cloudOrLocalStartMillis = 0L, + fallbackResumeMillis = 754_000L, + durationMillis = 1_200_000L, + ), + ) + // 云端比本地更新时,取云端 + assertEquals( + 900_000L, + resolveEffectiveResumeMillis( + explicitOverrideMillis = null, + cloudOrLocalStartMillis = 900_000L, + fallbackResumeMillis = 754_000L, + durationMillis = 1_200_000L, + ), + ) + // 显式覆写(切清晰度等)优先 + assertEquals( + 100_000L, + resolveEffectiveResumeMillis( + explicitOverrideMillis = 100_000L, + cloudOrLocalStartMillis = 900_000L, + fallbackResumeMillis = 754_000L, + durationMillis = 1_200_000L, + ), + ) + // 兜底位置落在片尾完播窗口内时安全归零,绝不跳到片尾之外 + assertEquals( + 0L, + resolveEffectiveResumeMillis( + explicitOverrideMillis = null, + cloudOrLocalStartMillis = 0L, + fallbackResumeMillis = 1_195_000L, + durationMillis = 1_200_000L, + ), + ) + } + + @Test + fun `PartRequest 一次性起播断点消费后清空`() { + val req = PartRequest() + req.requestResume(bvid = "BV1abc", cid = 321L, fallbackPositionMillis = 754_000L) + + assertEquals(PlaybackStartHint(), req.consumeHint("BV1other")) + assertEquals(PlaybackStartHint(cid = 321L, fallbackPositionMillis = 754_000L), req.consumeHint("BV1abc")) + assertEquals(PlaybackStartHint(), req.consumeHint("BV1abc")) + } +} diff --git a/shared/src/desktopMain/kotlin/dev/bilby/player/DesktopPlaybackHost.kt b/shared/src/desktopMain/kotlin/dev/bilby/player/DesktopPlaybackHost.kt index 6896ab9d..b9e62043 100644 --- a/shared/src/desktopMain/kotlin/dev/bilby/player/DesktopPlaybackHost.kt +++ b/shared/src/desktopMain/kotlin/dev/bilby/player/DesktopPlaybackHost.kt @@ -5,6 +5,8 @@ import dev.bilby.BiliLog import dev.bilby.BvidCodec import dev.bilby.api.BiliConstants import dev.bilby.api.BiliResult +import dev.bilby.data.CollectionKey +import dev.bilby.data.CollectionPlaybackTarget import dev.bilby.data.OpenedQueue import dev.bilby.data.PlayEndMode import dev.bilby.data.PlayInfo @@ -14,6 +16,8 @@ import dev.bilby.data.QueueOrder import dev.bilby.data.QueueSource import dev.bilby.data.SettingsStore import dev.bilby.data.decodeQueueContext +import dev.bilby.data.resolveCollectionTargets +import dev.bilby.data.resolveEffectiveResumeMillis import dev.bilby.data.resumeAtMillisFor import dev.bilby.elapsedRealtimeMillis import dev.bilby.getString @@ -114,6 +118,7 @@ class DesktopPlaybackHost( private var loadJob: Job? = null private var tickJob: Job? = null private var progressSession: ProgressSession? = null + private var historyPauseProbeStarted = false /** * 当前装进 mpv 的是哪一条(mediaId)、哪一 P。取流回来、打开之前置上,见 [loadCurrent]。 @@ -485,25 +490,33 @@ class DesktopPlaybackHost( return } // 指名在入口取走,理由见 [PartRequest]。 - val requestedCid = container().partRequest.consume(bvid) + val startHint = container().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 = decodeQueueContext(command.queueContext) ?: 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) } /** 回到了活帧那一页。不续播,理由见 Android 的 resumeFrame;云端进度在这里核对。 */ - private fun resumeFrame(frame: Frame, bvid: String, requestedCid: Long) { + private fun resumeFrame(frame: Frame, bvid: String, requestedCid: Long, fallbackStartMillis: Long?) { val current = queue.current?.bvid if (current != null) { - 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?.observedPositionMillis ?: 0L) < 1_000L) { + handle?.seekTo(fallbackStartMillis) + } + } reconcileCloudProgress(current) } publishState() @@ -560,14 +573,27 @@ class DesktopPlaybackHost( } /** 新的一帧:先装一份只有这条的临时队列并立刻起播,来源由 [enrichFrame] 在后台补上。 */ - 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 frameOrderTouched = false queue.order = defaultOrder val temporary = QueueItem(bvid = bvid, title = "", upName = "", coverUrl = "", durationSeconds = 0) - val kept = replaceQueue(listOf(temporary), 0, requestedCid, startMillis = null, playWhenReady = true) + val kept = replaceQueue( + items = listOf(temporary), + index = 0, + requestedCid = requestedCid, + startMillis = null, + playWhenReady = true, + fallbackStartMillis = fallbackStartMillis, + ) 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?.observedPositionMillis ?: 0L) < 1_000L) { + handle?.seekTo(fallbackStartMillis) + } + } enrichFrame(frame, bvid) } @@ -583,11 +609,17 @@ class DesktopPlaybackHost( requestedCid: Long, startMillis: Long?, playWhenReady: Boolean, + fallbackStartMillis: Long? = null, ): Boolean { val current = queue.current if (liveRoom != null || current == null || current.bvid != items[index].bvid) { setQueue(items, index) - loadCurrent(playWhenReady = playWhenReady, requestedCid = requestedCid, startMillis = startMillis) + loadCurrent( + playWhenReady = playWhenReady, + requestedCid = requestedCid, + startMillis = startMillis, + fallbackStartMillis = fallbackStartMillis, + ) return false } queue.set(items.toMutableList().also { it[index] = current }, index) @@ -982,7 +1014,12 @@ class DesktopPlaybackHost( * 旧的会话先定格关掉;同一条重来时旧的流留在 mpv 里接着放,到新的流打开的那一刻才换下, * 切清晰度因此没有静音的空档。 */ - private fun loadCurrent(playWhenReady: Boolean, requestedCid: Long = 0L, startMillis: Long? = null) { + private fun loadCurrent( + playWhenReady: Boolean, + requestedCid: Long = 0L, + startMillis: Long? = null, + fallbackStartMillis: Long? = null, + ) { val player = player ?: return val item = queue.current ?: return loadJob?.cancel() @@ -995,7 +1032,11 @@ class DesktopPlaybackHost( publishState() val live = liveRoom loadJob = scope.launch { - val resolved = if (live != null) resolveLive(live) else resolveVideo(item.bvid, requestedCid, startMillis) + val resolved = if (live != null) { + resolveLive(live) + } else { + resolveVideo(item.bvid, requestedCid, startMillis, fallbackStartMillis) + } if (resolved == null) { pendingPlayWhenReady = null return@launch @@ -1049,7 +1090,12 @@ class DesktopPlaybackHost( ) /** 视频那一支:放哪一 P 交给 [LoadResolver],取流的画质按 Android 的同一套次序。失败时返回 null。 */ - private suspend fun resolveVideo(bvid: String, requestedCid: Long, startMillis: Long?): Resolved? { + private suspend fun resolveVideo( + bvid: String, + requestedCid: Long, + startMillis: Long?, + fallbackStartMillis: Long?, + ): Resolved? { val app = container() val cid = when (val plan = loadResolver.resolve(bvid, requestedCid)) { is LoadPlan.Online -> plan.cid @@ -1079,7 +1125,13 @@ class DesktopPlaybackHost( return Resolved( source = StreamSource(info.streams.videoUrl, info.streams.audioUrl), cid = cid, - startMillis = startMillis ?: info.resumeAtMillisFor(cid), + startMillis = resolveEffectiveResumeMillis( + explicitOverrideMillis = startMillis, + cloudOrLocalStartMillis = info.resumeAtMillisFor(cid), + fallbackResumeMillis = fallbackStartMillis, + durationMillis = info.durationMillis, + finishedThresholdMillis = info.finishedThresholdMillis, + ), playInfo = info, // 实际选中的那一档,不是请求的那一档,见 Android 的 resolveOnlineStream。 quality = info.streams.qualityId, @@ -1361,7 +1413,73 @@ class DesktopPlaybackHost( if (aid <= 0) return val app = container() val reporter = app.heartbeatReporter - val session = ProgressSession(aid, cid) { playedTimeSeconds, finished, onConfirmed -> + if (app.historyRepository.lastKnownPaused == null && !historyPauseProbeStarted) { + historyPauseProbeStarted = true + scope.launch { app.historyRepository.isPaused() } + } + fun resolveTargets(): List { + val frame = liveFrame + val detached = frame?.detached == true + val currentItem = queue.current?.takeIf { it.bvid == bvid } + val pos = if (frame != null && !detached) queue.sourcePosition else null + val total = if (frame != null && !detached) queue.sourceTotal else null + return resolveCollectionTargets( + bvid = bvid, + cachedDetail = app.videoRepository.cachedVideoDetail(bvid), + frameContext = frame?.context, + frameSource = frame?.source, + sourcePosition = pos, + sourceTotal = total, + detached = detached, + fallbackTitle = currentItem?.title.orEmpty(), + ) + } + var cachedTargets = resolveTargets() + val fallbackDurationMillis = playInfo?.durationMillis?.takeIf { it > 0L } + ?: queue.current?.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 + app.persistScope.launch { + targets.forEach { target -> + app.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 -> reporter.report(aid, cid, bvid, playedTimeSeconds, finished) { scope.launch { onConfirmed() } } } progressSession = session