1 Commits
Author SHA1 Message Date
loveuer a9f38d7359 feat: release v0.1.3 with video favorites 2026-11-05 14:52:31 +08:00
28 changed files with 1492 additions and 50 deletions

No files matched your search

+11
View File
@@ -1,5 +1,16 @@
# Changelog # Changelog
## v0.1.3 — 2026-11-05
新增播放中收藏与登录后的「我的收藏」页签。
- 登录后新增「我的收藏」页签,支持切换官方账号的收藏夹、分页浏览及复用详情播放。
- 播放器新增「收藏 / 已收藏」操作,可选择多个已有收藏夹或移出收藏;只有确认「保存」才提交修改。
- 收藏请求绑定账号会话,退出或切换账号清空收藏状态并拒绝迟到结果;保存结果不确定时先重新加载,避免盲目重试。
- 完善播放器顶部操作的左右导航、收藏菜单返回焦点,以及收藏页的收藏夹 / 视频 / 页签返回层级。
- 当前支持视频稿件收藏,不含追番 / 追剧或收藏夹管理;真实账号同步仍待实测。
- 构建、Android Lint、96 项 JVM 测试和 21 项常规模拟器设备测试通过;应用版本号为 `0.1.3`,`versionCode` 递增为 `4`。
## v0.1.2 — 2026-11-04 ## v0.1.2 — 2026-11-04
新增播放清晰度选择;电视实机验证待进行。 新增播放清晰度选择;电视实机验证待进行。
+11 -5
View File
@@ -1,8 +1,8 @@
# bulubulu # bulubulu
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索和播放,把交互留给遥控器。 一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索、收藏和播放,把交互留给遥控器。
当前版本:**v0.1.2**。新增清晰度选择,电视实机验证待进行,详见 [验证记录](docs/VALIDATION.md)。 当前版本:**v0.1.3**。新增播放中收藏和登录后的「我的收藏」页签;真实账号收藏同步待实测,详见 [验证记录](docs/VALIDATION.md)。
![推荐页面](docs/screenshots/recommendation.png) ![推荐页面](docs/screenshots/recommendation.png)
@@ -18,6 +18,8 @@
- 视频详情、投稿分 P、番剧选集。 - 视频详情、投稿分 P、番剧选集。
- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。 - 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。
- 播放中手动选择清晰度,保留播放进度和暂停状态;切换失败时尝试恢复原档位。 - 播放中手动选择清晰度,保留播放进度和暂停状态;切换失败时尝试恢复原档位。
- 登录后出现「我的收藏」页签,按收藏夹浏览视频,支持分页、刷新和播放。
- 播放中把视频保存到一个或多个已有收藏夹,或取消收藏;勾选只是草稿,按「保存」才同步到 B 站账号。
- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。 - 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。
- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。 - 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。
@@ -28,18 +30,21 @@
| 场景 | 操作 | | 场景 | 操作 |
| --- | --- | | --- | --- |
| 首页 / 选集 | 方向键移动,确认键选择 | | 首页 / 选集 | 方向键移动,确认键选择 |
| 首页内容区 | 返回键把焦点移回当前页签 | | 首页内容区 | 返回键把焦点移回当前页签;收藏页先返回收藏夹,再返回页签 |
| 搜索 | 确认输入框打开系统键盘,键盘搜索键或页面「搜索」提交;向下进入分类和结果 | | 搜索 | 确认输入框打开系统键盘,键盘搜索键或页面「搜索」提交;向下进入分类和结果 |
| 搜索结果 | 确认打开详情;返回键先收起键盘,再返回分类,最后退出搜索 | | 搜索结果 | 确认打开详情;返回键先收起键盘,再返回分类,最后退出搜索 |
| 弹窗 | 返回键关闭 | | 弹窗 | 返回键关闭 |
| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 | | 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 |
| 播放中 | 上键聚焦「清晰度」,确认打开菜单;下键回到画面,返回退出播放器 | | 播放中 | 上键聚焦「清晰度」,左右切换顶部操作,确认打开菜单;下键回到画面,返回退出播放器 |
| 清晰度菜单 | 上下选择,确认切换;返回关闭菜单 | | 清晰度菜单 | 上下选择,确认切换;返回关闭菜单 |
| 收藏菜单 | 上下选择收藏夹,确认勾选 / 取消,移到「保存」并确认提交;返回关闭并放弃草稿 |
在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。 在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。
清晰度菜单只列出官方接口本次实际返回的 H.264 档位,可选项取决于视频和账号权限。默认选择不高于普通 1080P 的最佳档位;手动切换会短暂重新缓冲,新视频重新使用默认选择,不自动按网速调整清晰度。 清晰度菜单只列出官方接口本次实际返回的 H.264 档位,可选项取决于视频和账号权限。默认选择不高于普通 1080P 的最佳档位;手动切换会短暂重新缓冲,新视频重新使用默认选择,不自动按网速调整清晰度。
收藏接入官方账号收藏夹,当前支持视频稿件收藏;番剧 / 电影的「追番 / 追剧」属于另一套接口,尚未实现。新建、重命名或删除收藏夹请在哔哩哔哩客户端操作;失效视频和暂不支持的收藏类型会被过滤。网络中断导致保存结果不确定时,需要重新加载状态再操作。
## 构建 ## 构建
需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。 需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。
@@ -83,9 +88,10 @@ Cookie 通过 Android Keystore 的 AES-GCM 密钥加密,保存到禁止备份
- `core/Models.kt`:共享数据模型与可展示的错误。 - `core/Models.kt`:共享数据模型与可展示的错误。
- `data/`:官方接口、WBI 签名、扫码会话与加密存储。 - `data/`:官方接口、WBI 签名、扫码会话与加密存储。
- `search/`:临时搜索状态、取消与迟到响应隔离、跨页去重。 - `search/`:临时搜索状态、取消与迟到响应隔离、跨页去重。
- `favorites/`:账号收藏库、收藏夹草稿、显式保存与迟到响应隔离。
- `ui/`:首页、搜索、登录与选集弹窗、电视焦点组件。 - `ui/`:首页、搜索、登录与选集弹窗、电视焦点组件。
- `player/`:Media3 播放、备选 CDN 和遥控器控制。 - `player/`:Media3 播放、备选 CDN 和遥控器控制。
- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。 - `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。
- `docs/`:接口说明、设计说明和真实运行截图。 - `docs/`:接口说明、设计说明和真实运行截图。
接口与权限限制见 [CONTENT_API.md](docs/CONTENT_API.md),搜索见 [SEARCH_API.md](docs/SEARCH_API.md),登录实现见 [AUTH.md](docs/AUTH.md),界面说明见 [UI.md](docs/UI.md)。验证结果记录在 [VALIDATION.md](docs/VALIDATION.md)。 接口与权限限制见 [CONTENT_API.md](docs/CONTENT_API.md),搜索见 [SEARCH_API.md](docs/SEARCH_API.md),收藏见 [FAVORITES_API.md](docs/FAVORITES_API.md),登录实现见 [AUTH.md](docs/AUTH.md),界面说明见 [UI.md](docs/UI.md)。验证结果记录在 [VALIDATION.md](docs/VALIDATION.md)。
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "dev.bulubulu.tv" applicationId = "dev.bulubulu.tv"
minSdk = 23 minSdk = 23
targetSdk = 34 targetSdk = 34
versionCode = 3 versionCode = 4
versionName = "0.1.2" versionName = "0.1.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
} }
buildFeatures { compose = true; buildConfig = true } buildFeatures { compose = true; buildConfig = true }
@@ -0,0 +1,56 @@
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
package dev.bulubulu.tv.player
import android.view.KeyEvent
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.platform.app.InstrumentationRegistry
import dev.bulubulu.tv.core.*
import dev.bulubulu.tv.favorites.FavoriteActionState
import dev.bulubulu.tv.ui.BulubuluTheme
import dev.bulubulu.tv.ui.FavoriteDialog
import java.net.ServerSocket
import org.junit.Rule
import org.junit.Test
class PlayerFavoriteNavigationTest {
@get:Rule val compose = createComposeRule()
@Test fun remoteMovesBetweenPlayerActionsAndRestoresFocusAfterFavoriteMenu() {
// A local socket keeps playback buffering; this test never accesses an external CDN.
ServerSocket(0).use { socket ->
val source = PlaybackSource("播放器收藏操作", PlaybackStream("https://127.0.0.1:" + socket.localPort + "/video"))
val favorite = mutableStateOf(FavoriteActionState(
aid = 100, loggedIn = true, folders = listOf(FavoriteFolder(11, "默认收藏夹", 0)), selectedIds = setOf(11),
))
compose.setContent { BulubuluTheme {
PlayerScreen(source, {}, {}, favorite.value, { favorite.value = favorite.value.copy(visible = true) })
if (favorite.value.visible) {
FavoriteDialog(favorite.value, {}, {}, {}, { favorite.value = favorite.value.copy(visible = false) })
}
} }
compose.mainClock.advanceTimeBy(350)
compose.onNodeWithTag("quality_button").key(Key.DirectionUp)
awaitFocus("quality_button")
compose.onNodeWithTag("quality_button").key(Key.DirectionRight)
awaitFocus("favorite_button")
compose.onNodeWithTag("favorite_button").key(Key.DirectionLeft)
awaitFocus("quality_button")
compose.onNodeWithTag("quality_button").key(Key.DirectionRight).key(Key.DirectionCenter)
compose.mainClock.advanceTimeBy(350)
awaitFocus("favorite_option_11")
InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
compose.mainClock.advanceTimeBy(350)
awaitFocus("favorite_button")
}
}
private fun SemanticsNodeInteraction.key(key: Key) = performKeyInput { keyDown(key); keyUp(key) }
private fun awaitFocus(tag: String) = compose.waitUntil(5_000) {
compose.onAllNodesWithTag(tag).fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
}
}
@@ -0,0 +1,152 @@
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
package dev.bulubulu.tv.ui
import android.view.KeyEvent
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.semantics.SemanticsProperties
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.platform.app.InstrumentationRegistry
import dev.bulubulu.tv.core.*
import dev.bulubulu.tv.favorites.FavoriteActionState
import dev.bulubulu.tv.favorites.FavoriteLibraryState
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
class FavoriteNavigationTest {
@get:Rule val compose = createComposeRule()
private val folders = listOf(FavoriteFolder(11, "默认收藏夹", 2), FavoriteFolder(22, "教程", 1))
@Test fun favoritesTabOnlyAppearsAfterLoginAndIsRemoteReachable() {
val state = mutableStateOf(HomeUiState(loading = false, hasMore = false))
compose.setContent { BulubuluTheme {
BulubuluHome(
state = state.value, onTabSelected = { state.value = state.value.copy(selectedTab = it) },
onItemSelected = {}, onLoadMore = {}, onRefresh = {}, onLogin = {}, onLogout = {},
favorites = FavoriteLibraryState(folders = folders, selectedFolderId = 11),
)
} }
compose.mainClock.advanceTimeBy(300)
compose.onNodeWithTag("tab_FAVORITES").assertDoesNotExist()
compose.runOnIdle { state.value = state.value.copy(account = Account(123, "测试用户")) }
compose.onNodeWithTag("tab_RECOMMEND").key(Key.DirectionRight).key(Key.DirectionRight).key(Key.DirectionRight).key(Key.DirectionCenter)
compose.runOnIdle { assertEquals(ContentTab.FAVORITES, state.value.selectedTab) }
awaitFocus("tab_FAVORITES")
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
awaitFocus("favorite_folder_11")
}
@Test fun favoriteVideosOpenAndBackReturnsThroughFolderToTab() {
val favorite = mutableStateOf(FavoriteLibraryState(
folders = folders, selectedFolderId = 11,
items = listOf(VideoItem("av1", "收藏视频 0", "", aid = 1)),
))
val state = mutableStateOf(HomeUiState(
selectedTab = ContentTab.FAVORITES, account = Account(123, "测试用户"), loading = false,
))
var selected: VideoItem? = null
compose.setContent { BulubuluTheme {
BulubuluHome(
state.value, {}, { selected = it }, {}, {}, {}, {},
favorites = favorite.value,
onFavoriteFolderSelected = { favorite.value = favorite.value.copy(selectedFolderId = it) },
)
} }
compose.mainClock.advanceTimeBy(300)
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
awaitFocus("favorite_folder_11")
compose.onNodeWithTag("favorite_folder_11").key(Key.DirectionDown)
compose.waitUntil(5_000) {
compose.onAllNodesWithText("收藏视频 0").fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
}
compose.onNodeWithText("收藏视频 0").key(Key.DirectionCenter)
compose.runOnIdle { assertEquals("av1", selected?.id) }
back(); awaitFocus("favorite_folder_11")
back(); awaitFocus("tab_FAVORITES")
}
@Test fun selectedFolderOutsideViewportScrollsIntoFocus() {
compose.setContent { BulubuluTheme {
BulubuluHome(
HomeUiState(selectedTab = ContentTab.FAVORITES, account = Account(123, "测试用户"), loading = false),
{}, {}, {}, {}, {}, {},
favorites = FavoriteLibraryState(
folders = (1L..20L).map { FavoriteFolder(it, "收藏夹 $it", 0) }, selectedFolderId = 20,
),
)
} }
compose.mainClock.advanceTimeBy(300)
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
awaitFocus("favorite_folder_20")
compose.onNodeWithTag("favorite_folder_20").assertIsDisplayed()
back(); awaitFocus("tab_FAVORITES")
}
@Test fun folderChoicesAreDraftsUntilRemoteConfirmsSave() {
val state = mutableStateOf(FavoriteActionState(
aid = 100, loggedIn = true, visible = true, folders = folders, selectedIds = setOf(11),
))
var saved = false
compose.setContent { BulubuluTheme {
FavoriteDialog(
state.value,
{ id -> state.value = state.value.copy(selectedIds = state.value.selectedIds.let { if (id in it) it - id else it + id }) },
{ saved = true }, {}, {},
)
} }
compose.mainClock.advanceTimeBy(400)
awaitFocus("favorite_option_11")
compose.onNodeWithTag("favorite_option_11").key(Key.DirectionCenter).key(Key.DirectionDown)
awaitFocus("favorite_option_22")
compose.onNodeWithTag("favorite_option_22").key(Key.DirectionCenter)
compose.runOnIdle { assertFalse(saved); assertEquals(setOf(22L), state.value.selectedIds) }
compose.onNodeWithTag("favorite_option_22").key(Key.DirectionDown)
awaitFocus("favorite_save")
compose.onNodeWithTag("favorite_save").key(Key.DirectionCenter)
compose.runOnIdle { assertTrue(saved) }
}
@Test fun savingPreventsDuplicateWritesButBackCanDismiss() {
var dismissed = false
compose.setContent { BulubuluTheme {
FavoriteDialog(
FavoriteActionState(visible = true, saving = true, folders = folders, selectedIds = setOf(11)),
{}, {}, {}, { dismissed = true },
)
} }
compose.mainClock.advanceTimeBy(350)
awaitFocus("favorite_close")
compose.onNodeWithTag("favorite_option_11").assertIsNotEnabled()
compose.onNodeWithTag("favorite_save").assertIsNotEnabled()
back()
compose.runOnIdle { assertTrue(dismissed) }
}
@Test fun longFolderListScrollsToSelectionAndUncertainResultRequiresReload() {
val state = mutableStateOf(FavoriteActionState(
visible = true, folders = (1L..15L).map { FavoriteFolder(it, "收藏夹 $it", 0) }, selectedIds = setOf(15),
))
var reloaded = false
compose.setContent { BulubuluTheme {
FavoriteDialog(state.value, {}, {}, { reloaded = true }, {})
} }
compose.mainClock.advanceTimeBy(450)
awaitFocus("favorite_option_15")
compose.onNodeWithTag("favorite_option_15").assertIsDisplayed()
compose.runOnIdle { state.value = state.value.copy(needsReload = true, error = "结果尚未确认") }
compose.mainClock.advanceTimeBy(250)
awaitFocus("favorite_reload")
compose.onNodeWithTag("favorite_save").assertDoesNotExist()
compose.onNodeWithTag("favorite_reload").key(Key.DirectionCenter)
compose.runOnIdle { assertTrue(reloaded) }
}
private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
private fun SemanticsNodeInteraction.key(key: Key) = performKeyInput { keyDown(key); keyUp(key) }
private fun awaitFocus(tag: String) = compose.waitUntil(5_000) {
compose.onAllNodesWithTag(tag).fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
}
}
@@ -14,6 +14,9 @@ import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode import dev.bulubulu.tv.core.VideoEpisode
import dev.bulubulu.tv.core.VideoItem import dev.bulubulu.tv.core.VideoItem
import dev.bulubulu.tv.core.SearchCategory import dev.bulubulu.tv.core.SearchCategory
import dev.bulubulu.tv.core.Account
import dev.bulubulu.tv.favorites.FavoriteLibraryController
import dev.bulubulu.tv.favorites.FavoriteActionController
import dev.bulubulu.tv.search.SearchController import dev.bulubulu.tv.search.SearchController
import dev.bulubulu.tv.ui.HomeUiState import dev.bulubulu.tv.ui.HomeUiState
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
@@ -55,6 +58,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val notice = _notice.asStateFlow() val notice = _notice.asStateFlow()
private val searchController = SearchController(viewModelScope, graph.search) private val searchController = SearchController(viewModelScope, graph.search)
val search = searchController.state val search = searchController.state
private val libraryController = FavoriteLibraryController(viewModelScope, graph.favorites)
val favoriteLibrary = libraryController.state
private val favoriteController = FavoriteActionController(
viewModelScope, graph.favorites, libraryController::refreshIfOpened, ::showNotice,
)
val favoriteAction = favoriteController.state
private data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?) private data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?)
private val feeds = mutableMapOf<ContentTab, CachedFeed>() private val feeds = mutableMapOf<ContentTab, CachedFeed>()
@@ -65,12 +74,13 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private var accountJob: Job? = null private var accountJob: Job? = null
private var logoutJob: Job? = null private var logoutJob: Job? = null
private var selectedItem: VideoItem? = null private var selectedItem: VideoItem? = null
private var feedGeneration = 0L
init { init {
accountJob = viewModelScope.launch { accountJob = viewModelScope.launch {
try { try {
val account = graph.auth.currentAccount() val account = graph.auth.currentAccount()
_home.update { it.copy(account = account) } applyAccount(account)
} catch (error: Exception) { } catch (error: Exception) {
error.rethrowCancellation() error.rethrowCancellation()
showNotice("登录状态暂时无法验证,已保留本地登录信息") showNotice("登录状态暂时无法验证,已保留本地登录信息")
@@ -81,6 +91,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
fun selectTab(tab: ContentTab) { fun selectTab(tab: ContentTab) {
if (_home.value.authBusy) return if (_home.value.authBusy) return
if (tab == ContentTab.FAVORITES && _home.value.account == null) return
if (tab == _home.value.selectedTab) return if (tab == _home.value.selectedTab) return
loadTab(tab) loadTab(tab)
} }
@@ -91,6 +102,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private fun loadTab(tab: ContentTab, force: Boolean = false) { private fun loadTab(tab: ContentTab, force: Boolean = false) {
feedJob?.cancel() feedJob?.cancel()
val request = ++feedGeneration
if (tab == ContentTab.FAVORITES) {
_home.update { it.copy(selectedTab = tab, items = emptyList(), loading = false, loadingMore = false, error = null, hasMore = false) }
libraryController.refresh()
return
}
val cached = feeds[tab].takeUnless { force } val cached = feeds[tab].takeUnless { force }
_home.update { _home.update {
it.copy( it.copy(
@@ -106,12 +123,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
feedJob = viewModelScope.launch { feedJob = viewModelScope.launch {
try { try {
val result = graph.content.loadFeed(tab) val result = graph.content.loadFeed(tab)
if (request != feedGeneration) return@launch
feeds[tab] = CachedFeed(result.items.distinctBy(VideoItem::id), result.nextPage) feeds[tab] = CachedFeed(result.items.distinctBy(VideoItem::id), result.nextPage)
_home.update { _home.update {
it.copy(items = feeds.getValue(tab).items, loading = false, hasMore = result.nextPage != null) it.copy(items = feeds.getValue(tab).items, loading = false, hasMore = result.nextPage != null)
} }
} catch (error: Exception) { } catch (error: Exception) {
error.rethrowCancellation() error.rethrowCancellation()
if (request != feedGeneration) return@launch
_home.update { it.copy(loading = false, error = userMessage(error)) } _home.update { it.copy(loading = false, error = userMessage(error)) }
} }
} }
@@ -120,11 +139,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
fun loadMore() { fun loadMore() {
val current = _home.value val current = _home.value
if (current.loading || current.loadingMore || current.authBusy) return if (current.loading || current.loadingMore || current.authBusy) return
if (current.selectedTab == ContentTab.FAVORITES) { libraryController.loadMore(); return }
val nextPage = feeds[current.selectedTab]?.nextPage ?: return val nextPage = feeds[current.selectedTab]?.nextPage ?: return
_home.update { it.copy(loadingMore = true, error = null) } _home.update { it.copy(loadingMore = true, error = null) }
val request = feedGeneration
feedJob = viewModelScope.launch { feedJob = viewModelScope.launch {
try { try {
val result = graph.content.loadFeed(current.selectedTab, nextPage) val result = graph.content.loadFeed(current.selectedTab, nextPage)
if (request != feedGeneration) return@launch
val merged = (current.items + result.items).distinctBy(VideoItem::id) val merged = (current.items + result.items).distinctBy(VideoItem::id)
// A repeated backend page must not leave an endless "load more" loop. // A repeated backend page must not leave an endless "load more" loop.
val following = result.nextPage.takeIf { merged.size > current.items.size } val following = result.nextPage.takeIf { merged.size > current.items.size }
@@ -132,6 +154,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
_home.update { it.copy(items = merged, loadingMore = false, hasMore = following != null) } _home.update { it.copy(items = merged, loadingMore = false, hasMore = following != null) }
} catch (error: Exception) { } catch (error: Exception) {
error.rethrowCancellation() error.rethrowCancellation()
if (request != feedGeneration) return@launch
_home.update { it.copy(loadingMore = false, error = userMessage(error)) } _home.update { it.copy(loadingMore = false, error = userMessage(error)) }
} }
} }
@@ -161,7 +184,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
_login.update { it.copy(status = status) } _login.update { it.copy(status = status) }
when (status) { when (status) {
is QrLoginStatus.Success -> { is QrLoginStatus.Success -> {
_home.update { it.copy(account = status.account) } applyAccount(status.account)
feeds.clear() feeds.clear()
_login.value = LoginUiState() _login.value = LoginUiState()
refresh() refresh()
@@ -203,8 +226,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
closePlayer() closePlayer()
closeSearch() closeSearch()
feedJob?.cancel() feedJob?.cancel()
feedGeneration++
feeds.clear() feeds.clear()
_home.update { it.copy(account = null, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) } applyAccount(null)
_home.update { it.copy(selectedTab = ContentTab.RECOMMEND, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
logoutJob = viewModelScope.launch { logoutJob = viewModelScope.launch {
try { try {
graph.auth.logout() graph.auth.logout()
@@ -257,6 +282,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
detailsJob = viewModelScope.launch { detailsJob = viewModelScope.launch {
try { try {
val source = graph.content.resolvePlayback(episode) val source = graph.content.resolvePlayback(episode)
favoriteController.setVideo(episode.aid)
val heading = _details.value.details?.title.orEmpty() val heading = _details.value.details?.title.orEmpty()
_playback.value = if (heading.isNotBlank() && heading != source.title) { _playback.value = if (heading.isNotBlank() && heading != source.title) {
source.copy(title = "$heading · ${source.title}") source.copy(title = "$heading · ${source.title}")
@@ -269,7 +295,19 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
fun closePlayer() { _playback.value = null } fun closePlayer() { favoriteController.setVideo(null); _playback.value = null }
fun selectFavoriteFolder(id: Long) = libraryController.selectFolder(id)
fun openFavorite() = favoriteController.open()
fun closeFavorite() = favoriteController.close()
fun toggleFavoriteFolder(id: Long) = favoriteController.toggle(id)
fun saveFavorite() = favoriteController.save()
private fun applyAccount(account: Account?) {
libraryController.setAccount(account?.uid)
favoriteController.setAccount(account?.uid)
_home.update { it.copy(account = account) }
}
fun openSearch() { fun openSearch() {
if (!_home.value.authBusy) searchController.open() if (!_home.value.authBusy) searchController.open()
@@ -6,6 +6,7 @@ import dev.bulubulu.tv.data.BiliHttpClient
import dev.bulubulu.tv.data.ContentRepository import dev.bulubulu.tv.data.ContentRepository
import dev.bulubulu.tv.data.SessionStore import dev.bulubulu.tv.data.SessionStore
import dev.bulubulu.tv.data.SearchRepository import dev.bulubulu.tv.data.SearchRepository
import dev.bulubulu.tv.data.FavoriteRepository
class BulubuluApplication : Application() { class BulubuluApplication : Application() {
val sessionStore by lazy { SessionStore(this) } val sessionStore by lazy { SessionStore(this) }
@@ -13,4 +14,5 @@ class BulubuluApplication : Application() {
val auth by lazy { AuthRepository(http, sessionStore) } val auth by lazy { AuthRepository(http, sessionStore) }
val content by lazy { ContentRepository(http) } val content by lazy { ContentRepository(http) }
val search by lazy { SearchRepository(http) } val search by lazy { SearchRepository(http) }
val favorites by lazy { FavoriteRepository(http) }
} }
@@ -29,6 +29,7 @@ import dev.bulubulu.tv.ui.BulubuluTheme
import dev.bulubulu.tv.ui.DetailsDialog import dev.bulubulu.tv.ui.DetailsDialog
import dev.bulubulu.tv.ui.LoginDialog import dev.bulubulu.tv.ui.LoginDialog
import dev.bulubulu.tv.ui.SearchScreen import dev.bulubulu.tv.ui.SearchScreen
import dev.bulubulu.tv.ui.FavoriteDialog
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private val model: AppViewModel by viewModels() private val model: AppViewModel by viewModels()
@@ -47,6 +48,8 @@ class MainActivity : ComponentActivity() {
val playback by model.playback.collectAsStateWithLifecycle() val playback by model.playback.collectAsStateWithLifecycle()
val notice by model.notice.collectAsStateWithLifecycle() val notice by model.notice.collectAsStateWithLifecycle()
val search by model.search.collectAsStateWithLifecycle() val search by model.search.collectAsStateWithLifecycle()
val favoriteLibrary by model.favoriteLibrary.collectAsStateWithLifecycle()
val favoriteAction by model.favoriteAction.collectAsStateWithLifecycle()
var focusRestoreKey by remember { mutableIntStateOf(0) } var focusRestoreKey by remember { mutableIntStateOf(0) }
var hadOverlay by remember { mutableStateOf(false) } var hadOverlay by remember { mutableStateOf(false) }
var searchFocusRestoreKey by remember { mutableIntStateOf(0) } var searchFocusRestoreKey by remember { mutableIntStateOf(0) }
@@ -73,6 +76,8 @@ class MainActivity : ComponentActivity() {
focusRestoreKey = focusRestoreKey, focusRestoreKey = focusRestoreKey,
active = !overlay, active = !overlay,
onSearch = model::openSearch, onSearch = model::openSearch,
favorites = favoriteLibrary,
onFavoriteFolderSelected = model::selectFavoriteFolder,
) )
if (search.visible) { if (search.visible) {
SearchScreen( SearchScreen(
@@ -95,7 +100,10 @@ class MainActivity : ComponentActivity() {
if (details.visible) { if (details.visible) {
DetailsDialog(details.details, details.loading, details.error, model::play, model::retryDetails, model::dismissDetails) DetailsDialog(details.details, details.loading, details.error, model::play, model::retryDetails, model::dismissDetails)
} }
playback?.let { PlayerScreen(it, model::closePlayer, model::playbackError) } playback?.let { PlayerScreen(it, model::closePlayer, model::playbackError, favoriteAction, model::openFavorite) }
if (favoriteAction.visible && playback != null) {
FavoriteDialog(favoriteAction, model::toggleFavoriteFolder, model::saveFavorite, model::openFavorite, model::closeFavorite)
}
notice?.let { message -> notice?.let { message ->
Surface( Surface(
modifier = Modifier.align(Alignment.BottomCenter).padding(24.dp), modifier = Modifier.align(Alignment.BottomCenter).padding(24.dp),
@@ -0,0 +1,17 @@
package dev.bulubulu.tv.core
data class FavoriteFolder(
val id: Long,
val title: String,
val mediaCount: Int,
val containsVideo: Boolean = false,
)
data class FavoritePage(val items: List<VideoItem>, val nextPage: Int?)
interface FavoriteDataSource {
suspend fun folders(uid: Long, aid: Long? = null): List<FavoriteFolder>
suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage
suspend fun isFavorite(uid: Long, aid: Long): Boolean
suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>)
}
@@ -1,7 +1,7 @@
package dev.bulubulu.tv.core package dev.bulubulu.tv.core
enum class ContentTab(val title: String) { enum class ContentTab(val title: String) {
RECOMMEND("推荐"), MOVIE("电影"), BANGUMI("番剧") RECOMMEND("推荐"), MOVIE("电影"), BANGUMI("番剧"), FAVORITES("我的收藏")
} }
data class Account(val uid: Long, val name: String, val avatarUrl: String = "") data class Account(val uid: Long, val name: String, val avatarUrl: String = "")
@@ -22,6 +22,8 @@ import dev.bulubulu.tv.core.ClientException
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.coroutines.resumeWithException import kotlin.coroutines.resumeWithException
internal data class AccountRequestSession(val epoch: Long, val csrf: String?)
/** Host/path/expiry checks are shared by persistence and actual network requests. */ /** Host/path/expiry checks are shared by persistence and actual network requests. */
internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJar { internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJar {
private var epoch = 0L private var epoch = 0L
@@ -29,6 +31,27 @@ internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJa
@Synchronized @Synchronized
fun currentEpoch(): Long = epoch fun currentEpoch(): Long = epoch
@Synchronized
fun requestSession(url: HttpUrl, expectedEpoch: Long? = null): Pair<Long, List<Cookie>> {
if (expectedEpoch != null && expectedEpoch != epoch) {
// OkHttp worker callbacks require IOException for interceptor failures.
throw IOException("登录状态已变化,请重新操作")
}
return epoch to loadForRequest(url)
}
@Synchronized
fun accountSession(uid: Long, requireCsrf: Boolean): AccountRequestSession {
val scoped = loadForRequest("https://api.bilibili.com/".toHttpUrlOrNull()!!)
if (uid <= 0 || scoped.none { it.name == "DedeUserID" && it.value == uid.toString() } ||
scoped.none { it.name == "SESSDATA" && it.value.isNotBlank() }) {
throw ClientException("请重新扫码登录后使用收藏")
}
val csrf = scoped.firstOrNull { it.name == "bili_jct" }?.value?.takeIf { it.isNotBlank() }
if (requireCsrf && csrf == null) throw ClientException("登录验证已失效,请重新扫码登录")
return AccountRequestSession(epoch, csrf)
}
@Synchronized @Synchronized
fun clear() { fun clear() {
epoch++ epoch++
@@ -100,8 +123,9 @@ class BiliHttpClient(storage: SessionCookieStore) {
// The epoch also prevents an in-flight login response restoring cookies after logout. // The epoch also prevents an in-flight login response restoring cookies after logout.
.addNetworkInterceptor { chain -> .addNetworkInterceptor { chain ->
val request = chain.request() val request = chain.request()
val epoch = cookies.currentEpoch() val (epoch, scopedCookies) = cookies.requestSession(
val scopedCookies = cookies.loadForRequest(request.url) request.url, request.tag(AccountRequestSession::class.java)?.epoch,
)
val builder = request.newBuilder().removeHeader("Cookie") val builder = request.newBuilder().removeHeader("Cookie")
if (scopedCookies.isNotEmpty()) { if (scopedCookies.isNotEmpty()) {
builder.header("Cookie", scopedCookies.joinToString("; ") { "${it.name}=${it.value}" }) builder.header("Cookie", scopedCookies.joinToString("; ") { "${it.name}=${it.value}" })
@@ -125,18 +149,30 @@ class BiliHttpClient(storage: SessionCookieStore) {
url: String, url: String,
params: Map<String, String> = emptyMap(), params: Map<String, String> = emptyMap(),
allowedApiCodes: Set<Int> = emptySet(), allowedApiCodes: Set<Int> = emptySet(),
): JSONObject = getJsonForSession(url, params, allowedApiCodes, null)
private suspend fun getJsonForSession(
url: String, params: Map<String, String>, allowedApiCodes: Set<Int>, session: AccountRequestSession?,
): JSONObject { ): JSONObject {
val target = officialUrl(url).newBuilder().apply { val target = officialUrl(url).newBuilder().apply {
params.forEach { (key, value) -> setQueryParameter(key, value) } params.forEach { (key, value) -> setQueryParameter(key, value) }
}.build() }.build()
return requestJson(Request.Builder().url(target).get().build(), allowedApiCodes) return requestJson(Request.Builder().url(target).tag(AccountRequestSession::class.java, session).get().build(), allowedApiCodes)
} }
suspend fun postFormJson(url: String, params: Map<String, String>): JSONObject { internal suspend fun getAccountJson(url: String, params: Map<String, String>, uid: Long): JSONObject =
getJsonForSession(url, params, emptySet(), cookies.accountSession(uid, requireCsrf = false))
internal fun accountRequestSession(uid: Long): AccountRequestSession = cookies.accountSession(uid, requireCsrf = true)
suspend fun postFormJson(url: String, params: Map<String, String>): JSONObject =
postFormJson(url, params, null)
internal suspend fun postFormJson(url: String, params: Map<String, String>, session: AccountRequestSession?): JSONObject {
val body = FormBody.Builder().apply { val body = FormBody.Builder().apply {
params.forEach { (key, value) -> add(key, value) } params.forEach { (key, value) -> add(key, value) }
}.build() }.build()
return requestJson(Request.Builder().url(officialUrl(url)).post(body).build(), emptySet()) return requestJson(Request.Builder().url(officialUrl(url)).tag(AccountRequestSession::class.java, session).post(body).build(), emptySet())
} }
/** Obtain the ordinary first-party browser cookie required by official search. */ /** Obtain the ordinary first-party browser cookie required by official search. */
@@ -173,7 +209,11 @@ class BiliHttpClient(storage: SessionCookieStore) {
private suspend fun requestJson(request: Request, allowedApiCodes: Set<Int>): JSONObject = private suspend fun requestJson(request: Request, allowedApiCodes: Set<Int>): JSONObject =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
client.newCall(request).awaitResponse().use { response -> // A form's CSRF value and account-specific requests must never follow a redirect.
val transport = if (request.method == "POST" || request.tag(AccountRequestSession::class.java) != null) {
client.newBuilder().followRedirects(false).retryOnConnectionFailure(false).build()
} else client
transport.newCall(request).awaitResponse().use { response ->
if (!response.isSuccessful) { if (!response.isSuccessful) {
val message = when (response.code) { val message = when (response.code) {
412 -> "请求被哔哩哔哩风控拦截,请稍后重试或切换正常网络" 412 -> "请求被哔哩哔哩风控拦截,请稍后重试或切换正常网络"
@@ -25,6 +25,7 @@ class ContentRepository(private val http: BiliHttpClient) {
ContentTab.RECOMMEND -> recommendations(page) ContentTab.RECOMMEND -> recommendations(page)
ContentTab.MOVIE -> seasonIndex(seasonType = 2, page = page) ContentTab.MOVIE -> seasonIndex(seasonType = 2, page = page)
ContentTab.BANGUMI -> seasonIndex(seasonType = 1, page = page) ContentTab.BANGUMI -> seasonIndex(seasonType = 1, page = page)
ContentTab.FAVORITES -> throw ClientException("请登录后打开我的收藏")
} }
} }
@@ -0,0 +1,135 @@
package dev.bulubulu.tv.data
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.core.FavoriteDataSource
import dev.bulubulu.tv.core.FavoriteFolder
import dev.bulubulu.tv.core.FavoritePage
import dev.bulubulu.tv.core.VideoItem
import org.json.JSONArray
import org.json.JSONObject
/** Account-bound official favorites; only an explicit Save issues a mutation. */
class FavoriteRepository(private val http: BiliHttpClient) : FavoriteDataSource {
override suspend fun folders(uid: Long, aid: Long?): List<FavoriteFolder> {
val params = mutableMapOf("up_mid" to uid.toString(), "type" to "2", "web_location" to "333.1387")
if (aid != null) {
require(aid > 0)
params += mapOf("rid" to aid.toString(), "type" to "2")
}
val response = http.getAccountJson("$API/x/v3/fav/folder/created/list-all", params, uid)
if (response.has("data") && response.isNull("data")) {
// The endpoint can return data:null to anonymous/expired sessions too.
val nav = http.getAccountJson("$API/x/web-interface/nav", emptyMap(), uid).optJSONObject("data")
if (nav?.optBoolean("isLogin") != true || nav.optLong("mid") != uid) {
throw BiliApiException(-101, "登录已失效,请重新扫码登录后查看收藏")
}
}
return FavoriteJson.folders(response, uid, aid != null)
}
override suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage {
require(folderId > 0 && page in 1..FavoriteJson.MAX_PAGE)
return FavoriteJson.videos(http.getAccountJson(
"$API/x/v3/fav/resource/list",
mapOf("media_id" to folderId.toString(), "pn" to page.toString(), "ps" to "20", "order" to "mtime", "platform" to "web", "type" to "0", "tid" to "0", "web_location" to "333.1387"),
uid,
), page)
}
override suspend fun isFavorite(uid: Long, aid: Long): Boolean {
require(aid > 0)
return FavoriteJson.status(http.getAccountJson("$API/x/v2/fav/video/favoured", mapOf("aid" to aid.toString()), uid))
}
override suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>) {
require(aid > 0 && (add + remove).all { it > 0 } && add.intersect(remove).isEmpty())
if (add.isEmpty() && remove.isEmpty()) return
val session = http.accountRequestSession(uid)
val response = http.postFormJson(
"$API/x/v3/fav/resource/deal",
mapOf(
"rid" to aid.toString(), "type" to "2",
"add_media_ids" to add.sorted().joinToString(","),
"del_media_ids" to remove.sorted().joinToString(","),
"csrf" to requireNotNull(session.csrf), "platform" to "web",
),
session,
)
FavoriteJson.requireSuccess(response)
}
private companion object { const val API = "https://api.bilibili.com" }
}
internal object FavoriteJson {
const val MAX_PAGE = 1000
fun requireSuccess(root: JSONObject) {
val code = root.longValue("code") ?: throw malformed()
if (code != 0L) throw BiliApiException(code.toInt(), "收藏操作未成功,请稍后重试($code)")
}
fun folders(root: JSONObject, uid: Long, membership: Boolean): List<FavoriteFolder> {
requireSuccess(root)
// The official API returns data:null for an account with no visible folders.
if (root.has("data") && root.isNull("data")) return emptyList()
val data = root.optJSONObject("data") ?: throw malformed()
val raw = data.optJSONArray("list")
if (raw == null && data.longValue("count") == 0L) return emptyList()
if (raw == null) throw malformed()
return raw.objects().map { folder ->
val id = folder.longValue("id")?.takeIf { it > 0 } ?: throw malformed()
val owner = folder.longValue("mid")
if (owner != null && owner != uid) throw ClientException("收藏夹账号不匹配,请重新登录")
val title = SearchJson.plainText(folder.optString("title")).takeIf { it.isNotBlank() } ?: throw malformed()
val included = folder.flag("fav_state")
if (membership && included == null) throw ClientException("收藏夹状态不完整,请重新打开后重试")
FavoriteFolder(id, title, folder.optInt("media_count").coerceAtLeast(0), included == true)
}.distinctBy { it.id }
}
fun status(root: JSONObject): Boolean {
requireSuccess(root)
return root.optJSONObject("data")?.flag("favoured") ?: throw malformed()
}
fun videos(root: JSONObject, page: Int): FavoritePage {
require(page in 1..MAX_PAGE)
requireSuccess(root)
val data = root.optJSONObject("data") ?: throw malformed()
val hasMore = data.flag("has_more") ?: throw malformed()
val raw = data.optJSONArray("medias")
if (raw == null && hasMore) throw malformed()
if (raw == null && data.optJSONObject("info")?.longValue("media_count") != 0L) throw malformed()
val items = raw.objects().mapNotNull { item ->
if (item.optInt("type") != 2 || item.optInt("attr") and 9 != 0) return@mapNotNull null
val aid = item.longValue("id")?.takeIf { it > 0 } ?: return@mapNotNull null
val title = SearchJson.plainText(item.optString("title")).takeIf { it.isNotBlank() } ?: return@mapNotNull null
val bvid = item.optString("bvid").takeIf { it.matches(Regex("BV[0-9A-Za-z]+")) }
val owner = SearchJson.plainText(item.optJSONObject("upper")?.optString("name").orEmpty())
val duration = item.longValue("duration")?.let { SearchJson.duration(it.toString()) }.orEmpty()
VideoItem(
id = "av$aid", title = title, coverUrl = ContentJson.secureUrl(item.optString("cover")),
subtitle = listOf(owner, duration).filter { it.isNotBlank() }.joinToString(" · "),
aid = aid, bvid = bvid,
)
}.distinctBy { it.id }
return FavoritePage(items, if (hasMore && raw != null && raw.length() > 0 && page < MAX_PAGE) page + 1 else null)
}
private fun JSONArray?.objects(): List<JSONObject> =
if (this == null) emptyList() else (0 until length()).map { optJSONObject(it) ?: throw malformed() }
private fun JSONObject.longValue(key: String): Long? = when (val value = opt(key)) {
is Byte, is Short, is Int, is Long -> (value as Number).toLong()
is String -> value.toLongOrNull()
else -> null
}
private fun JSONObject.flag(key: String): Boolean? = when (val value = opt(key)) {
is Boolean -> value
0, 0L, "0" -> false
1, 1L, "1" -> true
else -> null
}
private fun malformed() = ClientException("B 站收藏数据不完整,请稍后重试")
}
@@ -0,0 +1,135 @@
package dev.bulubulu.tv.favorites
import dev.bulubulu.tv.core.FavoriteDataSource
import dev.bulubulu.tv.core.FavoriteFolder
import dev.bulubulu.tv.userMessage
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class FavoriteActionState(
val aid: Long? = null,
val loggedIn: Boolean = false,
val favorited: Boolean? = null,
val visible: Boolean = false,
val folders: List<FavoriteFolder> = emptyList(),
val selectedIds: Set<Long> = emptySet(),
val loading: Boolean = false,
val saving: Boolean = false,
val needsReload: Boolean = false,
val error: String? = null,
)
class FavoriteActionController(
private val scope: CoroutineScope,
private val repository: FavoriteDataSource,
private val onChanged: () -> Unit,
private val notice: (String) -> Unit,
) {
private val _state = MutableStateFlow(FavoriteActionState())
val state = _state.asStateFlow()
private var uid: Long? = null
private var generation = 0L
private var job: Job? = null
fun setAccount(value: Long?) {
if (uid == value) return
uid = value
reset(_state.value.aid)
}
fun setVideo(aid: Long?) { reset(aid?.takeIf { it > 0 }) }
private fun reset(aid: Long?) {
cancel()
_state.value = FavoriteActionState(aid = aid, loggedIn = uid != null)
readStatus()
}
private fun readStatus() {
val account = uid ?: return
val aid = _state.value.aid ?: return
val request = generation
job = scope.launch {
try {
val value = repository.isFavorite(account, aid)
if (request == generation) _state.update { it.copy(favorited = value) }
} catch (error: Exception) {
if (error is CancellationException) throw error
// A failed background status read never pretends the video is uncollected.
}
}
}
fun open() {
val account = uid ?: run { notice("请先返回首页扫码登录后收藏"); return }
val aid = _state.value.aid ?: run { notice("暂不支持收藏这类内容"); return }
if (_state.value.saving || _state.value.loading) return
cancel()
val request = generation
_state.update { it.copy(visible = true, loading = true, error = null, needsReload = false, folders = emptyList(), selectedIds = emptySet()) }
job = scope.launch {
try {
val folders = repository.folders(account, aid)
if (request != generation) return@launch
val current = folders.filter { it.containsVideo }.map { it.id }.toSet()
// Draft only: a new video defaults to the first folder; nothing is written until Save.
val selected = current.ifEmpty { folders.firstOrNull()?.let { setOf(it.id) }.orEmpty() }
_state.update { it.copy(folders = folders, selectedIds = selected, favorited = current.isNotEmpty(), loading = false) }
} catch (error: Exception) {
if (error is CancellationException) throw error
if (request == generation) _state.update { it.copy(loading = false, needsReload = true, error = userMessage(error)) }
}
}
}
fun toggle(id: Long) {
val current = _state.value
if (!current.visible || current.loading || current.saving || current.needsReload || current.folders.none { it.id == id }) return
_state.update { it.copy(selectedIds = if (id in it.selectedIds) it.selectedIds - id else it.selectedIds + id) }
}
fun save() {
val account = uid ?: return
val current = _state.value
val aid = current.aid ?: return
if (!current.visible || current.loading || current.saving || current.needsReload || current.folders.isEmpty()) return
val original = current.folders.filter { it.containsVideo }.map { it.id }.toSet()
val add = current.selectedIds - original
val remove = original - current.selectedIds
if (add.isEmpty() && remove.isEmpty()) { close(); return }
val request = generation
_state.update { it.copy(saving = true, error = null) }
job = scope.launch {
try {
repository.update(account, aid, add, remove)
if (request != generation) return@launch
_state.update { it.copy(visible = false, saving = false, favorited = current.selectedIds.isNotEmpty()) }
onChanged()
notice(if (current.selectedIds.isEmpty()) "已取消收藏" else "已更新收藏")
} catch (error: Exception) {
if (error is CancellationException) throw error
if (request == generation) {
_state.update { it.copy(
saving = false, needsReload = true, favorited = null,
error = "未能确认收藏结果,请重新加载后重试。\n" + userMessage(error),
) }
onChanged()
}
}
}
}
fun close() {
val uncertain = _state.value.saving || _state.value.needsReload
cancel()
_state.update { it.copy(visible = false, loading = false, saving = false, needsReload = false, error = null) }
if (uncertain) { _state.update { it.copy(favorited = null) }; onChanged(); readStatus() }
}
private fun cancel() { generation++; job?.cancel(); job = null }
}
@@ -0,0 +1,115 @@
package dev.bulubulu.tv.favorites
import dev.bulubulu.tv.core.FavoriteDataSource
import dev.bulubulu.tv.core.FavoriteFolder
import dev.bulubulu.tv.core.VideoItem
import dev.bulubulu.tv.userMessage
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class FavoriteLibraryState(
val folders: List<FavoriteFolder> = emptyList(),
val selectedFolderId: Long? = null,
val items: List<VideoItem> = emptyList(),
val loading: Boolean = false,
val loadingMore: Boolean = false,
val hasMore: Boolean = false,
val error: String? = null,
)
/** Account/folder generations isolate even non-cooperative late responses. */
class FavoriteLibraryController(private val scope: CoroutineScope, private val repository: FavoriteDataSource) {
private val _state = MutableStateFlow(FavoriteLibraryState())
val state = _state.asStateFlow()
private var uid: Long? = null
private var job: Job? = null
private var generation = 0L
private var nextPage: Int? = null
private var opened = false
fun setAccount(value: Long?) {
if (uid == value) return
cancel()
uid = value
opened = false
nextPage = null
_state.value = FavoriteLibraryState()
}
fun refreshIfOpened() { if (opened) refresh() }
fun refresh() {
val account = uid ?: return
opened = true
cancel()
val request = generation
val previousFolder = _state.value.selectedFolderId
nextPage = null
_state.update { it.copy(items = emptyList(), loading = true, loadingMore = false, hasMore = false, error = null) }
job = scope.launch {
try {
val folders = repository.folders(account)
if (generation != request) return@launch
val selected = folders.firstOrNull { it.id == previousFolder } ?: folders.firstOrNull()
_state.update { it.copy(folders = folders, selectedFolderId = selected?.id) }
if (selected == null) {
_state.update { it.copy(loading = false) }
return@launch
}
val page = repository.videos(account, selected.id, 1)
if (generation != request) return@launch
nextPage = page.nextPage?.takeIf { it > 1 }
_state.update { it.copy(items = page.items.distinctBy(VideoItem::id), loading = false, hasMore = nextPage != null) }
} catch (error: Exception) { fail(error, request) }
}
}
fun selectFolder(id: Long) {
val account = uid ?: return
if (_state.value.folders.none { it.id == id } || (id == _state.value.selectedFolderId && _state.value.error == null)) return
cancel()
val request = generation
nextPage = null
_state.update { it.copy(selectedFolderId = id, items = emptyList(), loading = true, loadingMore = false, hasMore = false, error = null) }
job = scope.launch {
try {
val page = repository.videos(account, id, 1)
if (generation != request) return@launch
nextPage = page.nextPage?.takeIf { it > 1 }
_state.update { it.copy(items = page.items.distinctBy(VideoItem::id), loading = false, hasMore = nextPage != null) }
} catch (error: Exception) { fail(error, request) }
}
}
fun loadMore() {
val account = uid ?: return
val current = _state.value
val folder = current.selectedFolderId ?: return
val number = nextPage ?: return
if (current.loading || current.loadingMore) return
val request = generation
_state.update { it.copy(loadingMore = true, error = null) }
job = scope.launch {
try {
val page = repository.videos(account, folder, number)
if (generation != request) return@launch
val merged = (current.items + page.items).distinctBy(VideoItem::id)
// Filtered (invalid/unsupported) entries may occupy a whole page.
nextPage = page.nextPage?.takeIf { it > number && (page.items.isEmpty() || merged.size > current.items.size) }
_state.update { it.copy(items = merged, loadingMore = false, hasMore = nextPage != null) }
} catch (error: Exception) { fail(error, request) }
}
}
private fun fail(error: Exception, request: Long) {
if (error is CancellationException) throw error
if (generation == request) _state.update { it.copy(loading = false, loadingMore = false, error = userMessage(error)) }
}
private fun cancel() { generation++; job?.cancel(); job = null }
}
@@ -60,6 +60,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView import androidx.media3.ui.PlayerView
import dev.bulubulu.tv.core.PlaybackSource import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.favorites.FavoriteActionState
import dev.bulubulu.tv.ui.TvAccent import dev.bulubulu.tv.ui.TvAccent
import dev.bulubulu.tv.ui.TvAction import dev.bulubulu.tv.ui.TvAction
import dev.bulubulu.tv.ui.TvMuted import dev.bulubulu.tv.ui.TvMuted
@@ -68,7 +69,10 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
@Composable @Composable
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) { fun PlayerScreen(
source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit,
favorite: FavoriteActionState = FavoriteActionState(), onFavorite: () -> Unit = {},
) {
val context = LocalContext.current val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current val lifecycleOwner = LocalLifecycleOwner.current
val windowFocused = LocalWindowInfo.current.isWindowFocused val windowFocused = LocalWindowInfo.current.isWindowFocused
@@ -76,6 +80,10 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
val focusRequester = remember { FocusRequester() } val focusRequester = remember { FocusRequester() }
val retryFocus = remember { FocusRequester() } val retryFocus = remember { FocusRequester() }
val qualityFocus = remember { FocusRequester() } val qualityFocus = remember { FocusRequester() }
val favoriteFocus = remember { FocusRequester() }
var favoriteButtonFocused by remember(source) { mutableStateOf(false) }
var focusFavoriteRequested by remember(source) { mutableStateOf(false) }
var hadFavoriteMenu by remember(source) { mutableStateOf(false) }
var qualityMenuOpen by remember(source) { mutableStateOf(false) } var qualityMenuOpen by remember(source) { mutableStateOf(false) }
var qualityButtonFocused by remember(source) { mutableStateOf(false) } var qualityButtonFocused by remember(source) { mutableStateOf(false) }
var focusQualityRequested by remember(source) { mutableStateOf(false) } var focusQualityRequested by remember(source) { mutableStateOf(false) }
@@ -180,21 +188,36 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
delay(400) delay(400)
} }
} }
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen) { LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen, favoriteButtonFocused, favorite.visible) {
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen) { if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen && !favoriteButtonFocused && !favorite.visible) {
delay(4_000) delay(4_000)
controlsVisible = false controlsVisible = false
} else { } else {
controlsVisible = true controlsVisible = true
} }
} }
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused) { LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused, favorite.visible) {
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && error == null && windowFocused) { if (focusQualityRequested && controlsVisible && !qualityMenuOpen && !favorite.visible && error == null && windowFocused) {
delay(100) delay(100)
qualityFocus.requestFocus() qualityFocus.requestFocus()
focusQualityRequested = false focusQualityRequested = false
} }
} }
LaunchedEffect(favorite.visible) {
if (hadFavoriteMenu && !favorite.visible) {
controlsVisible = true
lastInteraction = SystemClock.elapsedRealtime()
focusFavoriteRequested = true
}
hadFavoriteMenu = favorite.visible
}
LaunchedEffect(focusFavoriteRequested, controlsVisible, windowFocused, favorite.visible, error) {
if (focusFavoriteRequested && controlsVisible && windowFocused && !favorite.visible && error == null && favorite.aid != null) {
delay(100)
favoriteFocus.requestFocus()
focusFavoriteRequested = false
}
}
LaunchedEffect(error) { LaunchedEffect(error) {
if (error != null) { delay(100); retryFocus.requestFocus() } if (error != null) { delay(100); retryFocus.requestFocus() }
} }
@@ -212,11 +235,14 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
modifier = Modifier.fillMaxSize().background(Color.Black) modifier = Modifier.fillMaxSize().background(Color.Black)
.focusRequester(focusRequester) .focusRequester(focusRequester)
.onPreviewKeyEvent { event -> .onPreviewKeyEvent { event ->
if (error != null || qualityMenuOpen) return@onPreviewKeyEvent false if (error != null || qualityMenuOpen || favorite.visible) return@onPreviewKeyEvent false
val native = event.nativeKeyEvent val native = event.nativeKeyEvent
val key = native.keyCode val key = native.keyCode
// Let the focused action receive its own confirm events. // Let the focused action receive its own confirm events.
if (qualityButtonFocused && key in setOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)) { if ((qualityButtonFocused || favoriteButtonFocused) && key in setOf(
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
)) {
return@onPreviewKeyEvent false return@onPreviewKeyEvent false
} }
val supported = key in setOf( val supported = key in setOf(
@@ -293,6 +319,13 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
} }
TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus) TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus)
.onFocusChanged { qualityButtonFocused = it.isFocused }.testTag("quality_button")) .onFocusChanged { qualityButtonFocused = it.isFocused }.testTag("quality_button"))
if (favorite.aid != null) {
TvAction(
if (!favorite.loggedIn) "登录后收藏" else if (favorite.saving) "保存中…" else if (favorite.favorited == true) "已收藏" else "收藏",
{ onFavorite(); interact() },
Modifier.focusRequester(favoriteFocus).onFocusChanged { favoriteButtonFocused = it.isFocused }.testTag("favorite_button"),
)
}
} }
Column( Column(
Modifier.align(Alignment.BottomCenter).fillMaxWidth() Modifier.align(Alignment.BottomCenter).fillMaxWidth()
@@ -309,7 +342,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height) drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height) drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
} }
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 返回键 退出", color = TvMuted, fontSize = 12.sp) Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 / 收藏 返回键 退出", color = TvMuted, fontSize = 12.sp)
} }
} }
error?.let { message -> error?.let { message ->
@@ -24,6 +24,9 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -33,6 +36,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@@ -41,11 +45,17 @@ import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
@@ -55,7 +65,9 @@ import coil.compose.AsyncImage
import coil.request.ImageRequest import coil.request.ImageRequest
import dev.bulubulu.tv.core.ContentTab import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.VideoItem import dev.bulubulu.tv.core.VideoItem
import dev.bulubulu.tv.favorites.FavoriteLibraryState
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable @Composable
fun BulubuluHome( fun BulubuluHome(
@@ -69,22 +81,49 @@ fun BulubuluHome(
focusRestoreKey: Int = 0, focusRestoreKey: Int = 0,
active: Boolean = true, active: Boolean = true,
onSearch: () -> Unit = {}, onSearch: () -> Unit = {},
favorites: FavoriteLibraryState = FavoriteLibraryState(),
onFavoriteFolderSelected: (Long) -> Unit = {},
) { ) {
val isFavorites = state.selectedTab == ContentTab.FAVORITES
val content = if (isFavorites) state.copy(
items = favorites.items, loading = favorites.loading, loadingMore = favorites.loadingMore,
hasMore = favorites.hasMore, error = favorites.error,
) else state
val visibleTabs = ContentTab.entries.filter { it != ContentTab.FAVORITES || state.account != null }
val portrait = state.selectedTab == ContentTab.MOVIE || state.selectedTab == ContentTab.BANGUMI
val itemScope = state.selectedTab.name + if (isFavorites) ":${favorites.selectedFolderId}" else ""
val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } } val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } }
val accountFocus = remember { FocusRequester() } val accountFocus = remember { FocusRequester() }
val refreshFocus = remember { FocusRequester() } val refreshFocus = remember { FocusRequester() }
val searchFocus = remember { FocusRequester() } val searchFocus = remember { FocusRequester() }
val cardFocus = remember { mutableMapOf<String, FocusRequester>() } val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
val folderFocus = remember { mutableMapOf<Long, FocusRequester>() }
val foldersScroll = rememberLazyListState()
val focusScope = rememberCoroutineScope()
fun focusSelectedFolder() {
val index = favorites.folders.indexOfFirst { it.id == favorites.selectedFolderId }
if (index < 0) return
focusScope.launch {
foldersScroll.scrollToItem(index)
delay(100)
folderFocus[favorites.folders[index].id]?.requestFocus()
}
}
val footerFocus = remember { FocusRequester() }
var folderHasFocus by remember { mutableStateOf(false) }
var pageStart by remember { mutableStateOf<Int?>(null) }
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") } var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
val recommendGrid = rememberLazyGridState() val recommendGrid = rememberLazyGridState()
val movieGrid = rememberLazyGridState() val movieGrid = rememberLazyGridState()
val bangumiGrid = rememberLazyGridState() val bangumiGrid = rememberLazyGridState()
val favoritesGrid = rememberLazyGridState()
val gridState = when (state.selectedTab) { val gridState = when (state.selectedTab) {
ContentTab.RECOMMEND -> recommendGrid ContentTab.RECOMMEND -> recommendGrid
ContentTab.MOVIE -> movieGrid ContentTab.MOVIE -> movieGrid
ContentTab.BANGUMI -> bangumiGrid ContentTab.BANGUMI -> bangumiGrid
ContentTab.FAVORITES -> favoritesGrid
} }
val columns = if (state.selectedTab == ContentTab.RECOMMEND) 4 else 5 val columns = if (portrait) 5 else 4
var gridHasFocus by remember { mutableStateOf(false) } var gridHasFocus by remember { mutableStateOf(false) }
var logoutConfirmation by remember { mutableStateOf(false) } var logoutConfirmation by remember { mutableStateOf(false) }
LaunchedEffect(focusRestoreKey, active) { LaunchedEffect(focusRestoreKey, active) {
@@ -95,9 +134,18 @@ fun BulubuluHome(
lastFocusToken == "account" -> accountFocus.requestFocus() lastFocusToken == "account" -> accountFocus.requestFocus()
lastFocusToken == "refresh" -> refreshFocus.requestFocus() lastFocusToken == "refresh" -> refreshFocus.requestFocus()
lastFocusToken == "search" -> searchFocus.requestFocus() lastFocusToken == "search" -> searchFocus.requestFocus()
lastFocusToken == "more" && content.hasMore -> footerFocus.requestFocus()
lastFocusToken.startsWith("folder:") && isFavorites -> {
val index = favorites.folders.indexOfFirst { "folder:${it.id}" == lastFocusToken }
if (index >= 0) {
foldersScroll.scrollToItem(index)
delay(100)
folderFocus[favorites.folders[index].id]?.requestFocus()
} else tabFocus.getValue(state.selectedTab).requestFocus()
}
lastFocusToken.startsWith("item:") -> { lastFocusToken.startsWith("item:") -> {
val prefix = "item:${state.selectedTab.name}:" val prefix = "item:$itemScope:"
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken } val index = content.items.indexOfFirst { prefix + it.id == lastFocusToken }
if (index >= 0) { if (index >= 0) {
gridState.scrollToItem(index) gridState.scrollToItem(index)
delay(100) delay(100)
@@ -107,7 +155,26 @@ fun BulubuluHome(
else -> tabFocus.getValue(state.selectedTab).requestFocus() else -> tabFocus.getValue(state.selectedTab).requestFocus()
} }
} }
BackHandler(active && gridHasFocus) { tabFocus.getValue(state.selectedTab).requestFocus() } LaunchedEffect(favorites.selectedFolderId) { favoritesGrid.scrollToItem(0); pageStart = null }
LaunchedEffect(content.loadingMore, content.items.size, active) {
val start = pageStart ?: return@LaunchedEffect
if (!active || content.loadingMore) return@LaunchedEffect
pageStart = null
if (content.error == null && content.items.size > start) {
gridState.scrollToItem(start)
delay(100)
cardFocus["item:$itemScope:${content.items[start].id}"]?.requestFocus()
} else if (!content.hasMore && content.items.isNotEmpty()) {
gridState.scrollToItem(content.items.lastIndex)
delay(100)
cardFocus["item:$itemScope:${content.items.last().id}"]?.requestFocus()
}
}
BackHandler(active && (gridHasFocus || folderHasFocus)) {
if (gridHasFocus && isFavorites && favorites.selectedFolderId != null) {
focusSelectedFolder()
} else tabFocus.getValue(state.selectedTab).requestFocus()
}
CompositionLocalProvider(LocalTvFocusEnabled provides active) { CompositionLocalProvider(LocalTvFocusEnabled provides active) {
Column( Column(
@@ -117,10 +184,16 @@ fun BulubuluHome(
) { ) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("bulubulu", color = TvText, fontWeight = FontWeight.Bold, fontSize = 28.sp, letterSpacing = (-1).sp) Text("bulubulu", color = TvText, fontWeight = FontWeight.Bold, fontSize = 28.sp, letterSpacing = (-1).sp)
Spacer(Modifier.width(26.dp)) Spacer(Modifier.width(if (state.account == null) 26.dp else 18.dp))
Row(horizontalArrangement = Arrangement.spacedBy(9.dp), modifier = Modifier.focusGroup()) { Row(horizontalArrangement = Arrangement.spacedBy(9.dp), modifier = Modifier.focusGroup()) {
ContentTab.entries.forEach { tab -> visibleTabs.forEach { tab ->
TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab)).onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab) TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab))
.onPreviewKeyEvent { event ->
if (tab == ContentTab.FAVORITES && isFavorites && favorites.folders.isNotEmpty() && event.key == Key.DirectionDown) {
if (event.type == KeyEventType.KeyDown) focusSelectedFolder()
true
} else false
}.testTag("tab_${tab.name}").onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab)
} }
} }
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
@@ -129,7 +202,7 @@ fun BulubuluHome(
if (state.authBusy) { if (state.authBusy) {
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false) TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
} else if (state.account != null) { } else if (state.account != null) {
TvAction(state.account.name.take(10) + " · 退出", { logoutConfirmation = true }, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" }) TvAction(state.account.name.take(6) + " · 退出", { logoutConfirmation = true }, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
} else { } else {
TvAction("扫码登录", onLogin, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" }) TvAction("扫码登录", onLogin, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
} }
@@ -142,16 +215,35 @@ fun BulubuluHome(
ContentTab.RECOMMEND -> if (state.account == null) "发现好视频" else "为你推荐" ContentTab.RECOMMEND -> if (state.account == null) "发现好视频" else "为你推荐"
ContentTab.MOVIE -> "电影" ContentTab.MOVIE -> "电影"
ContentTab.BANGUMI -> "番剧" ContentTab.BANGUMI -> "番剧"
ContentTab.FAVORITES -> favorites.folders.firstOrNull { it.id == favorites.selectedFolderId }?.title ?: "我的收藏"
}, },
color = TvText, fontSize = 21.sp, fontWeight = FontWeight.SemiBold, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.SemiBold,
maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
Text(if (state.account == null) "登录后可观看账号有权访问的内容" else "${state.items.size} 部内容", color = TvMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 3.dp)) Text(if (state.account == null) "登录后可观看账号有权访问的内容" else if (isFavorites) "已加载 ${content.items.size} 个视频" else "${content.items.size} 部内容", color = TvMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 3.dp))
}
TvAction("刷新", onRefresh, Modifier.focusRequester(refreshFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "refresh" }, enabled = !content.loading)
}
if (isFavorites && favorites.folders.isNotEmpty()) {
LazyRow(
state = foldersScroll,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).onFocusChanged { folderHasFocus = it.hasFocus }.focusGroup(),
) {
items(favorites.folders, key = { it.id }) { folder ->
TvAction(
"${folder.title.take(22)} · ${folder.mediaCount}",
{ pageStart = null; onFavoriteFolderSelected(folder.id) },
Modifier.focusRequester(folderFocus.getOrPut(folder.id) { FocusRequester() })
.testTag("favorite_folder_${folder.id}").onFocusChanged { if (it.isFocused) lastFocusToken = "folder:${folder.id}" },
selected = folder.id == favorites.selectedFolderId,
)
}
} }
TvAction("刷新", onRefresh, Modifier.focusRequester(refreshFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "refresh" }, enabled = !state.loading)
} }
Spacer(Modifier.height(10.dp)) Spacer(Modifier.height(10.dp))
when { when {
state.loading && state.items.isEmpty() -> { content.loading && content.items.isEmpty() -> {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp) CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp)
@@ -159,11 +251,19 @@ fun BulubuluHome(
} }
} }
} }
state.items.isEmpty() -> { content.items.isEmpty() -> {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(state.error ?: "暂时没有内容", color = TvText, fontSize = 18.sp) Text(content.error ?: if (isFavorites) {
TvAction("重新加载", onRefresh) if (favorites.folders.isEmpty()) "还没有收藏夹,在哔哩哔哩创建后即可查看" else "这个收藏夹暂无可播放的视频"
} else "暂时没有内容", color = TvText, fontSize = 18.sp)
if (content.hasMore) {
TvAction(
if (content.loadingMore) "正在加载…" else "继续加载",
{ if (!content.loadingMore) { pageStart = content.items.size; onLoadMore() } },
Modifier.focusRequester(footerFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "more" },
)
} else TvAction("重新加载", onRefresh)
} }
} }
} }
@@ -176,11 +276,11 @@ fun BulubuluHome(
contentPadding = PaddingValues(6.dp, 8.dp, 6.dp, 20.dp), contentPadding = PaddingValues(6.dp, 8.dp, 6.dp, 20.dp),
modifier = Modifier.weight(1f).fillMaxWidth().onFocusChanged { gridHasFocus = it.hasFocus }.focusGroup(), modifier = Modifier.weight(1f).fillMaxWidth().onFocusChanged { gridHasFocus = it.hasFocus }.focusGroup(),
) { ) {
items(state.items, key = { it.id }) { item -> items(content.items, key = { it.id }) { item ->
val focusToken = "item:${state.selectedTab.name}:${item.id}" val focusToken = "item:$itemScope:${item.id}"
VideoCard( VideoCard(
item = item, item = item,
portrait = state.selectedTab != ContentTab.RECOMMEND, portrait = portrait,
focusRequester = cardFocus.getOrPut(focusToken) { FocusRequester() }, focusRequester = cardFocus.getOrPut(focusToken) { FocusRequester() },
onFocused = { lastFocusToken = focusToken }, onFocused = { lastFocusToken = focusToken },
onClick = { onItemSelected(item) }, onClick = { onItemSelected(item) },
@@ -188,10 +288,13 @@ fun BulubuluHome(
} }
item(span = { GridItemSpan(columns) }, key = "load-more") { item(span = { GridItemSpan(columns) }, key = "load-more") {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
state.error?.let { Text(it, color = Color(0xFFFFB0A6), fontSize = 14.sp) } content.error?.let { Text(it, color = Color(0xFFFFB0A6), fontSize = 14.sp) }
when { when {
state.loadingMore -> CircularProgressIndicator(Modifier.size(26.dp), color = TvAccent, strokeWidth = 2.dp) content.loadingMore || content.hasMore -> TvAction(
state.hasMore -> TvAction(if (state.error == null) "加载更多" else "重试", onLoadMore) if (content.loadingMore) "正在加载…" else if (content.error == null) "加载更多" else "重试",
{ if (!content.loadingMore) { if (isFavorites) pageStart = content.items.size; onLoadMore() } },
Modifier.focusRequester(footerFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "more" },
)
else -> Text("已经到底了", color = TvMuted, fontSize = 13.sp) else -> Text("已经到底了", color = TvMuted, fontSize = 13.sp)
} }
} }
@@ -0,0 +1,126 @@
package dev.bulubulu.tv.ui
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import dev.bulubulu.tv.favorites.FavoriteActionState
import kotlinx.coroutines.delay
@Composable
fun FavoriteDialog(
state: FavoriteActionState,
onToggle: (Long) -> Unit,
onSave: () -> Unit,
onReload: () -> Unit,
onDismiss: () -> Unit,
) {
val list = rememberLazyListState()
val firstFocus = remember { FocusRequester() }
val closeFocus = remember { FocusRequester() }
val reloadFocus = remember { FocusRequester() }
val saveFocus = remember { FocusRequester() }
val firstIndex = state.folders.indexOfFirst { it.id in state.selectedIds }.coerceAtLeast(0)
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
val view = LocalView.current
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(view) {
(view.parent as? DialogWindowProvider)?.window?.let { window ->
WindowCompat.getInsetsController(window, view).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
}
LaunchedEffect(state.loading, state.saving, state.needsReload, windowFocused) {
if (!windowFocused) return@LaunchedEffect
if (!state.loading && !state.saving && !state.needsReload && state.folders.isNotEmpty()) {
list.scrollToItem(firstIndex)
delay(100)
firstFocus.requestFocus()
} else {
delay(100)
if (state.needsReload) reloadFocus.requestFocus() else closeFocus.requestFocus()
}
}
Surface(
modifier = Modifier.widthIn(max = 540.dp).fillMaxWidth(0.92f)
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)).testTag("favorite_menu"),
color = TvPanel, contentColor = TvText, shape = RoundedCornerShape(22.dp),
) {
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("收藏到", fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
Text(
if (state.saving) "正在保存…" else "选择收藏夹后保存;取消勾选可移出对应收藏夹",
color = TvMuted, fontSize = 13.sp,
)
when {
state.loading -> CircularProgressIndicator(Modifier.size(28.dp), color = TvAccent, strokeWidth = 2.dp)
state.needsReload -> Text(state.error ?: "请重新加载收藏状态", color = Color(0xFFFFB0A6), fontSize = 14.sp)
state.folders.isEmpty() -> Text("还没有收藏夹,请先在哔哩哔哩创建一个。", color = TvMuted, fontSize = 15.sp)
else -> LazyColumn(
state = list, modifier = Modifier.fillMaxWidth().heightIn(max = 200.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(state.folders, key = { it.id }) { folder ->
val selected = folder.id in state.selectedIds
TvAction(
(if (selected) "✓ " else "○ ") + folder.title.take(26),
{ onToggle(folder.id) },
Modifier.fillMaxWidth().focusProperties {
if (folder.id == state.folders.last().id) down = saveFocus
}.testTag("favorite_option_${folder.id}").then(
if (folder.id == state.folders[firstIndex].id) Modifier.focusRequester(firstFocus) else Modifier,
),
selected = selected, enabled = !state.saving,
)
}
}
}
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (state.needsReload) {
TvAction("重新加载", onReload, Modifier.focusRequester(reloadFocus).testTag("favorite_reload"))
} else if (state.folders.isNotEmpty() && !state.loading) {
TvAction(
if (state.saving) "正在保存…" else if (state.selectedIds.isEmpty()) "保存(移出收藏)" else "保存",
onSave, Modifier.focusRequester(saveFocus).testTag("favorite_save"), enabled = !state.saving,
)
}
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus).testTag("favorite_close"))
}
}
}
}
}
@@ -0,0 +1,55 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.data.BiliCookieJar
import dev.bulubulu.tv.data.InMemorySessionCookieStore
import okhttp3.Cookie
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.IOException
import org.junit.Assert.*
import org.junit.Test
class AccountRequestSessionTest {
private fun cookie(name: String, value: String, domain: String = "bilibili.com") =
Cookie.Builder().name(name).value(value).domain(domain).path("/").secure().build()
private fun session(uid: Long) = listOf(cookie("DedeUserID", uid.toString()), cookie("SESSDATA", "fake-session"), cookie("bili_jct", "fake-csrf"))
@Test fun accountIdentityAndCsrfAreReadFromTheSameSession() {
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
val captured = jar.accountSession(123, true)
assertEquals("fake-csrf", captured.csrf)
assertEquals(jar.currentEpoch(), captured.epoch)
rejected { jar.accountSession(456, true) }
}
@Test fun csrfMustExistAndMatchTheApiCookieScopeForWrites() {
val cookies = session(123).filter { it.name != "bili_jct" } + cookie("bili_jct", "wrong-scope", "passport.bilibili.com")
val jar = BiliCookieJar(InMemorySessionCookieStore(cookies))
assertNull(jar.accountSession(123, false).csrf)
rejected { jar.accountSession(123, true) }
}
@Test fun logoutOrAccountReplacementRejectsQueuedOldAccountRequests() {
for (logout in listOf(true, false)) {
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
val captured = jar.accountSession(123, true)
if (logout) jar.clear() else jar.replaceSession(session(456))
try {
jar.requestSession("https://api.bilibili.com/".toHttpUrl(), captured.epoch)
fail("Stale request accepted")
} catch (_: IOException) {
// A transport-safe failure must reach OkHttp's onFailure, not crash its worker.
}
}
}
@Test fun accountCookieChecksNeverForwardCredentialsToCdn() {
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
val captured = jar.accountSession(123, true)
assertTrue(jar.requestSession("https://cdn.example/video".toHttpUrl(), captured.epoch).second.isEmpty())
val anonymous = BiliCookieJar(InMemorySessionCookieStore(session(123).filter { it.name != "SESSDATA" }))
rejected { anonymous.accountSession(123, true) }
}
private fun rejected(block: () -> Unit) { try { block(); fail("Unbound account request accepted") } catch (_: ClientException) { } }
}
@@ -0,0 +1,73 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.data.FavoriteJson
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
class FavoriteJsonTest {
@Test fun foldersKeepAccountLongIdsAndMembership() {
val folders = FavoriteJson.folders(json("""{"code":0,"data":{"list":[
{"id":9007199254740993,"mid":123,"title":"教程 &amp; 示例","media_count":31,"fav_state":1},
{"id":8,"mid":123,"title":"稍后看","media_count":2,"fav_state":0}
]}}"""), 123, true)
assertEquals(9007199254740993L, folders[0].id)
assertEquals("教程 & 示例", folders[0].title)
assertEquals(31, folders[0].mediaCount)
assertTrue(folders[0].containsVideo)
assertFalse(folders[1].containsVideo)
}
@Test fun emptyFolderResponseIsDifferentFromMalformedData() {
assertTrue(FavoriteJson.folders(json("""{"code":0,"data":null}"""), 1, false).isEmpty())
assertTrue(FavoriteJson.folders(json("""{"code":0,"data":{"count":0}}"""), 1, false).isEmpty())
malformed { FavoriteJson.folders(json("""{"code":0}"""), 1, false) }
malformed { FavoriteJson.folders(json("""{"code":0,"data":{}}"""), 1, false) }
}
@Test fun anotherAccountFolderAndUnknownMembershipCannotBecomeEditable() {
malformed { FavoriteJson.folders(json("""{"code":0,"data":{"list":[{"id":1,"mid":2,"title":"别的账号"}]}}"""), 1, false) }
malformed { FavoriteJson.folders(json("""{"code":0,"data":{"list":[{"id":1,"mid":1,"title":"收藏夹"}]}}"""), 1, true) }
}
@Test fun favoriteVideosFilterInvalidAndUnsupportedResourcesAndDeduplicate() {
val valid = """{"id":9007199254740993,"type":2,"attr":0,"title":"视频","cover":"http://img.example/cover.jpg","bvid":"BV1test","duration":125,"upper":{"name":"作者"}}"""
val page = FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true,"medias":[
$valid,$valid,{"id":2,"type":2,"attr":9,"title":"已失效视频"},{"id":3,"type":24,"title":"不支持的资源"}
]}}"""), 1)
assertEquals(1, page.items.size)
assertEquals(9007199254740993L, page.items.single().aid)
assertEquals("https://img.example/cover.jpg", page.items.single().coverUrl)
assertEquals("作者 · 2:05", page.items.single().subtitle)
assertEquals(2, page.nextPage)
}
@Test fun filteredPageStillAllowsAccessToFollowingVideos() {
val page = FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true,"medias":[{"id":1,"type":2,"attr":9}]}}"""), 4)
assertTrue(page.items.isEmpty())
assertEquals(5, page.nextPage)
}
@Test fun trueEmptyFolderStopsButMissingResourceDataDoesNotLookEmpty() {
assertNull(FavoriteJson.videos(json("""{"code":0,"data":{"has_more":false,"info":{"media_count":0},"medias":null}}"""), 1).nextPage)
malformed { FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true}}"""), 1) }
malformed { FavoriteJson.videos(json("""{"code":0,"data":{"medias":[]}}"""), 1) }
}
@Test fun statusRequiresExplicitFavoriteFlag() {
assertTrue(FavoriteJson.status(json("""{"code":0,"data":{"favoured":true}}""")))
assertFalse(FavoriteJson.status(json("""{"code":0,"data":{"favoured":0}}""")))
malformed { FavoriteJson.status(json("""{"code":0,"data":{}}""")) }
}
@Test fun writeSuccessRequiresAnExplicitZeroCode() {
FavoriteJson.requireSuccess(json("""{"code":0,"data":null}"""))
malformed { FavoriteJson.requireSuccess(json("""{}""")) }
try { FavoriteJson.requireSuccess(json("""{"code":-101}""")); fail() } catch (_: BiliApiException) { }
}
private fun json(value: String) = JSONObject(value)
private fun malformed(block: () -> Unit) { try { block(); fail("Incomplete favorite data accepted") } catch (_: ClientException) { } }
}
@@ -0,0 +1,33 @@
package dev.bulubulu.tv.favorites
import dev.bulubulu.tv.core.*
internal data class FavoriteChange(val uid: Long, val aid: Long, val add: Set<Long>, val remove: Set<Long>)
internal class FakeFavorites : FavoriteDataSource {
var onFolders: suspend (Long, Long?) -> List<FavoriteFolder> = { _, _ ->
listOf(FavoriteFolder(11, "默认收藏夹", 2), FavoriteFolder(22, "教程", 1))
}
var onVideos: suspend (Long, Long, Int) -> FavoritePage = { _, folder, _ ->
FavoritePage(listOf(VideoItem("av$folder", "视频", "", aid = folder)), null)
}
var onStatus: suspend (Long, Long) -> Boolean = { _, _ -> false }
var onUpdate: suspend (FavoriteChange) -> Unit = {}
val folderCalls = mutableListOf<Pair<Long, Long?>>()
val videoCalls = mutableListOf<Triple<Long, Long, Int>>()
val updates = mutableListOf<FavoriteChange>()
override suspend fun folders(uid: Long, aid: Long?): List<FavoriteFolder> {
folderCalls += uid to aid
return onFolders(uid, aid)
}
override suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage {
videoCalls += Triple(uid, folderId, page)
return onVideos(uid, folderId, page)
}
override suspend fun isFavorite(uid: Long, aid: Long) = onStatus(uid, aid)
override suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>) {
val change = FavoriteChange(uid, aid, add, remove)
updates += change
onUpdate(change)
}
}
@@ -0,0 +1,142 @@
package dev.bulubulu.tv.favorites
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.core.FavoriteFolder
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class FavoriteActionControllerTest {
@Test fun anonymousPlaybackCannotReadOrWritePrivateFavorites() = runTest {
val api = FakeFavorites()
val messages = mutableListOf<String>()
val controller = FavoriteActionController(this, api, {}, messages::add)
controller.setVideo(100)
controller.open()
controller.save()
runCurrent()
assertFalse(controller.state.value.visible)
assertTrue(api.folderCalls.isEmpty())
assertTrue(api.updates.isEmpty())
assertEquals(1, messages.size)
}
@Test fun draftSelectionAndDismissNeverWrite() = runTest {
val api = FakeFavorites()
val controller = FavoriteActionController(this, api, {}, {})
controller.setAccount(123); controller.setVideo(100); controller.open()
runCurrent()
assertEquals(setOf(11L), controller.state.value.selectedIds)
controller.toggle(22)
controller.toggle(999)
controller.close()
runCurrent()
assertTrue(api.updates.isEmpty())
assertFalse(controller.state.value.visible)
}
@Test fun saveOnlyAppliesMembershipDifferencesToThePlayingArchive() = runTest {
val api = FakeFavorites().apply {
onFolders = { _, _ -> listOf(FavoriteFolder(11, "已有", 1, true), FavoriteFolder(22, "新增", 0)) }
}
var changes = 0
val messages = mutableListOf<String>()
val controller = FavoriteActionController(this, api, { changes++ }, messages::add)
controller.setAccount(123); controller.setVideo(100); controller.open()
runCurrent()
controller.toggle(11); controller.toggle(22); controller.save()
runCurrent()
assertEquals(listOf(FavoriteChange(123, 100, setOf(22), setOf(11))), api.updates)
assertTrue(controller.state.value.favorited == true)
assertFalse(controller.state.value.visible)
assertEquals(1, changes)
assertEquals(listOf("已更新收藏"), messages)
}
@Test fun unchangedSelectionDoesNotReloadOrSendAWriteAndRemovingAllIsExplicit() = runTest {
val api = FakeFavorites().apply { onFolders = { _, _ -> listOf(FavoriteFolder(11, "已有", 1, true)) } }
val controller = FavoriteActionController(this, api, {}, {})
controller.setAccount(123); controller.setVideo(100); controller.open()
runCurrent()
controller.save()
runCurrent()
assertTrue(api.updates.isEmpty())
controller.open(); runCurrent()
controller.toggle(11); controller.save(); runCurrent()
assertEquals(setOf(11L), api.updates.single().remove)
assertEquals(false, controller.state.value.favorited)
}
@Test fun duplicateSaveCannotStartConcurrentWrites() = runTest {
val api = FakeFavorites()
lateinit var pending: Continuation<Unit>
api.onUpdate = { suspendCoroutine { pending = it } }
val controller = FavoriteActionController(this, api, {}, {})
controller.setAccount(123); controller.setVideo(100); controller.open()
runCurrent()
controller.save(); controller.save(); controller.toggle(22); runCurrent()
assertTrue(controller.state.value.saving)
assertEquals(1, api.updates.size)
pending.resume(Unit); runCurrent()
assertFalse(controller.state.value.saving)
}
@Test fun uncertainWriteRequiresAnAuthoritativeReloadBeforeRetry() = runTest {
val api = FakeFavorites().apply { onUpdate = { throw ClientException("连接中断") } }
val messages = mutableListOf<String>()
val controller = FavoriteActionController(this, api, {}, messages::add)
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
controller.save(); runCurrent()
assertTrue(controller.state.value.visible)
assertTrue(controller.state.value.needsReload)
assertNull(controller.state.value.favorited)
assertTrue(messages.isEmpty())
controller.save(); runCurrent()
assertEquals(1, api.updates.size)
api.onFolders = { _, _ -> listOf(FavoriteFolder(11, "已保存", 1, true)) }
controller.open(); runCurrent()
assertFalse(controller.state.value.needsReload)
assertEquals(true, controller.state.value.favorited)
controller.save(); runCurrent()
assertEquals(1, api.updates.size)
}
@Test fun accountSwitchRejectsLateFolderMembership() = runTest {
val api = FakeFavorites()
lateinit var pending: Continuation<List<FavoriteFolder>>
api.onFolders = { _, _ -> suspendCoroutine { pending = it } }
val controller = FavoriteActionController(this, api, {}, {})
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
controller.setAccount(null)
pending.resume(listOf(FavoriteFolder(11, "旧账号", 1, true))); runCurrent()
assertFalse(controller.state.value.visible)
assertFalse(controller.state.value.loggedIn)
assertTrue(controller.state.value.folders.isEmpty())
assertNull(controller.state.value.favorited)
}
@Test fun newVideoAndClosedDialogRejectLateSuccessfulWrites() = runTest {
for (newVideo in listOf(true, false)) {
val api = FakeFavorites()
lateinit var pending: Continuation<Unit>
api.onUpdate = { suspendCoroutine { pending = it } }
val messages = mutableListOf<String>()
val controller = FavoriteActionController(this, api, {}, messages::add)
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
controller.save(); runCurrent()
if (newVideo) controller.setVideo(200) else controller.close()
runCurrent()
pending.resume(Unit); runCurrent()
assertTrue(messages.isEmpty())
assertFalse(controller.state.value.visible)
assertEquals(if (newVideo) 200L else 100L, controller.state.value.aid)
assertEquals(false, controller.state.value.favorited)
}
}
}
@@ -0,0 +1,115 @@
package dev.bulubulu.tv.favorites
import dev.bulubulu.tv.core.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class FavoriteLibraryControllerTest {
private fun item(id: String) = VideoItem(id, "视频 $id", "")
@Test fun privateLibraryRequiresLoginAndLogoutClearsEverything() = runTest {
val api = FakeFavorites()
val controller = FavoriteLibraryController(this, api)
controller.refresh(); runCurrent()
assertTrue(api.folderCalls.isEmpty())
controller.setAccount(123); controller.refresh(); runCurrent()
assertEquals(2, controller.state.value.folders.size)
assertEquals(11L, controller.state.value.selectedFolderId)
controller.setAccount(null)
assertEquals(FavoriteLibraryState(), controller.state.value)
}
@Test fun newFolderRejectsUncooperativeOldPage() = runTest {
val api = FakeFavorites()
val pending = mutableListOf<Continuation<FavoritePage>>()
api.onVideos = { _, _, _ -> suspendCoroutine { pending += it } }
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refresh(); runCurrent()
controller.selectFolder(22); runCurrent()
pending[1].resume(FavoritePage(listOf(item("new")), null)); runCurrent()
pending[0].resume(FavoritePage(listOf(item("old")), 2)); runCurrent()
assertEquals(22L, controller.state.value.selectedFolderId)
assertEquals(listOf("new"), controller.state.value.items.map { it.id })
assertFalse(controller.state.value.hasMore)
}
@Test fun newAccountRejectsOldFolderList() = runTest {
val api = FakeFavorites()
lateinit var pending: Continuation<List<FavoriteFolder>>
api.onFolders = { _, _ -> suspendCoroutine { pending = it } }
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refresh(); runCurrent()
controller.setAccount(456)
pending.resume(listOf(FavoriteFolder(99, "旧账号", 1))); runCurrent()
assertEquals(FavoriteLibraryState(), controller.state.value)
assertTrue(api.videoCalls.isEmpty())
}
@Test fun emptyFolderListIsAValidEmptyLibrary() = runTest {
val api = FakeFavorites().apply { onFolders = { _, _ -> emptyList() } }
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refresh(); runCurrent()
assertFalse(controller.state.value.loading)
assertNull(controller.state.value.error)
assertNull(controller.state.value.selectedFolderId)
assertTrue(api.videoCalls.isEmpty())
}
@Test fun paginationSkipsUnsupportedEntriesAndStopsRepeatedPlayablePages() = runTest {
val api = FakeFavorites().apply {
onVideos = { _, _, page -> when (page) {
1 -> FavoritePage(emptyList(), 2)
2 -> FavoritePage(listOf(item("a"), item("a")), 3)
else -> FavoritePage(listOf(item("a")), 4)
} }
}
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refresh(); runCurrent()
assertTrue(controller.state.value.hasMore)
controller.loadMore(); controller.loadMore(); runCurrent()
controller.loadMore(); runCurrent()
controller.loadMore(); runCurrent()
assertEquals(listOf(1, 2, 3), api.videoCalls.map { it.third })
assertEquals(listOf("a"), controller.state.value.items.map { it.id })
assertFalse(controller.state.value.hasMore)
}
@Test fun pageFailureRetainsVideosAndRetryUsesTheSamePage() = runTest {
var fail = true
val api = FakeFavorites().apply {
onVideos = { _, _, page ->
if (page == 2 && fail) { fail = false; throw ClientException("请重试") }
FavoritePage(listOf(item(page.toString())), if (page == 1) 2 else null)
}
}
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refresh(); runCurrent()
controller.loadMore(); runCurrent()
assertEquals("请重试", controller.state.value.error)
assertEquals(listOf("1"), controller.state.value.items.map { it.id })
controller.loadMore(); runCurrent()
assertEquals(listOf(1, 2, 2), api.videoCalls.map { it.third })
assertEquals(listOf("1", "2"), controller.state.value.items.map { it.id })
}
@Test fun mutationRefreshesAnOpenedLibraryAndRetainsSelectedFolder() = runTest {
val api = FakeFavorites()
val controller = FavoriteLibraryController(this, api)
controller.setAccount(123); controller.refreshIfOpened(); runCurrent()
assertTrue(api.folderCalls.isEmpty())
controller.refresh(); runCurrent()
controller.selectFolder(22); runCurrent()
controller.refreshIfOpened(); runCurrent()
assertEquals(22L, controller.state.value.selectedFolderId)
api.onFolders = { _, _ -> listOf(FavoriteFolder(11, "剩下的", 0)) }
controller.refresh(); runCurrent()
assertEquals(11L, controller.state.value.selectedFolderId)
}
}
+3
View File
@@ -9,9 +9,12 @@ The application has one Android app module and no backend service.
- `SessionStore` encrypts cookies with an Android Keystore AES-GCM key and writes an atomic file in `noBackupFilesDir`. - `SessionStore` encrypts cookies with an Android Keystore AES-GCM key and writes an atomic file in `noBackupFilesDir`.
- `ContentRepository` retrieves official catalogue/details/playback responses; `WbiSigner` caches official signing material; pure `ContentJson` parsing separates format and entitlement checks from transport. - `ContentRepository` retrieves official catalogue/details/playback responses; `WbiSigner` caches official signing material; pure `ContentJson` parsing separates format and entitlement checks from transport.
- `SearchRepository` uses official category search and the shared first-party session; pure `SearchJson` parses highlights, content identifiers, rights badges and bounded pagination. `SearchController` owns draft/submitted queries, category, deduplicated pages and cancellable requests. A generation guard also rejects non-cooperative late responses after a new query, category, clear, close or logout. It keeps no durable history. - `SearchRepository` uses official category search and the shared first-party session; pure `SearchJson` parses highlights, content identifiers, rights badges and bounded pagination. `SearchController` owns draft/submitted queries, category, deduplicated pages and cancellable requests. A generation guard also rejects non-cooperative late responses after a new query, category, clear, close or logout. It keeps no durable history.
- `FavoriteRepository` reads official account folders, archive memberships and paginated resources, and submits explicit membership diffs. Account-bound requests capture a cookie epoch, require matching UID/SESSDATA and API-scoped CSRF for writes, and disable redirects and connection retries. `FavoriteJson` validates membership completeness and filters invalid or unsupported resources.
- `FavoriteLibraryController` owns the selected folder and deduplicated pagination. `FavoriteActionController` separates the player's draft selections from confirmed server membership; only Save writes. Both cancel and reject late results after account/folder/video changes. Uncertain writes require an authoritative reload before retry. Logout clears the library; it has no durable cache.
- `BulubuluHome`, dialogs and `TvAction` own TV layout/focus. Home stays composed beneath overlays, with focus/clicks disabled while inactive. - `BulubuluHome`, dialogs and `TvAction` own TV layout/focus. Home stays composed beneath overlays, with focus/clicks disabled while inactive.
- `SearchScreen` uses the device IME and the existing card components. It stays composed beneath details/player and restores result focus independently of Home. - `SearchScreen` uses the device IME and the existing card components. It stays composed beneath details/player and restores result focus independently of Home.
- `PlayerScreen` creates and releases Media3 with the composable lifecycle, merges separate AVC/AAC tracks and handles D-pad/media keys. CDN requests never receive account cookies. - `PlayerScreen` creates and releases Media3 with the composable lifecycle, merges separate AVC/AAC tracks and handles D-pad/media keys. CDN requests never receive account cookies.
- `PlaybackQualitySwitcher` owns manual quality changes and commits the selected label only when the replacement source is ready. It preserves position/play intent, rejects overlapping requests and attempts the original source once after failure. `playbackMediaSource` shares HTTP identity, backup CDN handling and track merging between initial playback and changes. `QualityDialog` scrolls to and focuses the current actual track; one ExoPlayer is retained throughout the screen lifecycle. - `PlaybackQualitySwitcher` owns manual quality changes and commits the selected label only when the replacement source is ready. It preserves position/play intent, rejects overlapping requests and attempts the original source once after failure. `playbackMediaSource` shares HTTP identity, backup CDN handling and track merging between initial playback and changes. `QualityDialog` scrolls to and focuses the current actual track; one ExoPlayer is retained throughout the screen lifecycle.
- `FavoriteDialog` provides multiple folder choices and explicit Save/Close actions. `PlayerScreen` restores its favorite action after the dialog regains the parent window's focus; opening or saving favorites does not recreate the player or media source.
There is no analytics, self-update service, local media scanning or private server. Login credentials and signed playback URLs must never appear in application logs or raw error messages. Account entitlements and region/DRM restrictions remain server-controlled. Tests use fake sessions in isolated storage and do not require a real account. There is no analytics, self-update service, local media scanning or private server. Login credentials and signed playback URLs must never appear in application logs or raw error messages. Account entitlements and region/DRM restrictions remain server-controlled. Tests use fake sessions in isolated storage and do not require a real account.
+2 -1
View File
@@ -7,6 +7,7 @@
- HTTP 层每一跳重新计算 Cookie,严格遵守域名、路径、有效期,并且仅向 HTTPS 的 `bilibili.com` 及其子域发送。图片/CDN、第三方和 HTTP 不会收到会话 Cookie。 - HTTP 层每一跳重新计算 Cookie,严格遵守域名、路径、有效期,并且仅向 HTTPS 的 `bilibili.com` 及其子域发送。图片/CDN、第三方和 HTTP 不会收到会话 Cookie。
- 退出登录先立即删除本地会话,再用隔离的旧会话尽力调用官方注销接口。该请求迟到也不会删除之后的新登录。Cookie 代次保护还可避免旧网络响应覆盖已验证的新账号。 - 退出登录先立即删除本地会话,再用隔离的旧会话尽力调用官方注销接口。该请求迟到也不会删除之后的新登录。Cookie 代次保护还可避免旧网络响应覆盖已验证的新账号。
- 只有官方明确返回未登录时清理失效凭据。网络失败、HTTP 412 风控和服务器错误不会触发删除登录状态。 - 只有官方明确返回未登录时清理失效凭据。网络失败、HTTP 412 风控和服务器错误不会触发删除登录状态。
- 收藏读写绑定请求创建时的账号 Cookie 代次;发送前重新检查,退出或账号替换后的旧请求会失败,不能携带新账号凭据提交。写入还要求匹配 UID、SESSDATA 和 API 域可用的 `bili_jct`,关闭重定向与连接自动重试;CSRF 不发送给图片或媒体服务器。
- 没有统计 SDK、崩溃上传、口令输入、刷新令牌上传或自动升级器。没有实现 Cookie 自动续期;失效后重新扫码。 - 没有统计 SDK、崩溃上传、口令输入、刷新令牌上传或自动升级器。没有实现 Cookie 自动续期;失效后重新扫码。
验证范围:官方匿名 nav 和 QR 生成接口已成功做只读探测。未使用用户账号完成扫码,也未在电视上安装。单元测试覆盖 Cookie 域名/路径/HTTPS/过期/替换、退出登录竞态,以及 JSON API URL 限制。Keystore 加密需要真机或 Android 模拟器验证,普通 JVM 单元测试不能代替。 验证范围:官方匿名 nav 和 QR 生成接口已成功做只读探测。应用已部署到目标电视;开发测试未使用真实账号完成扫码或收藏写入。单元测试覆盖 Cookie 域名/路径/HTTPS/过期/替换、退出登录竞态、JSON API URL 限制,以及收藏请求的账号 / CSRF 绑定。Android 模拟器已验证 Keystore 密文重建和篡改拒绝;真实账号的端到端验证仍待进行。
+28
View File
@@ -0,0 +1,28 @@
# 收藏接口与状态
所有请求直接访问官方 `https://api.bilibili.com`,使用扫码取得的本机加密会话。没有第三方收藏服务,不持久缓存收藏列表,也不在开发测试中修改真实账号收藏。
| 方法 | 路径 | 用途与主要参数 |
| --- | --- | --- |
| GET | `/x/v3/fav/folder/created/list-all` | `up_mid=uid&type=2` 读取自己的收藏夹;附加 `rid=aid` 时读取每个收藏夹的 `fav_state` |
| GET | `/x/v3/fav/resource/list` | `media_id`、`pn`、`ps=20`、`order=mtime`、`platform=web`、`type=0`、`tid=0`,按收藏时间读取视频 |
| GET | `/x/v2/fav/video/favoured` | `aid` 读取当前稿件是否已收藏 |
| POST | `/x/v3/fav/resource/deal` | `rid=aid&type=2`、逗号分隔的 `add_media_ids` / `del_media_ids`、`csrf`、`platform=web`,提交收藏夹差量 |
收藏夹与资源查询附带 `web_location=333.1387`。收藏夹和稿件 ID 全程使用 Long。资源分页遵守 `has_more`,每页去重;整页都是失效或不支持的条目时,仍允许继续加载。页码上限 1000,重复的非空视频页停止追加。
当前只展示 `type=2` 的视频稿件,过滤 `attr & 9 != 0` 的失效条目和其他资源类型,复用已有详情 / 分 P / 播放流程。播放器通过当前选集的 `aid` 收藏稿件,不能代替番剧或电影的追番 / 追剧。收藏夹数量可能包含已过滤的条目,因此不保证等于页面显示的视频数。创建、重命名、删除收藏夹尚未实现。
## 显式保存与错误处理
打开菜单读取权威的收藏夹归属;缺少 `fav_state` 时拒绝编辑,避免把已有归属误判为空。勾选仅修改本地草稿;新视频默认勾选第一个收藏夹。按「保存」才计算新增 / 移出差量,无变化时直接关闭。明确收到 `code=0` 才确认成功,随后刷新已经打开过的收藏库。
保存失败、取消在途保存或网络中断都可能产生不确定结果,界面不会自动重发写入;先重新读取状态,再允许编辑保存。关闭菜单和取消请求不能撤回已送达服务端的操作。切换账号、切换视频和关闭菜单后,旧响应不能改变当前界面。
收藏夹接口的 `data:null` 既可能是空账号,也可能是登录失效,因此额外调用同一账号绑定的 `/x/web-interface/nav`;确认 `isLogin=true` 且 UID 一致后才展示空收藏夹。其他格式错误与空结果分别处理。
## 会话边界与验证
请求创建时要求 API 域可用的 `DedeUserID` 与预期 UID 匹配,并有非空 `SESSDATA`;写入同时捕获该会话的 `bili_jct`。网络发送前检查 Cookie 代次,退出或替换账号后拒绝排队中的旧请求。账号请求与表单写入禁用重定向和连接自动重试。图片与视频 CDN 不接收会话 Cookie 或 CSRF。
2026-11-05 依据公开 `bilibili-api-python` 17.4.2 源码静态核对参数,未安装或执行该库。匿名探测确认未登录的状态接口返回 `-101`,并观察到收藏夹接口的 `data:null` 行为。解析、保存状态机、账号竞态和遥控器导航已用固定数据测试;真实账号的收藏夹读取、收藏 / 取消及其他官方客户端同步仍待实测。
+3 -1
View File
@@ -10,8 +10,10 @@ At a typical 960 × 540 dp TV viewport, the home screen has 38 dp horizontal and
- Search: the header entry opens a separate screen while preserving Home. Confirm on the text field opens the system IME; its Search action, Enter, or the explicit search button submits. Typing alone never requests results. Down moves to the selected video/movie/bangumi filter, then into the four/five-column result grid. Results use the existing details/episode/player flow. Back first hides the keyboard, then returns from the grid to the selected filter, then closes search. Clear returns to the input. Closing clears the transient query and results; there is no search history. - Search: the header entry opens a separate screen while preserving Home. Confirm on the text field opens the system IME; its Search action, Enter, or the explicit search button submits. Typing alone never requests results. Down moves to the selected video/movie/bangumi filter, then into the four/five-column result grid. Results use the existing details/episode/player flow. Back first hides the keyboard, then returns from the grid to the selected filter, then closes search. Clear returns to the input. Closing clears the transient query and results; there is no search history.
- Details: first episode receives focus after loading. Confirm starts playback. Multi-part videos and series have an episode grid. Back closes the dialog. - Details: first episode receives focus after loading. Confirm starts playback. Multi-part videos and series have an episode grid. Back closes the dialog.
- Login: QR code is generated locally with ZXing, not uploaded to a QR service. Refresh and close are D-pad targets. Closing cancels the parent-owned poll task. No password input is present. - Login: QR code is generated locally with ZXing, not uploaded to a QR service. Refresh and close are D-pad targets. Closing cancels the parent-owned poll task. No password input is present.
- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up reveals controls and focuses the top-right quality action; confirm opens its menu. Down returns focus to the video. Back exits playback directly. Both key-down and key-up are consumed so Android PlayerView cannot apply the same event twice. Controls remain visible when paused/end/error, while the quality action is focused or while its menu is open, and otherwise hide after four seconds during playback. - Favorites: a fourth tab, 「我的收藏」, appears only while logged in. A horizontal folder row sits above a four-column landscape grid. Confirm selects a folder or opens a video; Down from the tab scrolls the selected folder into view and focuses it. Back from videos returns to the selected folder, then to the tab. Folder changes reset the video scroll; pagination retains focus during loading and then focuses the first appended card. Empty folders, filtered pages, failed requests and accounts with no folders have explicit states.
- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up reveals controls and focuses the top-right quality action; left/right then move between quality and favorites, and confirm opens the focused action. Down returns focus to the video. Back exits playback directly. Both key-down and key-up are consumed for playback commands so Android PlayerView cannot apply the same event twice. Controls remain visible when paused/end/error, while a top action is focused or its menu is open, and otherwise hide after four seconds during playback.
- Quality menu: the current option is marked and receives focus, scrolling into view if necessary. Up/down navigate and confirm selects. Back/Close returns focus to the quality action. Only actual compatible tracks are shown; a single available option is explained. Changes briefly rebuffer at the same position and retain pause/play intent. An in-flight change disables duplicate selection; failure attempts the original quality once and reports recovery after it is ready. Choosing the current option closes without reloading. This is manual selection; each new video starts at the default quality and there is no automatic bitrate adaptation. - Quality menu: the current option is marked and receives focus, scrolling into view if necessary. Up/down navigate and confirm selects. Back/Close returns focus to the quality action. Only actual compatible tracks are shown; a single available option is explained. Changes briefly rebuffer at the same position and retain pause/play intent. An in-flight change disables duplicate selection; failure attempts the original quality once and reports recovery after it is ready. Choosing the current option closes without reloading. This is manual selection; each new video starts at the default quality and there is no automatic bitrate adaptation.
- Favorite menu: the player's favorite action reads 「收藏」 or 「已收藏」; guests receive a login prompt. Existing memberships are checked, or the first folder is selected as a draft for a new video. Confirm toggles independent folder choices; Down from the final choice reaches Save. Only Save submits additions/removals, including removal from all folders. Saving disables duplicate choices/submission while Back/Close can dismiss. A failed or uncertain write requires Reload before another Save. Closing restores the favorite action after actual window focus returns. Folder creation/rename/deletion and season following are outside this screen's scope.
- App backgrounding pauses the player; foregrounding resumes only if it was previously playing. Leaving the player releases Media3 and screen-on state. - App backgrounding pauses the player; foregrounding resumes only if it was previously playing. Leaving the player releases Media3 and screen-on state.
Search remains composed beneath details and playback, with focus/clicks disabled while inactive. Returning restores the selected result and scroll position. Load more retains its focus during the request, then moves focus to the first appended result. If the final page adds no items, focus returns to the last result. Empty, error, risk-control and loading states do not use placeholder search results. Search remains composed beneath details and playback, with focus/clicks disabled while inactive. Returning restores the selected result and scroll position. Load more retains its focus during the request, then moves focus to the first appended result. If the final page adds no items, focus returns to the last result. Empty, error, risk-control and loading states do not use placeholder search results.
+13 -1
View File
@@ -1,6 +1,6 @@
# 验证记录 # 验证记录
记录范围:2026-11-03 至 2026-11-04。 记录范围:2026-11-03 至 2026-11-05。
## v0.1.0-alpha 已验证 ## v0.1.0-alpha 已验证
@@ -56,6 +56,18 @@
- 实际匿名投稿视频曾从 480P 切到 360P,画面和进度继续推进至 `00:42 / 03:31`。后续双向切换与暂停状态的完整复测未完成:模拟器出现绿屏、Codec2 超时和宿主图形缓冲错误,重新启动后的首次播放也能复现,尚未完成原因隔离。单元测试通过不代表真实解码、音画同步和所有清晰度已经端到端验证。 - 实际匿名投稿视频曾从 480P 切到 360P,画面和进度继续推进至 `00:42 / 03:31`。后续双向切换与暂停状态的完整复测未完成:模拟器出现绿屏、Codec2 超时和宿主图形缓冲错误,重新启动后的首次播放也能复现,尚未完成原因隔离。单元测试通过不代表真实解码、音画同步和所有清晰度已经端到端验证。
- 本轮 ADB 连接目标电视超时,未把本功能覆盖安装到电视;最终实机双向切换、暂停后切换和高档位解码仍待验证。用户决定先提交为 `v0.1.2`,晚上进行电视实机验证;应用版本号更新为 `0.1.2`,Android `versionCode` 递增为 `3`,既有 `v0.1.1` 标签保留。 - 本轮 ADB 连接目标电视超时,未把本功能覆盖安装到电视;最终实机双向切换、暂停后切换和高档位解码仍待验证。用户决定先提交为 `v0.1.2`,晚上进行电视实机验证;应用版本号更新为 `0.1.2`,Android `versionCode` 递增为 `3`,既有 `v0.1.1` 标签保留。
## v0.1.2 后续部署
- 用户开启电视后,已将 `v0.1.2` 覆盖安装到 `192.168.1.20:5555`;设备确认 `versionName=0.1.2`、`versionCode=3`,启动返回 `Status: ok`。之后 ADB 离线;安装成功不等于清晰度双向切换和真实遥控器已验证。
## v0.1.3 收藏功能 — 2026-11-05
- 开发版构建、Android Lint 和 `git diff --check` 通过。用户确认按 `v0.1.3` 提交,应用版本号更新为 `0.1.3` / `versionCode=4`;既有版本标签保留,本轮功能尚未安装到电视。
- JVM 测试共 96 项通过,0 失败。新增 27 项覆盖收藏 JSON 解析、Long ID、归属完整性、失效 / 不支持条目过滤、分页、账号 / API 域 CSRF 绑定、退出后的旧请求拒绝、草稿不写入、差量保存、重复提交、保存结果不确定时重新读取,以及账号 / 收藏夹 / 视频切换后的迟到响应隔离。
- Android 11 ARM64 模拟器共 21 项设备测试通过,0 失败;另有 1 项显式外网播放诊断按默认设置跳过。新增 7 项验证登录后才出现收藏页签、收藏夹与视频的返回层级、屏幕外收藏夹滚动聚焦、多选后显式保存、保存时禁止重复操作、长列表选中项可见、不确定结果要求重新加载,以及播放器顶部操作左右切换和收藏菜单关闭后的实际窗口焦点恢复。
- 播放器收藏导航测试使用本地 socket 保持缓冲,未请求外部媒体或依赖模拟器实际解码。设备测试的账号和收藏夹均为固定测试数据,不代表真实账号接口已端到端验证,也没有修改用户实际收藏。
- 官方参数通过公开库静态源码核对,匿名探测验证了未登录状态与 `data:null` 情况。真实账号收藏夹读取、添加 / 移出收藏、多个客户端同步、账号失效提示和目标电视遥控器仍待实测。当前只实现视频稿件收藏,未实现追番 / 追剧或收藏夹管理。
## 复现 ## 复现
```sh ```sh