2 Commits
Author SHA1 Message Date
loveuer a9f38d7359 feat: release v0.1.3 with video favorites 2026-11-05 14:52:31 +08:00
loveuer e8cd96eb5e feat: release v0.1.2 with playback quality selection 2026-11-04 10:44:16 +08:00
35 changed files with 2077 additions and 80 deletions

No files matched your search

+21
View File
@@ -1,5 +1,26 @@
# Changelog
## v0.1.3 — 2026-11-05
新增播放中收藏与登录后的「我的收藏」页签。
- 登录后新增「我的收藏」页签,支持切换官方账号的收藏夹、分页浏览及复用详情播放。
- 播放器新增「收藏 / 已收藏」操作,可选择多个已有收藏夹或移出收藏;只有确认「保存」才提交修改。
- 收藏请求绑定账号会话,退出或切换账号清空收藏状态并拒绝迟到结果;保存结果不确定时先重新加载,避免盲目重试。
- 完善播放器顶部操作的左右导航、收藏菜单返回焦点,以及收藏页的收藏夹 / 视频 / 页签返回层级。
- 当前支持视频稿件收藏,不含追番 / 追剧或收藏夹管理;真实账号同步仍待实测。
- 构建、Android Lint、96 项 JVM 测试和 21 项常规模拟器设备测试通过;应用版本号为 `0.1.3`,`versionCode` 递增为 `4`。
## v0.1.2 — 2026-11-04
新增播放清晰度选择;电视实机验证待进行。
- 新增遥控器清晰度菜单:播放中按上键,再确认打开;只展示当前视频实际可用的 H.264 档位。
- 手动切换保留播放进度和暂停状态,加载失败时尝试恢复原清晰度;选择当前档位不会重新加载。
- 沿用官方接口返回的清晰度名称与账号权限,默认仍选择不高于普通 1080P 的最佳档位。
- 完善清晰度菜单的窗口焦点恢复和全屏处理,沿用播放器的请求头与备用 CDN。
- 69 项 JVM 测试、14 项常规模拟器设备测试及构建、Android Lint 通过。真实视频曾成功切换;后续模拟器解码异常,完整双向切换、暂停后切换与电视实机表现仍待验证。
## v0.1.1 — 2026-11-04
新增搜索,并修复目标电视上视频服务器返回 HTTP 403 导致无法播放的问题。
+16 -6
View File
@@ -1,8 +1,8 @@
# bulubulu
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索和播放,把交互留给遥控器。
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索、收藏和播放,把交互留给遥控器。
当前版本:**v0.1.1**。
当前版本:**v0.1.3**。新增播放中收藏和登录后的「我的收藏」页签;真实账号收藏同步待实测,详见 [验证记录](docs/VALIDATION.md)。
![推荐页面](docs/screenshots/recommendation.png)
@@ -17,25 +17,34 @@
- 顶部「搜索」入口:系统输入法输入关键词,确认后搜索;支持视频 / 电影 / 番剧分类、分页和失败重试。
- 视频详情、投稿分 P、番剧选集。
- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。
- 播放中手动选择清晰度,保留播放进度和暂停状态;切换失败时尝试恢复原档位。
- 登录后出现「我的收藏」页签,按收藏夹浏览视频,支持分页、刷新和播放。
- 播放中把视频保存到一个或多个已有收藏夹,或取消收藏;勾选只是草稿,按「保存」才同步到 B 站账号。
- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。
- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。目前没有弹幕、历史同步、追番管理和播放清晰度菜单。
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。目前没有弹幕、历史同步和追番管理。
## 遥控器
| 场景 | 操作 |
| --- | --- |
| 首页 / 选集 | 方向键移动,确认键选择 |
| 首页内容区 | 返回键把焦点移回当前页签 |
| 首页内容区 | 返回键把焦点移回当前页签;收藏页先返回收藏夹,再返回页签 |
| 搜索 | 确认输入框打开系统键盘,键盘搜索键或页面「搜索」提交;向下进入分类和结果 |
| 搜索结果 | 确认打开详情;返回键先收起键盘,再返回分类,最后退出搜索 |
| 弹窗 | 返回键关闭 |
| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 |
| 播放中 | 上下显示控制栏,返回退出播放器 |
| 播放中 | 上键聚焦「清晰度」,左右切换顶部操作,确认打开菜单;下键回到画面,返回退出播放器 |
| 清晰度菜单 | 上下选择,确认切换;返回关闭菜单 |
| 收藏菜单 | 上下选择收藏夹,确认勾选 / 取消,移到「保存」并确认提交;返回关闭并放弃草稿 |
在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。
清晰度菜单只列出官方接口本次实际返回的 H.264 档位,可选项取决于视频和账号权限。默认选择不高于普通 1080P 的最佳档位;手动切换会短暂重新缓冲,新视频重新使用默认选择,不自动按网速调整清晰度。
收藏接入官方账号收藏夹,当前支持视频稿件收藏;番剧 / 电影的「追番 / 追剧」属于另一套接口,尚未实现。新建、重命名或删除收藏夹请在哔哩哔哩客户端操作;失效视频和暂不支持的收藏类型会被过滤。网络中断导致保存结果不确定时,需要重新加载状态再操作。
## 构建
需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。
@@ -79,9 +88,10 @@ Cookie 通过 Android Keystore 的 AES-GCM 密钥加密,保存到禁止备份
- `core/Models.kt`:共享数据模型与可展示的错误。
- `data/`:官方接口、WBI 签名、扫码会话与加密存储。
- `search/`:临时搜索状态、取消与迟到响应隔离、跨页去重。
- `favorites/`:账号收藏库、收藏夹草稿、显式保存与迟到响应隔离。
- `ui/`:首页、搜索、登录与选集弹窗、电视焦点组件。
- `player/`:Media3 播放、备选 CDN 和遥控器控制。
- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。
- `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"
minSdk = 23
targetSdk = 34
versionCode = 2
versionName = "0.1.1"
versionCode = 4
versionName = "0.1.3"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
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,60 @@
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
package dev.bulubulu.tv.player
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.test.assertIsFocused
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performKeyInput
import androidx.test.platform.app.InstrumentationRegistry
import dev.bulubulu.tv.core.PlaybackQuality
import dev.bulubulu.tv.core.PlaybackStream
import dev.bulubulu.tv.ui.BulubuluTheme
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class QualityNavigationTest {
@get:Rule val compose = createComposeRule()
private fun quality(id: Int) = PlaybackQuality(id, "清晰度 $id", PlaybackStream("https://cdn.example/$id.m4s"))
@Test fun currentQualityGetsFocusAndRemoteSelectsNextOption() {
var selected: Int? = null
compose.setContent {
BulubuluTheme {
QualityDialog(listOf(quality(80), quality(64), quality(32)), 80, false, { selected = it.id }, {})
}
}
compose.mainClock.advanceTimeBy(300)
compose.onNodeWithTag("quality_80").assertIsFocused().performKeyInput {
keyDown(Key.DirectionDown); keyUp(Key.DirectionDown)
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
}
compose.runOnIdle { assertEquals(64, selected) }
}
@Test fun lowerCurrentQualityIsScrolledIntoViewAndBackDismisses() {
var dismissed = false
compose.setContent {
BulubuluTheme {
QualityDialog(listOf(120, 116, 112, 80, 74, 64, 32, 16).map(::quality), 16, false, {}, { dismissed = true })
}
}
compose.mainClock.advanceTimeBy(400)
compose.onNodeWithTag("quality_16").assertIsFocused()
InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
compose.runOnIdle { assertEquals(true, dismissed) }
}
@Test fun inFlightChangePreventsDuplicateSelectionAndKeepsCloseFocusable() {
compose.setContent {
BulubuluTheme { QualityDialog(listOf(quality(80), quality(32)), 80, true, {}, {}) }
}
compose.mainClock.advanceTimeBy(250)
compose.onNodeWithTag("quality_80").assertIsNotEnabled()
compose.onNodeWithTag("quality_32").assertIsNotEnabled()
compose.onNodeWithTag("quality_close").assertIsFocused()
}
}
@@ -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.VideoItem
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.ui.HomeUiState
import java.net.SocketTimeoutException
@@ -55,6 +58,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val notice = _notice.asStateFlow()
private val searchController = SearchController(viewModelScope, graph.search)
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 val feeds = mutableMapOf<ContentTab, CachedFeed>()
@@ -65,12 +74,13 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private var accountJob: Job? = null
private var logoutJob: Job? = null
private var selectedItem: VideoItem? = null
private var feedGeneration = 0L
init {
accountJob = viewModelScope.launch {
try {
val account = graph.auth.currentAccount()
_home.update { it.copy(account = account) }
applyAccount(account)
} catch (error: Exception) {
error.rethrowCancellation()
showNotice("登录状态暂时无法验证,已保留本地登录信息")
@@ -81,6 +91,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
fun selectTab(tab: ContentTab) {
if (_home.value.authBusy) return
if (tab == ContentTab.FAVORITES && _home.value.account == null) return
if (tab == _home.value.selectedTab) return
loadTab(tab)
}
@@ -91,6 +102,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private fun loadTab(tab: ContentTab, force: Boolean = false) {
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 }
_home.update {
it.copy(
@@ -106,12 +123,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
feedJob = viewModelScope.launch {
try {
val result = graph.content.loadFeed(tab)
if (request != feedGeneration) return@launch
feeds[tab] = CachedFeed(result.items.distinctBy(VideoItem::id), result.nextPage)
_home.update {
it.copy(items = feeds.getValue(tab).items, loading = false, hasMore = result.nextPage != null)
}
} catch (error: Exception) {
error.rethrowCancellation()
if (request != feedGeneration) return@launch
_home.update { it.copy(loading = false, error = userMessage(error)) }
}
}
@@ -120,11 +139,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
fun loadMore() {
val current = _home.value
if (current.loading || current.loadingMore || current.authBusy) return
if (current.selectedTab == ContentTab.FAVORITES) { libraryController.loadMore(); return }
val nextPage = feeds[current.selectedTab]?.nextPage ?: return
_home.update { it.copy(loadingMore = true, error = null) }
val request = feedGeneration
feedJob = viewModelScope.launch {
try {
val result = graph.content.loadFeed(current.selectedTab, nextPage)
if (request != feedGeneration) return@launch
val merged = (current.items + result.items).distinctBy(VideoItem::id)
// A repeated backend page must not leave an endless "load more" loop.
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) }
} catch (error: Exception) {
error.rethrowCancellation()
if (request != feedGeneration) return@launch
_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) }
when (status) {
is QrLoginStatus.Success -> {
_home.update { it.copy(account = status.account) }
applyAccount(status.account)
feeds.clear()
_login.value = LoginUiState()
refresh()
@@ -203,8 +226,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
closePlayer()
closeSearch()
feedJob?.cancel()
feedGeneration++
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 {
try {
graph.auth.logout()
@@ -257,6 +282,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
detailsJob = viewModelScope.launch {
try {
val source = graph.content.resolvePlayback(episode)
favoriteController.setVideo(episode.aid)
val heading = _details.value.details?.title.orEmpty()
_playback.value = if (heading.isNotBlank() && 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() {
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.SessionStore
import dev.bulubulu.tv.data.SearchRepository
import dev.bulubulu.tv.data.FavoriteRepository
class BulubuluApplication : Application() {
val sessionStore by lazy { SessionStore(this) }
@@ -13,4 +14,5 @@ class BulubuluApplication : Application() {
val auth by lazy { AuthRepository(http, sessionStore) }
val content by lazy { ContentRepository(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.LoginDialog
import dev.bulubulu.tv.ui.SearchScreen
import dev.bulubulu.tv.ui.FavoriteDialog
class MainActivity : ComponentActivity() {
private val model: AppViewModel by viewModels()
@@ -47,6 +48,8 @@ class MainActivity : ComponentActivity() {
val playback by model.playback.collectAsStateWithLifecycle()
val notice by model.notice.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 hadOverlay by remember { mutableStateOf(false) }
var searchFocusRestoreKey by remember { mutableIntStateOf(0) }
@@ -73,6 +76,8 @@ class MainActivity : ComponentActivity() {
focusRestoreKey = focusRestoreKey,
active = !overlay,
onSearch = model::openSearch,
favorites = favoriteLibrary,
onFavoriteFolderSelected = model::selectFavoriteFolder,
)
if (search.visible) {
SearchScreen(
@@ -95,7 +100,10 @@ class MainActivity : ComponentActivity() {
if (details.visible) {
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 ->
Surface(
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
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 = "")
@@ -27,6 +27,7 @@ data class VideoEpisode(
)
data class VideoDetails(val title: String, val description: String, val episodes: List<VideoEpisode>)
data class PlaybackStream(val url: String, val backupUrls: List<String> = emptyList())
data class PlaybackQuality(val id: Int, val label: String, val video: PlaybackStream)
data class PlaybackSource(
val title: String,
val video: PlaybackStream,
@@ -34,6 +35,8 @@ data class PlaybackSource(
val qualityLabel: String = "",
val durationMs: Long = 0,
val referer: String = "https://www.bilibili.com/",
val qualityId: Int = 0,
val qualities: List<PlaybackQuality> = emptyList(),
)
data class QrLoginCode(val url: String, val key: String)
sealed interface QrLoginStatus {
@@ -22,6 +22,8 @@ import dev.bulubulu.tv.core.ClientException
import java.util.concurrent.TimeUnit
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. */
internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJar {
private var epoch = 0L
@@ -29,6 +31,27 @@ internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJa
@Synchronized
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
fun clear() {
epoch++
@@ -100,8 +123,9 @@ class BiliHttpClient(storage: SessionCookieStore) {
// The epoch also prevents an in-flight login response restoring cookies after logout.
.addNetworkInterceptor { chain ->
val request = chain.request()
val epoch = cookies.currentEpoch()
val scopedCookies = cookies.loadForRequest(request.url)
val (epoch, scopedCookies) = cookies.requestSession(
request.url, request.tag(AccountRequestSession::class.java)?.epoch,
)
val builder = request.newBuilder().removeHeader("Cookie")
if (scopedCookies.isNotEmpty()) {
builder.header("Cookie", scopedCookies.joinToString("; ") { "${it.name}=${it.value}" })
@@ -125,18 +149,30 @@ class BiliHttpClient(storage: SessionCookieStore) {
url: String,
params: Map<String, String> = emptyMap(),
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 {
val target = officialUrl(url).newBuilder().apply {
params.forEach { (key, value) -> setQueryParameter(key, value) }
}.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 {
params.forEach { (key, value) -> add(key, value) }
}.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. */
@@ -173,7 +209,11 @@ class BiliHttpClient(storage: SessionCookieStore) {
private suspend fun requestJson(request: Request, allowedApiCodes: Set<Int>): JSONObject =
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) {
val message = when (response.code) {
412 -> "请求被哔哩哔哩风控拦截,请稍后重试或切换正常网络"
@@ -4,6 +4,7 @@ import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.FeedPage
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.core.PlaybackQuality
import dev.bulubulu.tv.core.PlaybackStream
import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode
@@ -24,6 +25,7 @@ class ContentRepository(private val http: BiliHttpClient) {
ContentTab.RECOMMEND -> recommendations(page)
ContentTab.MOVIE -> seasonIndex(seasonType = 2, page = page)
ContentTab.BANGUMI -> seasonIndex(seasonType = 1, page = page)
ContentTab.FAVORITES -> throw ClientException("请登录后打开我的收藏")
}
}
@@ -102,7 +104,9 @@ class ContentRepository(private val http: BiliHttpClient) {
}
suspend fun resolvePlayback(episode: VideoEpisode): PlaybackSource {
val common = mapOf("qn" to "80", "fnval" to "16", "fnver" to "0", "fourk" to "0")
// Ask for the available DASH ladder, but still start at no more than
// ordinary 1080P. The server enforces account rights for every URL.
val common = mapOf("qn" to "120", "fnval" to "16", "fnver" to "0", "fourk" to "1")
val response = if (episode.epId != null) {
http.getJson(
"$API/pgc/player/web/playurl",
@@ -259,19 +263,18 @@ internal object ContentJson {
}
val dash = data.optJSONObject("dash")
if (dash != null) {
val video = dash.optJSONArray("video").objects()
val candidates = dash.optJSONArray("video").objects()
.filter { stream ->
val codec = stream.optString("codecs").lowercase()
(codec.startsWith("avc1") || stream.optInt("codecid") == 7) &&
streamUrl(stream).isNotBlank()
(codec.startsWith("avc1") || (codec.isBlank() && stream.optInt("codecid") == 7)) &&
stream.optInt("id") > 0 && streamUrl(stream).isNotBlank()
}
.let { candidates ->
val standard = candidates.filter { it.optInt("id", 80) <= 80 }
(standard.ifEmpty { candidates }).maxWithOrNull(
compareBy<JSONObject> { it.optInt("height") }
.thenBy { it.optLong("bandwidth") },
)
} ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
.groupBy { it.optInt("id") }
.values.map { variants -> variants.maxBy { it.optLong("bandwidth") } }
val standard = candidates.filter { it.optInt("id") <= 80 }
val video = (standard.ifEmpty { candidates }).maxWithOrNull(
compareBy<JSONObject> { it.optInt("height") }.thenBy { it.optLong("bandwidth") },
) ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
val audio = dash.optJSONArray("audio").objects()
.filter { stream ->
(stream.optString("codecs").startsWith("mp4a") || stream.optString("codecs").isBlank()) &&
@@ -288,6 +291,11 @@ internal object ContentJson {
durationMs = data.optLong("timelength").takeIf { it > 0 }
?: (dash.optDouble("duration", 0.0) * 1_000).toLong(),
referer = referer(episode),
qualityId = quality,
qualities = candidates.sortedByDescending { it.optInt("id") }.map { candidate ->
val id = candidate.optInt("id")
PlaybackQuality(id, qualityLabel(data, id), stream(candidate))
},
)
}
val parts = data.optJSONArray("durl").objects()
@@ -305,6 +313,7 @@ internal object ContentJson {
qualityLabel = qualityLabel(data, data.optInt("quality")),
durationMs = data.optLong("timelength", part.optLong("length")),
referer = referer(episode),
qualityId = data.optInt("quality"),
)
}
throw ClientException("没有获取到可播放的视频流,请确认已登录、账号权限及所在地区")
@@ -326,6 +335,8 @@ internal object ContentJson {
}
private fun qualityLabel(data: JSONObject, quality: Int): String {
data.optJSONArray("support_formats").objects().firstOrNull { it.optInt("quality") == quality }
?.optString("new_description")?.takeIf { it.isNotBlank() }?.let { return it }
val ids = data.optJSONArray("accept_quality")
val descriptions = data.optJSONArray("accept_description")
if (ids != null && descriptions != null) {
@@ -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 }
}
@@ -4,6 +4,13 @@ package dev.bulubulu.tv.player
import androidx.media3.datasource.DefaultHttpDataSource
import dev.bulubulu.tv.data.BiliHttpClient
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.core.PlaybackStream
import androidx.media3.common.MediaItem
import androidx.media3.datasource.DataSource
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.MergingMediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
/** CDN requests must use the same browser identity as the playback API request. */
internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.Factory =
@@ -13,3 +20,16 @@ internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.
.setConnectTimeoutMs(15_000)
.setReadTimeoutMs(20_000)
.setAllowCrossProtocolRedirects(false)
internal fun playbackMediaSource(source: PlaybackSource, video: PlaybackStream = source.video): MediaSource {
val http = mediaHttpDataSourceFactory(source.referer)
val alternatives = buildMap {
put(video.url, video.backupUrls)
source.audio?.let { put(it.url, it.backupUrls) }
}
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
.createMediaSource(MediaItem.fromUri(url))
val videoSource = track(video.url)
return source.audio?.let { MergingMediaSource(true, true, videoSource, track(it.url)) } ?: videoSource
}
@@ -0,0 +1,81 @@
package dev.bulubulu.tv.player
import dev.bulubulu.tv.core.PlaybackQuality
import dev.bulubulu.tv.core.PlaybackSource
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
internal data class PlaybackCheckpoint(val positionMs: Long, val playWhenReady: Boolean)
internal data class QualitySelectionState(
val current: PlaybackQuality,
val switchingTo: PlaybackQuality? = null,
val restoring: Boolean = false,
)
/** Keeps a quality change transactional until both tracks are ready. Main-thread owned. */
internal class PlaybackQualitySwitcher(
source: PlaybackSource,
private val checkpoint: () -> PlaybackCheckpoint,
private val load: (PlaybackQuality, PlaybackCheckpoint) -> Unit,
) {
private val initial = source.qualities.firstOrNull { it.id == source.qualityId }
?: source.qualities.firstOrNull { it.video.url == source.video.url }
?: PlaybackQuality(source.qualityId, source.qualityLabel.ifBlank { "当前清晰度" }, source.video)
val options = (source.qualities + initial).distinctBy { it.id }.sortedByDescending { it.id }
private val _state = MutableStateFlow(QualitySelectionState(initial))
val state = _state.asStateFlow()
private data class Request(
val previous: PlaybackQuality,
val target: PlaybackQuality,
val checkpoint: PlaybackCheckpoint,
val restoring: Boolean = false,
)
private var pending: Request? = null
private var closed = false
fun select(id: Int): Boolean {
if (closed || pending != null || id == _state.value.current.id) return false
val target = options.firstOrNull { it.id == id } ?: return false
val request = Request(_state.value.current, target, checkpoint())
pending = request
_state.value = QualitySelectionState(request.previous, target)
return try {
load(target, request.checkpoint)
true
} catch (_: Exception) {
onFailure()
}
}
/** Returns true only after recovery is ready, so the UI can report it accurately. */
fun onReady(): Boolean {
if (closed) return false
val request = pending ?: return false
pending = null
_state.value = QualitySelectionState(if (request.restoring) request.previous else request.target)
return request.restoring
}
/** A failed new source is restored once; failure of the original source is surfaced normally. */
fun onFailure(): Boolean {
if (closed) return false
val request = pending ?: return false
if (request.restoring) {
pending = null
_state.value = QualitySelectionState(request.previous)
return false
}
pending = request.copy(restoring = true)
_state.value = QualitySelectionState(request.previous, request.previous, restoring = true)
return try {
load(request.previous, request.checkpoint)
true
} catch (_: Exception) {
pending = null
_state.value = QualitySelectionState(request.previous)
false
}
}
fun close() { closed = true; pending = null }
}
@@ -34,11 +34,14 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -47,20 +50,17 @@ import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.datasource.DataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.MergingMediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.PlayerView
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.favorites.FavoriteActionState
import dev.bulubulu.tv.ui.TvAccent
import dev.bulubulu.tv.ui.TvAction
import dev.bulubulu.tv.ui.TvMuted
@@ -69,12 +69,24 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
@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 lifecycleOwner = LocalLifecycleOwner.current
val windowFocused = LocalWindowInfo.current.isWindowFocused
val errorCallback by rememberUpdatedState(onPlaybackError)
val focusRequester = remember { FocusRequester() }
val retryFocus = 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 qualityButtonFocused by remember(source) { mutableStateOf(false) }
var focusQualityRequested by remember(source) { mutableStateOf(false) }
var isPlaying by remember(source) { mutableStateOf(false) }
var buffering by remember(source) { mutableStateOf(true) }
var ended by remember(source) { mutableStateOf(false) }
@@ -86,28 +98,35 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
var lastSeekEvent by remember(source) { mutableLongStateOf(0) }
val player = remember(context, source) {
androidx.media3.common.util.Log.setLogLevel(androidx.media3.common.util.Log.LOG_LEVEL_OFF)
val http = mediaHttpDataSourceFactory(source.referer)
val alternatives = buildMap {
put(source.video.url, source.video.backupUrls)
source.audio?.let { put(it.url, it.backupUrls) }
}
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
.createMediaSource(MediaItem.fromUri(url))
val video = track(source.video.url)
val media = source.audio?.let { MergingMediaSource(true, true, video, track(it.url)) } ?: video
ExoPlayer.Builder(context)
.setRenderersFactory(DefaultRenderersFactory(context).setEnableDecoderFallback(true))
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(10_000, 30_000, 1_000, 2_000).build())
.build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
setHandleAudioBecomingNoisy(true)
setMediaSource(media)
setMediaSource(playbackMediaSource(source))
playWhenReady = true
prepare()
}
}
DisposableEffect(player, lifecycleOwner) {
val qualitySwitcher = remember(player, source) {
PlaybackQualitySwitcher(
source,
checkpoint = { PlaybackCheckpoint(player.currentPosition.coerceAtLeast(0), player.playWhenReady) },
load = { quality, checkpoint ->
// Separate progressive tracks can change decoder dimensions/profile.
// Release the old track resources before preparing the replacement.
player.stop()
player.setMediaSource(playbackMediaSource(source, quality.video))
player.seekTo(checkpoint.positionMs)
player.playWhenReady = checkpoint.playWhenReady && lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
player.prepare()
position = checkpoint.positionMs
},
)
}
val qualityState by qualitySwitcher.state.collectAsStateWithLifecycle()
DisposableEffect(player, lifecycleOwner, qualitySwitcher) {
val listener = object : Player.Listener {
override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }
override fun onPlaybackStateChanged(state: Int) {
@@ -115,9 +134,18 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
ended = state == Player.STATE_ENDED
if (ended) controlsVisible = true
if (player.duration > 0) duration = player.duration
if (state == Player.STATE_READY && qualitySwitcher.onReady()) {
errorCallback("切换未成功,已恢复原清晰度")
}
}
override fun onPlayerError(exception: PlaybackException) {
if (qualitySwitcher.onFailure()) {
buffering = true
return
}
buffering = false
qualityMenuOpen = false
focusQualityRequested = false
val message = when (exception.errorCode) {
PlaybackException.ERROR_CODE_DECODING_FAILED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
@@ -147,6 +175,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
player.removeListener(listener)
qualitySwitcher.close()
player.release()
}
}
@@ -159,14 +188,36 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
delay(400)
}
}
LaunchedEffect(lastInteraction, isPlaying, error) {
if (isPlaying && error == null) {
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen, favoriteButtonFocused, favorite.visible) {
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen && !favoriteButtonFocused && !favorite.visible) {
delay(4_000)
controlsVisible = false
} else {
controlsVisible = true
}
}
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused, favorite.visible) {
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && !favorite.visible && error == null && windowFocused) {
delay(100)
qualityFocus.requestFocus()
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) {
if (error != null) { delay(100); retryFocus.requestFocus() }
}
@@ -184,9 +235,16 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
modifier = Modifier.fillMaxSize().background(Color.Black)
.focusRequester(focusRequester)
.onPreviewKeyEvent { event ->
if (error != null) return@onPreviewKeyEvent false
if (error != null || qualityMenuOpen || favorite.visible) return@onPreviewKeyEvent false
val native = event.nativeKeyEvent
val key = native.keyCode
// Let the focused action receive its own confirm events.
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
}
val supported = key in setOf(
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY,
@@ -208,7 +266,14 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
}
interact()
}
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> interact()
KeyEvent.KEYCODE_DPAD_UP -> {
interact()
focusQualityRequested = true
}
KeyEvent.KEYCODE_DPAD_DOWN -> {
interact()
focusRequester.requestFocus()
}
KeyEvent.KEYCODE_MEDIA_PLAY -> if (native.repeatCount == 0) { player.play(); interact() }
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (native.repeatCount == 0) { player.pause(); interact() }
else -> if (native.repeatCount == 0) togglePlayback()
@@ -240,9 +305,27 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
}
if (controlsVisible && error == null) {
Box(Modifier.fillMaxWidth().height(110.dp).align(Alignment.TopCenter).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent))))
Column(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp)) {
Row(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
Column(Modifier.weight(1f)) {
Text(source.title, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (source.qualityLabel.isNotBlank()) Text(source.qualityLabel, color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp))
Text(
when {
qualityState.restoring -> "正在恢复 ${qualityState.current.label}…"
qualityState.switchingTo != null -> "正在切换到 ${qualityState.switchingTo?.label}…"
else -> qualityState.current.label
},
color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp),
)
}
TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus)
.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(
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
@@ -259,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(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 ->
@@ -277,5 +360,21 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
}
}
}
if (qualityMenuOpen) {
QualityDialog(
options = qualitySwitcher.options,
selectedId = qualityState.current.id,
switching = qualityState.switchingTo != null,
onSelected = { quality ->
qualityMenuOpen = false
focusQualityRequested = true
interact()
if (quality.id != qualityState.current.id && !qualitySwitcher.select(quality.id)) {
errorCallback("暂时无法切换清晰度,请重试")
}
},
onDismiss = { qualityMenuOpen = false; focusQualityRequested = true; interact() },
)
}
}
}
@@ -0,0 +1,115 @@
package dev.bulubulu.tv.player
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
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.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.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalWindowInfo
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.core.PlaybackQuality
import dev.bulubulu.tv.ui.TvAction
import dev.bulubulu.tv.ui.TvMuted
import dev.bulubulu.tv.ui.TvPanel
import dev.bulubulu.tv.ui.TvText
import kotlinx.coroutines.delay
@Composable
internal fun QualityDialog(
options: List<PlaybackQuality>,
selectedId: Int,
switching: Boolean,
onSelected: (PlaybackQuality) -> Unit,
onDismiss: () -> Unit,
) {
val selectedFocus = remember { FocusRequester() }
val closeFocus = remember { FocusRequester() }
val list = rememberLazyListState()
val selectedIndex = options.indexOfFirst { it.id == selectedId }.coerceAtLeast(0)
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
) {
val view = LocalView.current
val windowFocused = LocalWindowInfo.current.isWindowFocused
LaunchedEffect(view) {
// Keep the video surface at its fullscreen size while the menu owns focus.
(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(switching, windowFocused) {
if (!windowFocused) return@LaunchedEffect
if (switching || options.isEmpty()) {
delay(100)
closeFocus.requestFocus()
} else {
list.scrollToItem(selectedIndex)
delay(100)
selectedFocus.requestFocus()
}
}
Surface(
color = TvPanel, contentColor = TvText, shape = RoundedCornerShape(22.dp),
modifier = Modifier.widthIn(max = 460.dp).fillMaxWidth(0.9f)
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)).testTag("quality_menu"),
) {
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("清晰度", fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
Text(
if (switching) "正在切换,请稍候…" else "切换后从当前进度继续",
color = TvMuted, fontSize = 14.sp,
)
LazyColumn(
state = list, modifier = Modifier.fillMaxWidth().heightIn(max = 210.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(options, key = { it.id }) { quality ->
val selected = quality.id == options.getOrNull(selectedIndex)?.id
TvAction(
quality.label + if (quality.id == selectedId) " · 当前" else "",
{ onSelected(quality) },
Modifier.fillMaxWidth().testTag("quality_${quality.id}").then(
if (selected) Modifier.focusRequester(selectedFocus) else Modifier,
),
selected = quality.id == selectedId, enabled = !switching,
)
}
}
Text(
if (options.size == 1) "当前仅提供这一档清晰度" else "可选项取决于视频、账号权限和设备兼容性",
color = TvMuted, fontSize = 12.sp,
)
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus).testTag("quality_close"))
}
}
}
}
@@ -24,6 +24,9 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
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.material3.CircularProgressIndicator
import androidx.compose.material3.Text
@@ -33,6 +36,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
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.focusProperties
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.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
@@ -55,7 +65,9 @@ import coil.compose.AsyncImage
import coil.request.ImageRequest
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.VideoItem
import dev.bulubulu.tv.favorites.FavoriteLibraryState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun BulubuluHome(
@@ -69,22 +81,49 @@ fun BulubuluHome(
focusRestoreKey: Int = 0,
active: Boolean = true,
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 accountFocus = remember { FocusRequester() }
val refreshFocus = remember { FocusRequester() }
val searchFocus = remember { 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}") }
val recommendGrid = rememberLazyGridState()
val movieGrid = rememberLazyGridState()
val bangumiGrid = rememberLazyGridState()
val favoritesGrid = rememberLazyGridState()
val gridState = when (state.selectedTab) {
ContentTab.RECOMMEND -> recommendGrid
ContentTab.MOVIE -> movieGrid
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 logoutConfirmation by remember { mutableStateOf(false) }
LaunchedEffect(focusRestoreKey, active) {
@@ -95,9 +134,18 @@ fun BulubuluHome(
lastFocusToken == "account" -> accountFocus.requestFocus()
lastFocusToken == "refresh" -> refreshFocus.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:") -> {
val prefix = "item:${state.selectedTab.name}:"
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
val prefix = "item:$itemScope:"
val index = content.items.indexOfFirst { prefix + it.id == lastFocusToken }
if (index >= 0) {
gridState.scrollToItem(index)
delay(100)
@@ -107,7 +155,26 @@ fun BulubuluHome(
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) {
Column(
@@ -117,10 +184,16 @@ fun BulubuluHome(
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
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()) {
ContentTab.entries.forEach { tab ->
TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab)).onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab)
visibleTabs.forEach { tab ->
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))
@@ -129,7 +202,7 @@ fun BulubuluHome(
if (state.authBusy) {
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
} 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 {
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.MOVIE -> "电影"
ContentTab.BANGUMI -> "番剧"
ContentTab.FAVORITES -> favorites.folders.firstOrNull { it.id == favorites.selectedFolderId }?.title ?: "我的收藏"
},
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))
when {
state.loading && state.items.isEmpty() -> {
content.loading && content.items.isEmpty() -> {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.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) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(state.error ?: "暂时没有内容", color = TvText, fontSize = 18.sp)
TvAction("重新加载", onRefresh)
Text(content.error ?: if (isFavorites) {
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),
modifier = Modifier.weight(1f).fillMaxWidth().onFocusChanged { gridHasFocus = it.hasFocus }.focusGroup(),
) {
items(state.items, key = { it.id }) { item ->
val focusToken = "item:${state.selectedTab.name}:${item.id}"
items(content.items, key = { it.id }) { item ->
val focusToken = "item:$itemScope:${item.id}"
VideoCard(
item = item,
portrait = state.selectedTab != ContentTab.RECOMMEND,
portrait = portrait,
focusRequester = cardFocus.getOrPut(focusToken) { FocusRequester() },
onFocused = { lastFocusToken = focusToken },
onClick = { onItemSelected(item) },
@@ -188,10 +288,13 @@ fun BulubuluHome(
}
item(span = { GridItemSpan(columns) }, key = "load-more") {
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 {
state.loadingMore -> CircularProgressIndicator(Modifier.size(26.dp), color = TvAccent, strokeWidth = 2.dp)
state.hasMore -> TvAction(if (state.error == null) "加载更多" else "重试", onLoadMore)
content.loadingMore || content.hasMore -> TvAction(
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)
}
}
@@ -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,71 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.core.VideoEpisode
import dev.bulubulu.tv.data.ContentJson
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
class PlaybackQualityJsonTest {
private val episode = VideoEpisode("p1", "P1", "视频", bvid = "BV1test", cid = 123)
@Test fun advertisedButUnavailableQualitiesAreNotSelectable() {
val source = parse("""{
"quality":64,"accept_quality":[112,80,64,32,16],
"accept_description":["1080P+","1080P","720P","480P","360P"],
"dash":{"video":[${video(32, 480)},${video(16, 360)}],"audio":[$audio]}
}""")
assertEquals(listOf(32, 16), source.qualities.map { it.id })
assertEquals(32, source.qualityId)
assertEquals("480P", source.qualityLabel)
}
@Test fun onlyCompatibleTracksAreKeptAndDuplicateRenditionsAreCombined() {
val higherBitrate = JSONObject(video(64, 720)).put("bandwidth", 2_000).put("baseUrl", "https://cdn.example/better.m4s")
.put("backupUrl", org.json.JSONArray("""["https://backup.example/better.m4s"]"""))
val source = parse("""{"dash":{"video":[
${video(80, 1080, "hvc1.1.6", 12)},${video(74, 720, "av01.0.08", 13)},
${video(64, 720)},$higherBitrate,${video(16, 360)}
],"audio":[$audio]}}""")
assertEquals(listOf(64, 16), source.qualities.map { it.id })
assertEquals("https://cdn.example/better.m4s", source.video.url)
assertEquals(listOf("https://backup.example/better.m4s"), source.qualities.first().video.backupUrls)
}
@Test fun higherAvailableQualitiesAreOfferedButDefaultRemainsOrdinary1080p() {
val source = parse("""{"support_formats":[{"quality":112,"new_description":"1080P 高码率"}],
"dash":{"video":[${video(120, 2160)},${video(112, 1080)},${video(80, 1080)},${video(32, 480)}],"audio":[$audio]}}
""")
assertEquals(80, source.qualityId)
assertEquals(listOf(120, 112, 80, 32), source.qualities.map { it.id })
assertEquals("1080P 高码率", source.qualities.first { it.id == 112 }.label)
}
@Test fun brokenAndContradictoryCodecTracksCannotBecomeOptions() {
val invalid = JSONObject(video(80, 1080)).put("baseUrl", "file:///private/data")
val source = parse("""{"dash":{"video":[
${video(80, 1080, "hvc1.1.6", 7)},$invalid,${video(16, 360)}
],"audio":[$audio]}}""")
assertEquals(listOf(16), source.qualities.map { it.id })
}
@Test fun missingAacIsRejectedForEveryQuality() {
try {
parse("""{"dash":{"video":[${video(80, 1080)}],"audio":[]}}""")
fail("A silent source must not be offered")
} catch (_: ClientException) { }
}
@Test fun progressiveSourceKeepsItsActualQuality() {
val source = parse("""{"quality":32,"durl":[{"url":"https://cdn.example/file.mp4"}]}""")
assertEquals(32, source.qualityId)
assertEquals("480P", source.qualityLabel)
assertTrue(source.qualities.isEmpty())
}
private fun parse(value: String) = ContentJson.playback(JSONObject(value), episode)
private fun video(id: Int, height: Int, codec: String = "avc1.64001f", codecId: Int = 7) =
"""{"id":$id,"height":$height,"bandwidth":1000,"codecs":"$codec","codecid":$codecId,"baseUrl":"https://cdn.example/$id.m4s"}"""
private val audio = """{"codecs":"mp4a.40.2","baseUrl":"https://cdn.example/audio.m4s"}"""
}
@@ -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)
}
}
@@ -0,0 +1,101 @@
package dev.bulubulu.tv.player
import dev.bulubulu.tv.core.PlaybackQuality
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.core.PlaybackStream
import org.junit.Assert.*
import org.junit.Test
class PlaybackQualitySwitcherTest {
private val hd = PlaybackQuality(80, "1080P", PlaybackStream("https://cdn.example/hd.m4s"))
private val low = PlaybackQuality(32, "480P", PlaybackStream("https://cdn.example/low.m4s"))
private val source = PlaybackSource("投稿", hd.video, qualityLabel = hd.label, qualityId = hd.id, qualities = listOf(hd, low))
@Test fun selectionKeepsPositionAndOnlyCommitsAfterTracksAreReady() {
val checkpoint = PlaybackCheckpoint(94_600, true)
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
assertTrue(switcher.select(32))
assertEquals(listOf(low to checkpoint), loaded)
assertEquals(hd, switcher.state.value.current)
assertEquals(low, switcher.state.value.switchingTo)
assertFalse(switcher.onReady())
assertEquals(low, switcher.state.value.current)
assertNull(switcher.state.value.switchingTo)
}
@Test fun switchingPausedVideoDoesNotStartPlayback() {
var captured: PlaybackCheckpoint? = null
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(120_000, false) }) { _, at -> captured = at }
switcher.select(32)
assertEquals(PlaybackCheckpoint(120_000, false), captured)
switcher.onReady()
assertEquals(32, switcher.state.value.current.id)
}
@Test fun currentUnknownAndOverlappingChoicesDoNotReload() {
var requests = 0
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(100, true) }) { _, _ -> requests++ }
assertFalse(switcher.select(80))
assertFalse(switcher.select(120))
assertTrue(switcher.select(32))
assertFalse(switcher.select(80))
assertFalse(switcher.select(32))
assertEquals(1, requests)
}
@Test fun failedNewQualityRestoresOriginalProgressAndPausedStateOnce() {
val checkpoint = PlaybackCheckpoint(81_300, false)
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
switcher.select(32)
assertTrue(switcher.onFailure())
assertTrue(switcher.state.value.restoring)
assertEquals(listOf(low to checkpoint, hd to checkpoint), loaded)
assertTrue(switcher.onReady())
assertEquals(hd, switcher.state.value.current)
assertFalse(switcher.state.value.restoring)
assertNull(switcher.state.value.switchingTo)
assertFalse(switcher.onFailure())
}
@Test fun recoveryFailureIsSurfacedWithoutRetryLoop() {
var requests = 0
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(30_000, true) }) { _, _ -> requests++ }
switcher.select(32)
assertTrue(switcher.onFailure())
assertFalse(switcher.onFailure())
assertEquals(2, requests)
assertNull(switcher.state.value.switchingTo)
}
@Test fun closingRejectsLateCallbacksAndNewRequests() {
var requests = 0
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(0, true) }) { _, _ -> requests++ }
switcher.select(32)
switcher.close()
assertFalse(switcher.onReady())
assertFalse(switcher.onFailure())
assertFalse(switcher.select(80))
assertEquals(hd, switcher.state.value.current)
assertEquals(1, requests)
}
@Test fun progressiveVideoHasOneHonestChoice() {
val progressive = source.copy(qualities = emptyList())
val switcher = PlaybackQualitySwitcher(progressive, { PlaybackCheckpoint(0, true) }) { _, _ -> error("Unexpected reload") }
assertEquals(listOf(hd), switcher.options)
assertFalse(switcher.select(80))
}
@Test fun synchronousSourceFailureAlsoAttemptsRecovery() {
val loaded = mutableListOf<Int>()
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(42_000, true) }) { quality, _ ->
loaded += quality.id
if (quality.id == 32) throw IllegalArgumentException("invalid source")
}
assertTrue(switcher.select(32))
assertEquals(listOf(32, 80), loaded)
assertTrue(switcher.onReady())
}
}
+4
View File
@@ -9,8 +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`.
- `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.
- `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.
- `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.
- `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.
+2 -1
View File
@@ -7,6 +7,7 @@
- HTTP 层每一跳重新计算 Cookie,严格遵守域名、路径、有效期,并且仅向 HTTPS 的 `bilibili.com` 及其子域发送。图片/CDN、第三方和 HTTP 不会收到会话 Cookie。
- 退出登录先立即删除本地会话,再用隔离的旧会话尽力调用官方注销接口。该请求迟到也不会删除之后的新登录。Cookie 代次保护还可避免旧网络响应覆盖已验证的新账号。
- 只有官方明确返回未登录时清理失效凭据。网络失败、HTTP 412 风控和服务器错误不会触发删除登录状态。
- 收藏读写绑定请求创建时的账号 Cookie 代次;发送前重新检查,退出或账号替换后的旧请求会失败,不能携带新账号凭据提交。写入还要求匹配 UID、SESSDATA 和 API 域可用的 `bili_jct`,关闭重定向与连接自动重试;CSRF 不发送给图片或媒体服务器。
- 没有统计 SDK、崩溃上传、口令输入、刷新令牌上传或自动升级器。没有实现 Cookie 自动续期;失效后重新扫码。
验证范围:官方匿名 nav 和 QR 生成接口已成功做只读探测。未使用用户账号完成扫码,也未在电视上安装。单元测试覆盖 Cookie 域名/路径/HTTPS/过期/替换、退出登录竞态,以及 JSON API URL 限制。Keystore 加密需要真机或 Android 模拟器验证,普通 JVM 单元测试不能代替。
验证范围:官方匿名 nav 和 QR 生成接口已成功做只读探测。应用已部署到目标电视;开发测试未使用真实账号完成扫码或收藏写入。单元测试覆盖 Cookie 域名/路径/HTTPS/过期/替换、退出登录竞态、JSON API URL 限制,以及收藏请求的账号 / CSRF 绑定。Android 模拟器已验证 Keystore 密文重建和篡改拒绝;真实账号的端到端验证仍待进行。
+4
View File
@@ -13,6 +13,10 @@
播放请求按普通 Web 客户端获取服务端允许的视频流,优先选择不高于常规 1080P 的 H.264 与 AAC,适合已知的 32 位 ARM Android 11 电视。清晰度由实际返回的轨道决定,登录和会员权益仍以 B 站接口结果为准。HTTP 图片/CDN链接升级到 HTTPS。
播放接口使用 `qn=120`、`fnval=16`、`fourk=1` 请求账号可用的 DASH 档位,首次播放仍优先选择不高于普通 1080P 的轨道。请求高档位不会预先下载该档位媒体,也不会扩大账号权益。菜单按实际 `dash.video` 中的 H.264 轨道生成,同一清晰度的重复轨道取码率较高的一条,并保留官方备用地址;音频复用本次返回的 AAC 轨道。只有单文件 progressive 时只显示当前一档。
清晰度名称优先读取 `support_formats[].new_description`,其次读取 `accept_description`,最后使用已知档位名称。`accept_quality` 和 `support_formats` 仅供描述,不能证明账号实际拿到了对应视频流。2026-11-04 匿名只读探测中,响应曾声明 1080P 高码率、1080P、720P 等档位,但实际 H.264 视频只有 480P / 360P;菜单据此只提供这两档。非 H.264、无有效 HTTPS 地址的轨道不会成为选项,会员、试看和 DRM 检查保持原有处理。
获取播放地址和下载音视频必须共用 `BiliHttpClient.USER_AGENT`。播放器的独立 HTTP 数据源由 `mediaHttpDataSourceFactory` 创建,携带内容 Referer,保留 Range 请求,不携带账号 Cookie。2026-11-04 目标电视对照验证:旧 Android 播放器标识使多个 CDN 返回 HTTP 403;同一批地址改用接口的浏览器标识后,三个视频地址及三个音频地址均可读取 MP4 数据。
`PlaybackNetworkDiagnosticTest` 提供显式启用的真实网络诊断,默认测试不访问外部服务。它使用独立匿名内存会话,比较旧标识和生产数据源,仅报告 CDN 主机、状态码和媒体文件头,不读取用户登录状态,不输出 Cookie 或带签名的完整地址。
+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` 行为。解析、保存状态机、账号竞态和遥控器导航已用固定数据测试;真实账号的收藏夹读取、收藏 / 取消及其他官方客户端同步仍待实测。
+4 -1
View File
@@ -10,7 +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.
- 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.
- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up/down display controls. 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 and 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.
- 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.
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.
+22 -2
View File
@@ -1,6 +1,6 @@
# 验证记录
记录范围:2026-11-03 至 2026-11-04。
记录范围:2026-11-03 至 2026-11-05。
## v0.1.0-alpha 已验证
@@ -48,11 +48,31 @@
- 此次构建、55 项 JVM 测试和 Android Lint 通过。新增的真实网络诊断默认跳过,须传入 `livePlayback=true` 显式启用。
- 用户实测后确认播放恢复正常,并同意提交为 `v0.1.1`;应用版本号为 `0.1.1`,Android `versionCode` 递增为 `2`。
## v0.1.2 清晰度选择 — 2026-11-04
- 匿名官方播放接口探测确认可取得多档 DASH 视频流;`qn=120`、`fnval=16`、`fourk=1` 请求成功,但账号无权取得的档位仍不会返回。样本中的 `accept_quality` 声明了 1080P / 720P 等档位,实际 H.264 轨道只有 480P / 360P;菜单以实际轨道为准。
- 开发版构建、Android Lint 和 69 项 JVM 测试通过,0 失败。新增 6 项解析测试和 8 项切换状态测试,覆盖实际轨道与声明档位的区别、编码过滤、重复轨道、默认清晰度、备用地址、位置与暂停意图保持、就绪后才提交选择、重复请求隔离、失败恢复和关闭后迟到回调。
- Android 11 ARM64 模拟器的 14 项常规设备测试通过,0 失败;另有 1 项显式网络诊断按默认设置跳过。新增 3 项清晰度菜单测试验证当前档位焦点、方向键选择、长列表滚动、返回关闭以及切换期间禁止重复选择。
- 实际匿名投稿视频曾从 480P 切到 360P,画面和进度继续推进至 `00:42 / 03:31`。后续双向切换与暂停状态的完整复测未完成:模拟器出现绿屏、Codec2 超时和宿主图形缓冲错误,重新启动后的首次播放也能复现,尚未完成原因隔离。单元测试通过不代表真实解码、音画同步和所有清晰度已经端到端验证。
- 本轮 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
./gradlew assembleDebug testDebugUnitTest lintDebug
ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest
ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest -Pandroid.injected.device.serial=emulator-5580
```
设备测试需要已启动的模拟器。测试使用独立存储目录和假测试会话,不需要用户账号;Gradle 的 connected 测试任务可能在结束后移除测试安装的 APK。如需继续查看,运行 `./scripts/preview.sh` 重新部署到预览模拟器。