Compare commits
1
Commits
v0.1.0-alpha
...
v0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93f1221e6a |
No files matched your search
@@ -1,5 +1,16 @@
|
||||
# Changelog
|
||||
|
||||
## v0.1.1 — 2026-11-04
|
||||
|
||||
新增搜索,并修复目标电视上视频服务器返回 HTTP 403 导致无法播放的问题。
|
||||
|
||||
- 修复播放接口与播放器 User-Agent 不一致导致多个 CDN 返回 HTTP 403、视频无法播放的问题。
|
||||
- 顶部新增搜索入口,系统输入法输入,确认后请求官方视频 / 电影 / 番剧搜索。
|
||||
- 支持结果分页、去重、失败重试和空结果;风控挑战单独提示。
|
||||
- 复用详情、选集和播放,返回恢复搜索结果焦点;关闭搜索清空临时内容,不保存历史。
|
||||
- 取消或切换查询后隔离迟到响应,退出登录时清除搜索状态。
|
||||
- 55 项 JVM 测试、11 项模拟器设备测试及显式实机网络诊断通过;目标电视已验证 1080P 短时播放,用户确认恢复正常。
|
||||
|
||||
## v0.1.0-alpha — 2026-11-03
|
||||
|
||||
第一个可以构建并在模拟器运行的个人使用版本。
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
# bulubulu
|
||||
|
||||
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧和播放,把交互留给遥控器。
|
||||
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索和播放,把交互留给遥控器。
|
||||
|
||||
当前版本:**v0.1.0-alpha**。
|
||||
当前版本:**v0.1.1**。
|
||||
|
||||

|
||||
|
||||
## 第一版已有
|
||||
搜索页面:
|
||||
|
||||

|
||||
|
||||
## 已有功能
|
||||
|
||||
- 使用哔哩哔哩手机客户端扫码并确认登录,不输入账号密码。
|
||||
- 推荐视频、电影和番剧三个页签,接入真实官方接口,支持刷新和分页。
|
||||
- 顶部「搜索」入口:系统输入法输入关键词,确认后搜索;支持视频 / 电影 / 番剧分类、分页和失败重试。
|
||||
- 视频详情、投稿分 P、番剧选集。
|
||||
- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。
|
||||
- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。
|
||||
- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。
|
||||
|
||||
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。第一版没有搜索、弹幕、历史同步、追番管理和播放清晰度菜单。
|
||||
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。目前没有弹幕、历史同步、追番管理和播放清晰度菜单。
|
||||
|
||||
## 遥控器
|
||||
|
||||
@@ -23,6 +28,8 @@
|
||||
| --- | --- |
|
||||
| 首页 / 选集 | 方向键移动,确认键选择 |
|
||||
| 首页内容区 | 返回键把焦点移回当前页签 |
|
||||
| 搜索 | 确认输入框打开系统键盘,键盘搜索键或页面「搜索」提交;向下进入分类和结果 |
|
||||
| 搜索结果 | 确认打开详情;返回键先收起键盘,再返回分类,最后退出搜索 |
|
||||
| 弹窗 | 返回键关闭 |
|
||||
| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 |
|
||||
| 播放中 | 上下显示控制栏,返回退出播放器 |
|
||||
@@ -63,15 +70,18 @@ Cookie 通过 Android Keystore 的 AES-GCM 密钥加密,保存到禁止备份
|
||||
|
||||
扫码使用独立内存会话,确认并验证账号后才保存;取消扫码会作废该尝试。退出先清除本地凭据,再尝试注销旧的官方会话。过期或迟到的网络响应不能把旧会话恢复回来。错误提示不会展示带签名的播放地址或原始网络异常。
|
||||
|
||||
这不代表第三方客户端可以保证永久兼容:官方网页接口、风控和账号协议可能变化,目标电视的解码和遥控器还需实机检查。当前没有在用户电视上安装。
|
||||
搜索关键词只在提交时发给 B 站官方接口,不逐字上传,不保存本地搜索历史,关闭搜索页即清空。首次搜索可能访问官方首页获取正常的网站 Cookie,只接收响应头,不执行网页脚本。系统输入法的联网和隐私行为取决于设备安装的输入法。
|
||||
|
||||
这不代表第三方客户端可以保证永久兼容:官方网页接口、风控和账号协议可能变化。已于 2026-11-04 在目标电视安装包含搜索功能的开发版,并修复 CDN 请求头不一致导致的 HTTP 403,实机验证了 1080P 短时播放。完整遥控器、输入法和长期播放表现仍需实测。
|
||||
|
||||
## 项目结构
|
||||
|
||||
- `core/Models.kt`:共享数据模型与可展示的错误。
|
||||
- `data/`:官方接口、WBI 签名、扫码会话与加密存储。
|
||||
- `ui/`:首页、登录与选集弹窗、电视焦点组件。
|
||||
- `search/`:临时搜索状态、取消与迟到响应隔离、跨页去重。
|
||||
- `ui/`:首页、搜索、登录与选集弹窗、电视焦点组件。
|
||||
- `player/`:Media3 播放、备选 CDN 和遥控器控制。
|
||||
- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。
|
||||
- `docs/`:接口说明、设计说明和真实运行截图。
|
||||
|
||||
接口与权限限制见 [CONTENT_API.md](docs/CONTENT_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),登录实现见 [AUTH.md](docs/AUTH.md),界面说明见 [UI.md](docs/UI.md)。验证结果记录在 [VALIDATION.md](docs/VALIDATION.md)。
|
||||
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "dev.bulubulu.tv"
|
||||
minSdk = 23
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "0.1.0-alpha"
|
||||
versionCode = 2
|
||||
versionName = "0.1.1"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
buildFeatures { compose = true; buildConfig = true }
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
|
||||
package dev.bulubulu.tv
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.datasource.DefaultHttpDataSource
|
||||
import androidx.media3.datasource.HttpDataSource
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import dev.bulubulu.tv.core.ContentTab
|
||||
import dev.bulubulu.tv.data.BiliHttpClient
|
||||
import dev.bulubulu.tv.data.ContentRepository
|
||||
import dev.bulubulu.tv.data.InMemorySessionCookieStore
|
||||
import dev.bulubulu.tv.player.mediaHttpDataSourceFactory
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** Explicit opt-in live diagnostic. Uses anonymous memory cookies, never the user's account. */
|
||||
class PlaybackNetworkDiagnosticTest {
|
||||
@Test fun compareMediaRequestsOnDevice() = runBlocking {
|
||||
assumeTrue(InstrumentationRegistry.getArguments().getString("livePlayback") == "true")
|
||||
fun report(message: String) {
|
||||
InstrumentationRegistry.getInstrumentation().sendStatus(0, Bundle().apply {
|
||||
putString("stream", "\nBuluMediaProbe $message\n")
|
||||
})
|
||||
}
|
||||
try {
|
||||
val repository = ContentRepository(BiliHttpClient(InMemorySessionCookieStore()))
|
||||
val item = repository.loadFeed(ContentTab.RECOMMEND).items.first { it.bvid != null }
|
||||
val episode = repository.loadDetails(item).episodes.first()
|
||||
val source = repository.resolvePlayback(episode)
|
||||
report("resolved video=${source.video.backupUrls.size + 1} audio=${source.audio?.let { it.backupUrls.size + 1 } ?: 0}")
|
||||
val factories = listOf(
|
||||
"legacy" to DefaultHttpDataSource.Factory()
|
||||
.setUserAgent("Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36")
|
||||
.setDefaultRequestProperties(mapOf("Referer" to source.referer)),
|
||||
"shared" to mediaHttpDataSourceFactory(source.referer),
|
||||
)
|
||||
for ((label, factory) in factories) {
|
||||
for ((track, stream) in listOfNotNull("video" to source.video, source.audio?.let { "audio" to it })) {
|
||||
var readable = false
|
||||
for ((index, url) in (listOf(stream.url) + stream.backupUrls).withIndex()) {
|
||||
val data = factory.setConnectTimeoutMs(8_000).setReadTimeoutMs(8_000)
|
||||
.createDataSource()
|
||||
try {
|
||||
data.open(DataSpec.Builder().setUri(url).setLength(4_096).build())
|
||||
val bytes = ByteArray(16)
|
||||
val read = data.read(bytes, 0, bytes.size)
|
||||
if (read >= 8 && bytes.copyOfRange(4, 8).contentEquals("ftyp".toByteArray(Charsets.US_ASCII))) readable = true
|
||||
val hex = bytes.take(read.coerceAtLeast(0)).joinToString("") { "%02x".format(it) }
|
||||
report("agent=$label track=$track candidate=$index host=${Uri.parse(url).host} opened=true prefix=$hex")
|
||||
} catch (error: Exception) {
|
||||
val status = (error as? HttpDataSource.InvalidResponseCodeException)?.responseCode
|
||||
report("agent=$label track=$track candidate=$index host=${Uri.parse(url).host} http=$status error=${error.javaClass.simpleName}")
|
||||
} finally { runCatching { data.close() } }
|
||||
}
|
||||
if (label == "shared") assertTrue("No readable MP4 $track candidate with production headers", readable)
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
// Exceptions may contain signed media URLs; never print or chain them.
|
||||
throw AssertionError("Live playback diagnostic failed: ${error.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
|
||||
|
||||
package dev.bulubulu.tv.ui
|
||||
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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.input.key.Key
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.SemanticsMatcher
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.hasClickAction
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class SearchNavigationTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val result = VideoItem("test", "搜索结果甲", "", "测试作者")
|
||||
|
||||
@Test fun searchEntryCanBeOpenedWithRemote() {
|
||||
var opened = false
|
||||
compose.setContent {
|
||||
BulubuluTheme {
|
||||
BulubuluHome(
|
||||
state = HomeUiState(loading = false, hasMore = false),
|
||||
onTabSelected = {}, onItemSelected = {}, onLoadMore = {}, onRefresh = {},
|
||||
onLogin = {}, onLogout = {}, onSearch = { opened = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNode(hasText("推荐") and hasClickAction()).performKeyInput {
|
||||
repeat(3) { keyDown(Key.DirectionRight); keyUp(Key.DirectionRight) }
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.onNode(hasText("搜索") and hasClickAction()).assertIsFocused()
|
||||
compose.runOnIdle { assertEquals(true, opened) }
|
||||
}
|
||||
|
||||
@Test fun chineseInputSubmitsWithImeAndResultsOpenWithRemote() {
|
||||
val state = mutableStateOf(SearchUiState(visible = true))
|
||||
var submitted = ""
|
||||
var chosen: VideoItem? = null
|
||||
compose.setContent {
|
||||
BulubuluTheme {
|
||||
TestSearch(
|
||||
state.value,
|
||||
onQuery = { state.value = state.value.copy(query = it) },
|
||||
onSearch = {
|
||||
submitted = state.value.query
|
||||
state.value = state.value.copy(submittedQuery = submitted, items = listOf(result), totalResults = 1)
|
||||
},
|
||||
onItem = { chosen = it },
|
||||
)
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("search_query").assertIsFocused().performTextInput("三体")
|
||||
compose.runOnIdle { assertEquals("", submitted) }
|
||||
compose.onNodeWithTag("search_query").performImeAction()
|
||||
compose.mainClock.advanceTimeBy(500)
|
||||
compose.onNode(hasText(result.title) and hasClickAction()).assertIsFocused().performKeyInput {
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.runOnIdle {
|
||||
assertEquals("三体", submitted)
|
||||
assertEquals(result, chosen)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun categoryCanBeChangedWithRemoteFromInput() {
|
||||
val state = mutableStateOf(SearchUiState(visible = true))
|
||||
compose.setContent {
|
||||
BulubuluTheme { TestSearch(state.value, onCategory = { state.value = state.value.copy(category = it) }) }
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("search_query").performKeyInput {
|
||||
keyDown(Key.DirectionDown); keyUp(Key.DirectionDown)
|
||||
keyDown(Key.DirectionRight); keyUp(Key.DirectionRight)
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.onNode(hasText("电影") and hasClickAction()).assertIsFocused()
|
||||
compose.runOnIdle { assertEquals(SearchCategory.MOVIE, state.value.category) }
|
||||
}
|
||||
|
||||
@Test fun detailsOverlayDisablesSearchAndRestoresResultFocus() {
|
||||
val overlay = mutableStateOf(false)
|
||||
val state = SearchUiState(visible = true, query = "测试", submittedQuery = "测试", items = listOf(result))
|
||||
compose.setContent {
|
||||
BulubuluTheme {
|
||||
Box {
|
||||
TestSearch(state, active = !overlay.value, onItem = { overlay.value = true })
|
||||
if (overlay.value) {
|
||||
val focus = remember { FocusRequester() }
|
||||
Text("详情覆盖层", Modifier.focusRequester(focus).focusable())
|
||||
LaunchedEffect(Unit) { focus.requestFocus() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("search_query").performKeyInput {
|
||||
repeat(2) { keyDown(Key.DirectionDown); keyUp(Key.DirectionDown) }
|
||||
}
|
||||
compose.onNode(hasText(result.title) and hasClickAction()).assertIsFocused().performKeyInput {
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithText("详情覆盖层").assertIsFocused()
|
||||
compose.onNodeWithTag("search_submit").assertIsNotEnabled()
|
||||
compose.runOnIdle { overlay.value = false }
|
||||
awaitFocus(hasText(result.title) and hasClickAction())
|
||||
compose.onNode(hasText(result.title) and hasClickAction()).assertIsFocused()
|
||||
}
|
||||
|
||||
@Test fun pagingRetainsRemoteFocusAndFinishingReturnsToLastResult() {
|
||||
val state = mutableStateOf(SearchUiState(visible = true, query = "测试", submittedQuery = "测试", items = listOf(result), hasMore = true))
|
||||
compose.setContent {
|
||||
BulubuluTheme { TestSearch(state.value, onLoadMore = { state.value = state.value.copy(loadingMore = true) }) }
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("search_query").performKeyInput {
|
||||
repeat(3) { keyDown(Key.DirectionDown); keyUp(Key.DirectionDown) }
|
||||
}
|
||||
compose.onNodeWithText("加载更多").assertIsFocused().performKeyInput {
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.onNodeWithText("正在加载…").assertIsFocused()
|
||||
compose.runOnIdle { state.value = state.value.copy(loadingMore = false, hasMore = false) }
|
||||
awaitFocus(hasText(result.title) and hasClickAction())
|
||||
compose.onNode(hasText(result.title) and hasClickAction()).assertIsFocused()
|
||||
}
|
||||
|
||||
@Test fun appendedPageMovesFocusToFirstNewResult() {
|
||||
val next = VideoItem("next", "下一页首个结果", "")
|
||||
val state = mutableStateOf(SearchUiState(visible = true, query = "测试", submittedQuery = "测试", items = listOf(result), hasMore = true))
|
||||
compose.setContent {
|
||||
BulubuluTheme { TestSearch(state.value, onLoadMore = { state.value = state.value.copy(loadingMore = true) }) }
|
||||
}
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
compose.onNodeWithTag("search_query").performKeyInput {
|
||||
repeat(3) { keyDown(Key.DirectionDown); keyUp(Key.DirectionDown) }
|
||||
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||
}
|
||||
compose.onNodeWithText("正在加载…").assertIsFocused()
|
||||
compose.runOnIdle { state.value = state.value.copy(items = listOf(result, next), loadingMore = false) }
|
||||
awaitFocus(hasText(next.title) and hasClickAction())
|
||||
compose.onNode(hasText(next.title) and hasClickAction()).assertIsFocused()
|
||||
}
|
||||
|
||||
private fun awaitFocus(matcher: SemanticsMatcher) {
|
||||
// Lazy-grid remeasure and the system IME run outside the Compose virtual clock.
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodes(matcher).fetchSemanticsNodes().any {
|
||||
it.config.getOrElse(SemanticsProperties.Focused) { false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TestSearch(
|
||||
state: SearchUiState,
|
||||
active: Boolean = true,
|
||||
onQuery: (String) -> Unit = {},
|
||||
onSearch: () -> Unit = {},
|
||||
onCategory: (SearchCategory) -> Unit = {},
|
||||
onItem: (VideoItem) -> Unit = {},
|
||||
onLoadMore: () -> Unit = {},
|
||||
) {
|
||||
SearchScreen(state, onQuery, onSearch, onCategory, onItem, onLoadMore, {}, {}, {}, active)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import dev.bulubulu.tv.core.QrLoginStatus
|
||||
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.search.SearchController
|
||||
import dev.bulubulu.tv.ui.HomeUiState
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
@@ -51,6 +53,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val playback = _playback.asStateFlow()
|
||||
private val _notice = MutableStateFlow<String?>(null)
|
||||
val notice = _notice.asStateFlow()
|
||||
private val searchController = SearchController(viewModelScope, graph.search)
|
||||
val search = searchController.state
|
||||
|
||||
private data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?)
|
||||
private val feeds = mutableMapOf<ContentTab, CachedFeed>()
|
||||
@@ -197,6 +201,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
dismissLogin()
|
||||
dismissDetails()
|
||||
closePlayer()
|
||||
closeSearch()
|
||||
feedJob?.cancel()
|
||||
feeds.clear()
|
||||
_home.update { it.copy(account = null, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
|
||||
@@ -266,6 +271,18 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
fun closePlayer() { _playback.value = null }
|
||||
|
||||
fun openSearch() {
|
||||
if (!_home.value.authBusy) searchController.open()
|
||||
}
|
||||
|
||||
fun closeSearch() = searchController.close()
|
||||
fun updateSearchQuery(query: String) = searchController.updateQuery(query)
|
||||
fun submitSearch() = searchController.submit()
|
||||
fun clearSearch() = searchController.clear()
|
||||
fun selectSearchCategory(category: SearchCategory) = searchController.selectCategory(category)
|
||||
fun loadMoreSearch() = searchController.loadMore()
|
||||
fun retrySearch() = searchController.retry()
|
||||
|
||||
fun playbackError(message: String) {
|
||||
showNotice(message)
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ import dev.bulubulu.tv.data.AuthRepository
|
||||
import dev.bulubulu.tv.data.BiliHttpClient
|
||||
import dev.bulubulu.tv.data.ContentRepository
|
||||
import dev.bulubulu.tv.data.SessionStore
|
||||
import dev.bulubulu.tv.data.SearchRepository
|
||||
|
||||
class BulubuluApplication : Application() {
|
||||
val sessionStore by lazy { SessionStore(this) }
|
||||
val http by lazy { BiliHttpClient(sessionStore) }
|
||||
val auth by lazy { AuthRepository(http, sessionStore) }
|
||||
val content by lazy { ContentRepository(http) }
|
||||
val search by lazy { SearchRepository(http) }
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import dev.bulubulu.tv.ui.BulubuluHome
|
||||
import dev.bulubulu.tv.ui.BulubuluTheme
|
||||
import dev.bulubulu.tv.ui.DetailsDialog
|
||||
import dev.bulubulu.tv.ui.LoginDialog
|
||||
import dev.bulubulu.tv.ui.SearchScreen
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val model: AppViewModel by viewModels()
|
||||
@@ -45,13 +46,21 @@ class MainActivity : ComponentActivity() {
|
||||
val details by model.details.collectAsStateWithLifecycle()
|
||||
val playback by model.playback.collectAsStateWithLifecycle()
|
||||
val notice by model.notice.collectAsStateWithLifecycle()
|
||||
val search by model.search.collectAsStateWithLifecycle()
|
||||
var focusRestoreKey by remember { mutableIntStateOf(0) }
|
||||
var hadOverlay by remember { mutableStateOf(false) }
|
||||
val overlay = login.visible || details.visible || playback != null || home.authBusy
|
||||
var searchFocusRestoreKey by remember { mutableIntStateOf(0) }
|
||||
var hadSearchOverlay by remember { mutableStateOf(false) }
|
||||
val secondaryOverlay = login.visible || details.visible || playback != null || home.authBusy
|
||||
val overlay = secondaryOverlay || search.visible
|
||||
LaunchedEffect(overlay) {
|
||||
if (hadOverlay && !overlay) focusRestoreKey++
|
||||
hadOverlay = overlay
|
||||
}
|
||||
LaunchedEffect(secondaryOverlay) {
|
||||
if (hadSearchOverlay && !secondaryOverlay) searchFocusRestoreKey++
|
||||
hadSearchOverlay = secondaryOverlay
|
||||
}
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
BulubuluHome(
|
||||
state = home,
|
||||
@@ -63,7 +72,23 @@ class MainActivity : ComponentActivity() {
|
||||
onLogout = model::logout,
|
||||
focusRestoreKey = focusRestoreKey,
|
||||
active = !overlay,
|
||||
onSearch = model::openSearch,
|
||||
)
|
||||
if (search.visible) {
|
||||
SearchScreen(
|
||||
state = search,
|
||||
onQueryChange = model::updateSearchQuery,
|
||||
onSearch = model::submitSearch,
|
||||
onCategorySelected = model::selectSearchCategory,
|
||||
onItemSelected = model::openDetails,
|
||||
onLoadMore = model::loadMoreSearch,
|
||||
onRetry = model::retrySearch,
|
||||
onClear = model::clearSearch,
|
||||
onBack = model::closeSearch,
|
||||
active = !secondaryOverlay,
|
||||
focusRestoreKey = searchFocusRestoreKey,
|
||||
)
|
||||
}
|
||||
if (login.visible) {
|
||||
LoginDialog(login.code, login.status, login.loading, login.error, model::startQrLogin, model::dismissLogin)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.bulubulu.tv.core
|
||||
|
||||
enum class SearchCategory(val title: String, val apiType: String, val portrait: Boolean) {
|
||||
VIDEO("视频", "video", false),
|
||||
MOVIE("电影", "media_ft", true),
|
||||
BANGUMI("番剧", "media_bangumi", true),
|
||||
}
|
||||
|
||||
data class SearchPage(
|
||||
val items: List<VideoItem>,
|
||||
val nextPage: Int?,
|
||||
val totalResults: Int? = null,
|
||||
)
|
||||
|
||||
fun interface SearchDataSource {
|
||||
suspend fun search(keyword: String, category: SearchCategory, page: Int): SearchPage
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import dev.bulubulu.tv.core.BiliApiException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.Cookie
|
||||
@@ -78,6 +80,7 @@ internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJa
|
||||
/** Official HTTPS JSON API client. The raw client is also available for ordinary network consumers. */
|
||||
class BiliHttpClient(storage: SessionCookieStore) {
|
||||
private val cookies = BiliCookieJar(storage)
|
||||
private val webSessionMutex = Mutex()
|
||||
|
||||
val client: OkHttpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
@@ -89,7 +92,7 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
||||
chain.request().newBuilder()
|
||||
.header("User-Agent", USER_AGENT)
|
||||
.header("Referer", "https://www.bilibili.com/")
|
||||
.header("Accept", "application/json")
|
||||
.header("Accept", chain.request().header("Accept") ?: "application/json")
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
@@ -136,6 +139,31 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
||||
return requestJson(Request.Builder().url(officialUrl(url)).post(body).build(), emptySet())
|
||||
}
|
||||
|
||||
/** Obtain the ordinary first-party browser cookie required by official search. */
|
||||
suspend fun prepareWebSession() = webSessionMutex.withLock {
|
||||
val api = officialUrl("https://api.bilibili.com/")
|
||||
fun ready() = cookies.loadForRequest(api).any { it.name == "buvid3" && it.value.isNotBlank() }
|
||||
if (ready()) return@withLock
|
||||
val epoch = cookies.currentEpoch()
|
||||
withContext(Dispatchers.IO) {
|
||||
val request = Request.Builder()
|
||||
.url(officialUrl("https://www.bilibili.com/"))
|
||||
.header("Accept", "text/html,application/xhtml+xml")
|
||||
.get().build()
|
||||
client.newCall(request).awaitResponse().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
throw BiliApiException(-response.code, "无法建立 B 站搜索会话,请稍后重试")
|
||||
}
|
||||
// Cookie headers have already passed the existing host/epoch checks.
|
||||
// The homepage body is deliberately never read, parsed or executed.
|
||||
}
|
||||
}
|
||||
if (cookies.currentEpoch() != epoch) {
|
||||
throw ClientException("登录状态已变化,请重新搜索")
|
||||
}
|
||||
if (!ready()) throw ClientException("B 站未返回有效的搜索会话,请稍后重试")
|
||||
}
|
||||
|
||||
fun clearSession() = cookies.clear()
|
||||
|
||||
internal fun adoptSession(newCookies: List<Cookie>) = cookies.replaceSession(newCookies)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package dev.bulubulu.tv.data
|
||||
|
||||
import dev.bulubulu.tv.core.BiliApiException
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.SearchDataSource
|
||||
import dev.bulubulu.tv.core.SearchPage
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Official search only; first-party session cookies are scoped by BiliHttpClient. */
|
||||
class SearchRepository(private val http: BiliHttpClient) : SearchDataSource {
|
||||
override suspend fun search(keyword: String, category: SearchCategory, page: Int): SearchPage {
|
||||
val normalized = keyword.trim().replace(Regex("\\s+"), " ")
|
||||
if (normalized.isBlank()) throw ClientException("请输入搜索关键词")
|
||||
if (normalized.length > 100) throw ClientException("搜索关键词过长,请控制在 100 个字符以内")
|
||||
if (page !in 1..SearchJson.MAX_PAGE) throw ClientException("搜索页码超出范围,请重新搜索")
|
||||
http.prepareWebSession()
|
||||
// The WBI search route returned a voucher challenge in live checks while
|
||||
// this official route returned genuine results with the same web session.
|
||||
val response = http.getJson(
|
||||
"https://api.bilibili.com/x/web-interface/search/type",
|
||||
mapOf(
|
||||
"keyword" to normalized,
|
||||
"search_type" to category.apiType,
|
||||
"page" to page.toString(),
|
||||
"page_size" to PAGE_SIZE.toString(),
|
||||
"order" to "totalrank",
|
||||
),
|
||||
)
|
||||
return SearchJson.parse(response, category, page)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PAGE_SIZE = 20
|
||||
}
|
||||
}
|
||||
|
||||
/** Pure response handling: a challenge or malformed response is never an empty result. */
|
||||
internal object SearchJson {
|
||||
const val MAX_PAGE = 50
|
||||
private val tagPattern = Regex("</?[A-Za-z][^>]*>")
|
||||
private val hiddenPattern = Regex("<(script|style)\\b[^>]*>.*?</\\1\\s*>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
|
||||
private val entityPattern = Regex("&(#(?:[xX][0-9a-fA-F]+|[0-9]+)|[A-Za-z]+);")
|
||||
private val whitespacePattern = Regex("[\\s\\u00a0]+")
|
||||
private val commentPattern = Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL)
|
||||
private val episodePath = Regex("(?:^|/)ep([0-9]+)(?:[/?#]|$)")
|
||||
private val seasonPath = Regex("(?:^|/)ss([0-9]+)(?:[/?#]|$)")
|
||||
|
||||
fun parse(root: JSONObject, category: SearchCategory, requestedPage: Int): SearchPage {
|
||||
if (requestedPage !in 1..MAX_PAGE) throw ClientException("搜索页码超出范围,请重新搜索")
|
||||
val code = root.longValue("code") ?: throw malformed()
|
||||
if (code != 0L) {
|
||||
throw BiliApiException(code.toInt(), root.optString("message").ifBlank { "搜索暂不可用,请稍后重试" })
|
||||
}
|
||||
val data = root.optJSONObject("data") ?: throw malformed()
|
||||
if (data.has("v_voucher") || root.has("v_voucher")) {
|
||||
throw BiliApiException(-352, "搜索请求被 B 站风控拦截,请稍后重试")
|
||||
}
|
||||
val actualPage = data.positiveInt("page") ?: throw malformed()
|
||||
val total = data.nonNegativeInt("numResults")
|
||||
val pages = data.nonNegativeInt("numPages")
|
||||
val rawResult = data.opt("result")
|
||||
val array = when {
|
||||
rawResult is JSONArray -> rawResult
|
||||
(rawResult == null || rawResult == JSONObject.NULL) && total == 0 -> JSONArray()
|
||||
else -> throw malformed()
|
||||
}
|
||||
val items = (0 until array.length()).mapNotNull { index ->
|
||||
val item = array.optJSONObject(index) ?: return@mapNotNull null
|
||||
when (category) {
|
||||
SearchCategory.VIDEO -> video(item)
|
||||
SearchCategory.MOVIE, SearchCategory.BANGUMI -> season(item, category)
|
||||
}
|
||||
}.distinctBy { it.id }
|
||||
// Explicit zero metadata is required for an empty result, not just a
|
||||
// missing array or a non-video/malformed response from an API change.
|
||||
val pageLimit = when {
|
||||
pages != null -> pages
|
||||
total != null -> {
|
||||
val size = data.positiveInt("pagesize") ?: 20
|
||||
((total.toLong() + size - 1L) / size).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
}
|
||||
else -> actualPage // Unknown pagination stops safely instead of guessing.
|
||||
}.coerceAtMost(MAX_PAGE)
|
||||
val beyondLastPage = total != null && total > 0 && pages != null && actualPage > pages
|
||||
if (items.isEmpty() && (array.length() > 0 || (total != 0 && !beyondLastPage))) throw malformed()
|
||||
if (items.isNotEmpty() && (total == 0 || pages == 0)) throw malformed()
|
||||
val next = if (
|
||||
items.isNotEmpty() && actualPage >= requestedPage && actualPage < pageLimit && actualPage < MAX_PAGE
|
||||
) actualPage + 1 else null
|
||||
return SearchPage(items, next, total)
|
||||
}
|
||||
|
||||
private fun video(item: JSONObject): VideoItem? {
|
||||
if (item.optString("type").let { it.isNotBlank() && it != "video" }) return null
|
||||
if (item.optInt("is_ad") != 0 || item.optJSONObject("business_info") != null) return null
|
||||
val bvid = item.optString("bvid").takeIf { it.matches(Regex("BV[0-9A-Za-z]+")) }
|
||||
val aid = item.positiveLong("aid") ?: item.positiveLong("id")
|
||||
if (bvid == null && aid == null) return null
|
||||
val title = plainText(item.optString("title")).takeIf { it.isNotBlank() } ?: return null
|
||||
val author = plainText(item.optString("author"))
|
||||
val duration = duration(item.optString("duration"))
|
||||
return VideoItem(
|
||||
id = bvid ?: "av$aid",
|
||||
title = title,
|
||||
coverUrl = ContentJson.secureUrl(item.optString("pic")),
|
||||
subtitle = listOf(author, duration).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
bvid = bvid,
|
||||
aid = aid,
|
||||
)
|
||||
}
|
||||
|
||||
private fun season(item: JSONObject, category: SearchCategory): VideoItem? {
|
||||
if (item.optString("type").let { it.isNotBlank() && it != category.apiType }) return null
|
||||
val candidate = item.optString("url").ifBlank { item.optString("goto_url") }
|
||||
val officialUrl = ContentJson.secureUrl(candidate).toHttpUrlOrNull()?.takeIf {
|
||||
it.host == "www.bilibili.com" || it.host == "bilibili.com"
|
||||
}
|
||||
val path = officialUrl?.encodedPath.orEmpty()
|
||||
// media_id identifies a metadata record and MUST NOT be used as season_id.
|
||||
val seasonId = item.positiveLong("season_id") ?: item.positiveLong("pgc_season_id")
|
||||
?: seasonPath.find(path)?.groupValues?.get(1)?.toLongOrNull()?.takeIf { it > 0 }
|
||||
val eps = item.optJSONArray("eps")
|
||||
val firstEpisode = eps?.let { array ->
|
||||
(0 until array.length()).firstNotNullOfOrNull { index ->
|
||||
array.optJSONObject(index)?.positiveLong("id")
|
||||
}
|
||||
}
|
||||
val epId = firstEpisode ?: episodePath.find(path)?.groupValues?.get(1)?.toLongOrNull()?.takeIf { it > 0 }
|
||||
if (seasonId == null && epId == null) return null
|
||||
val title = plainText(item.optString("title")).takeIf { it.isNotBlank() } ?: return null
|
||||
val badges = item.optJSONArray("badges") ?: item.optJSONArray("display_info")
|
||||
val badgeTexts = badges?.let { array ->
|
||||
(0 until array.length()).mapNotNull { index ->
|
||||
array.optJSONObject(index)?.optString("text")?.let(::plainText)?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
}.orEmpty().distinct()
|
||||
val detail = plainText(item.optString("index_show").ifBlank { item.optString("styles") })
|
||||
return VideoItem(
|
||||
id = seasonId?.let { "ss$it" } ?: "ep$epId",
|
||||
title = title,
|
||||
coverUrl = ContentJson.secureUrl(item.optString("cover")),
|
||||
subtitle = (badgeTexts + detail).filter { it.isNotBlank() }.distinct().joinToString(" · "),
|
||||
seasonId = seasonId,
|
||||
epId = epId,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun plainText(value: String): String {
|
||||
val withoutTags = value.replace(commentPattern, "")
|
||||
.replace(hiddenPattern, "").replace(tagPattern, "")
|
||||
return withoutTags.replace(entityPattern) { match ->
|
||||
when (val entity = match.groupValues[1]) {
|
||||
"amp" -> "&"
|
||||
"lt" -> "<"
|
||||
"gt" -> ">"
|
||||
"quot" -> "\""
|
||||
"apos" -> "'"
|
||||
"nbsp" -> " "
|
||||
else -> {
|
||||
if (!entity.startsWith('#')) return@replace match.value
|
||||
val codepoint = if (entity.startsWith("#x", true)) {
|
||||
entity.drop(2).toLongOrNull(16)
|
||||
} else entity.drop(1).toLongOrNull()
|
||||
if (codepoint == null || codepoint !in 1L..0x10FFFFL || codepoint in 0xD800L..0xDFFFL) {
|
||||
"\uFFFD"
|
||||
} else String(Character.toChars(codepoint.toInt()))
|
||||
}
|
||||
}
|
||||
}.filterNot { it.isISOControl() && !it.isWhitespace() }
|
||||
.replace(whitespacePattern, " ").trim()
|
||||
}
|
||||
|
||||
internal fun duration(value: String): String {
|
||||
val parts = value.trim().split(':')
|
||||
if (parts.size !in 1..3) return ""
|
||||
val numbers = parts.map { it.toLongOrNull()?.takeIf { number -> number >= 0 } ?: return "" }
|
||||
val seconds = when (numbers.size) {
|
||||
1 -> numbers[0].takeIf { it <= MAX_DURATION_SECONDS } ?: return ""
|
||||
2 -> {
|
||||
if (numbers[0] > MAX_DURATION_SECONDS / 60 || numbers[1] > 59) return ""
|
||||
numbers[0] * 60 + numbers[1]
|
||||
}
|
||||
else -> {
|
||||
if (numbers[0] > MAX_DURATION_SECONDS / 3600 || numbers[1] > 59 || numbers[2] > 59) return ""
|
||||
numbers[0] * 3600 + numbers[1] * 60 + numbers[2]
|
||||
}
|
||||
}
|
||||
if (seconds > MAX_DURATION_SECONDS) return ""
|
||||
return if (seconds >= 3600) {
|
||||
"%d:%02d:%02d".format(seconds / 3600, seconds / 60 % 60, seconds % 60)
|
||||
} else "%d:%02d".format(seconds / 60, seconds % 60)
|
||||
}
|
||||
|
||||
private fun JSONObject.positiveLong(key: String): Long? = longValue(key)?.takeIf { it > 0 }
|
||||
private fun JSONObject.positiveInt(key: String): Int? =
|
||||
longValue(key)?.takeIf { it in 1..Int.MAX_VALUE.toLong() }?.toInt()
|
||||
private fun JSONObject.nonNegativeInt(key: String): Int? =
|
||||
longValue(key)?.takeIf { it >= 0 }?.coerceAtMost(Int.MAX_VALUE.toLong())?.toInt()
|
||||
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 malformed() = ClientException("B 站搜索返回的数据不完整,请稍后重试")
|
||||
private const val MAX_DURATION_SECONDS = 366L * 24 * 3600
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import androidx.media3.datasource.DefaultHttpDataSource
|
||||
import dev.bulubulu.tv.data.BiliHttpClient
|
||||
|
||||
/** CDN requests must use the same browser identity as the playback API request. */
|
||||
internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.Factory =
|
||||
DefaultHttpDataSource.Factory()
|
||||
.setUserAgent(BiliHttpClient.USER_AGENT)
|
||||
.setDefaultRequestProperties(mapOf("Referer" to referer))
|
||||
.setConnectTimeoutMs(15_000)
|
||||
.setReadTimeoutMs(20_000)
|
||||
.setAllowCrossProtocolRedirects(false)
|
||||
@@ -52,7 +52,6 @@ import androidx.media3.common.C
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.datasource.DefaultHttpDataSource
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.exoplayer.DefaultLoadControl
|
||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
@@ -87,12 +86,7 @@ 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 = DefaultHttpDataSource.Factory()
|
||||
.setUserAgent("Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36")
|
||||
.setDefaultRequestProperties(mapOf("Referer" to source.referer))
|
||||
.setConnectTimeoutMs(15_000)
|
||||
.setReadTimeoutMs(20_000)
|
||||
.setAllowCrossProtocolRedirects(false)
|
||||
val http = mediaHttpDataSourceFactory(source.referer)
|
||||
val alternatives = buildMap {
|
||||
put(source.video.url, source.video.backupUrls)
|
||||
source.audio?.let { put(it.url, it.backupUrls) }
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package dev.bulubulu.tv.search
|
||||
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.SearchDataSource
|
||||
import dev.bulubulu.tv.ui.SearchUiState
|
||||
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
|
||||
|
||||
/** A screen-scoped search: typing never sends requests, and old responses cannot replace new ones. */
|
||||
class SearchController(
|
||||
private val scope: CoroutineScope,
|
||||
private val repository: SearchDataSource,
|
||||
) {
|
||||
private val _state = MutableStateFlow(SearchUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
private var generation = 0L
|
||||
private var nextPage: Int? = null
|
||||
|
||||
fun open() { _state.update { it.copy(visible = true) } }
|
||||
|
||||
fun close() {
|
||||
cancelRequest()
|
||||
nextPage = null
|
||||
_state.value = SearchUiState()
|
||||
}
|
||||
|
||||
fun updateQuery(value: String) {
|
||||
// Bound pasted/IME input without cutting a UTF-16 surrogate pair in half.
|
||||
val bounded = value.take(MAX_QUERY_LENGTH).let {
|
||||
if (it.lastOrNull()?.isHighSurrogate() == true) it.dropLast(1) else it
|
||||
}
|
||||
_state.update { it.copy(query = bounded) }
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
cancelRequest()
|
||||
nextPage = null
|
||||
_state.update { SearchUiState(visible = it.visible, category = it.category) }
|
||||
}
|
||||
|
||||
fun submit() {
|
||||
if (!_state.value.visible) return
|
||||
val keyword = _state.value.query.trim()
|
||||
if (keyword.isBlank()) return
|
||||
if (_state.value.loading && keyword == _state.value.submittedQuery) return
|
||||
firstPage(keyword, _state.value.category)
|
||||
}
|
||||
|
||||
fun selectCategory(category: SearchCategory) {
|
||||
if (!_state.value.visible || category == _state.value.category) return
|
||||
val keyword = _state.value.query.trim()
|
||||
if (keyword.isBlank()) {
|
||||
clear()
|
||||
_state.update { it.copy(category = category) }
|
||||
} else {
|
||||
firstPage(keyword, category)
|
||||
}
|
||||
}
|
||||
|
||||
fun retry() {
|
||||
if (!_state.value.visible || _state.value.loading || _state.value.loadingMore) return
|
||||
if (_state.value.items.isNotEmpty()) loadMore()
|
||||
else _state.value.submittedQuery.takeIf { it.isNotBlank() }?.let {
|
||||
firstPage(it, _state.value.category)
|
||||
}
|
||||
}
|
||||
|
||||
private fun firstPage(keyword: String, category: SearchCategory) {
|
||||
cancelRequest()
|
||||
val requestGeneration = generation
|
||||
nextPage = null
|
||||
_state.value = SearchUiState(
|
||||
visible = true, query = keyword, submittedQuery = keyword,
|
||||
category = category, loading = true,
|
||||
)
|
||||
job = scope.launch {
|
||||
try {
|
||||
val page = repository.search(keyword, category, 1)
|
||||
if (generation != requestGeneration || !_state.value.visible) return@launch
|
||||
nextPage = page.nextPage?.takeIf { it > 1 && page.items.isNotEmpty() }
|
||||
_state.update {
|
||||
it.copy(
|
||||
items = page.items.distinctBy { item -> item.id }, loading = false,
|
||||
hasMore = nextPage != null, totalResults = page.totalResults,
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException) throw error
|
||||
if (generation == requestGeneration && _state.value.visible) {
|
||||
_state.update { it.copy(loading = false, error = userMessage(error)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadMore() {
|
||||
val current = _state.value
|
||||
val requestedPage = nextPage ?: return
|
||||
if (!current.visible || current.loading || current.loadingMore || current.submittedQuery.isBlank()) return
|
||||
val requestGeneration = generation
|
||||
_state.update { it.copy(loadingMore = true, error = null) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
// Keep paging the displayed query even if an unsubmitted draft is being edited.
|
||||
val page = repository.search(current.submittedQuery, current.category, requestedPage)
|
||||
if (generation != requestGeneration || !_state.value.visible) return@launch
|
||||
val merged = (current.items + page.items).distinctBy { it.id }
|
||||
nextPage = page.nextPage?.takeIf { it > requestedPage && merged.size > current.items.size }
|
||||
_state.update {
|
||||
it.copy(
|
||||
items = merged, loadingMore = false, hasMore = nextPage != null,
|
||||
totalResults = page.totalResults ?: it.totalResults,
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException) throw error
|
||||
if (generation == requestGeneration && _state.value.visible) {
|
||||
_state.update { it.copy(loadingMore = false, error = userMessage(error)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelRequest() {
|
||||
generation++
|
||||
job?.cancel()
|
||||
job = null
|
||||
}
|
||||
|
||||
companion object { const val MAX_QUERY_LENGTH = 100 }
|
||||
}
|
||||
@@ -68,10 +68,12 @@ fun BulubuluHome(
|
||||
onLogout: () -> Unit,
|
||||
focusRestoreKey: Int = 0,
|
||||
active: Boolean = true,
|
||||
onSearch: () -> Unit = {},
|
||||
) {
|
||||
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>() }
|
||||
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
|
||||
val recommendGrid = rememberLazyGridState()
|
||||
@@ -92,6 +94,7 @@ fun BulubuluHome(
|
||||
when {
|
||||
lastFocusToken == "account" -> accountFocus.requestFocus()
|
||||
lastFocusToken == "refresh" -> refreshFocus.requestFocus()
|
||||
lastFocusToken == "search" -> searchFocus.requestFocus()
|
||||
lastFocusToken.startsWith("item:") -> {
|
||||
val prefix = "item:${state.selectedTab.name}:"
|
||||
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
|
||||
@@ -121,6 +124,8 @@ fun BulubuluHome(
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
TvAction("搜索", onSearch, Modifier.focusRequester(searchFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "search" })
|
||||
Spacer(Modifier.width(12.dp))
|
||||
if (state.authBusy) {
|
||||
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
|
||||
} else if (state.account != null) {
|
||||
@@ -209,7 +214,7 @@ fun BulubuluHome(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VideoCard(item: VideoItem, portrait: Boolean, focusRequester: FocusRequester, onFocused: () -> Unit, onClick: () -> Unit) {
|
||||
internal fun VideoCard(item: VideoItem, portrait: Boolean, focusRequester: FocusRequester, onFocused: () -> Unit, onClick: () -> Unit) {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val focusEnabled = LocalTvFocusEnabled.current
|
||||
val scale by animateFloatAsState(if (focused) 1.025f else 1f, label = "posterFocus")
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
package dev.bulubulu.tv.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.ime
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
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.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
fun SearchScreen(
|
||||
state: SearchUiState,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onSearch: () -> Unit,
|
||||
onCategorySelected: (SearchCategory) -> Unit,
|
||||
onItemSelected: (VideoItem) -> Unit,
|
||||
onLoadMore: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
active: Boolean = true,
|
||||
focusRestoreKey: Int = 0,
|
||||
) {
|
||||
val inputFocus = remember { FocusRequester() }
|
||||
val backFocus = remember { FocusRequester() }
|
||||
val submitFocus = remember { FocusRequester() }
|
||||
val clearFocus = remember { FocusRequester() }
|
||||
val footerFocus = remember { FocusRequester() }
|
||||
val categoryFocus = remember { SearchCategory.entries.associateWith { FocusRequester() } }
|
||||
val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
|
||||
val gridState = rememberLazyGridState()
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val imeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
|
||||
var lastFocus by remember { mutableStateOf("input") }
|
||||
var suspendedFocus by remember { mutableStateOf<String?>(null) }
|
||||
var gridHasFocus by remember { mutableStateOf(false) }
|
||||
var focusResultsWhenReady by remember { mutableStateOf(false) }
|
||||
var pageStartIndex by remember { mutableStateOf<Int?>(null) }
|
||||
val columns = if (state.category.portrait) 5 else 4
|
||||
|
||||
fun submit() {
|
||||
if (!active || state.query.isBlank()) return
|
||||
keyboard?.hide()
|
||||
pageStartIndex = null
|
||||
focusResultsWhenReady = true
|
||||
submitFocus.requestFocus()
|
||||
onSearch()
|
||||
}
|
||||
|
||||
LaunchedEffect(state.submittedQuery, state.category) {
|
||||
gridState.scrollToItem(0)
|
||||
}
|
||||
LaunchedEffect(active, focusRestoreKey) {
|
||||
if (!active) {
|
||||
suspendedFocus = lastFocus
|
||||
return@LaunchedEffect
|
||||
}
|
||||
// Enabling a text field can temporarily reclaim Android focus. Restore
|
||||
// the token captured before the overlay, not that incidental focus.
|
||||
val targetFocus = suspendedFocus ?: lastFocus
|
||||
if (targetFocus == "footer" && pageStartIndex != null && !state.loadingMore) return@LaunchedEffect
|
||||
delay(100)
|
||||
when (targetFocus) {
|
||||
"back" -> backFocus.requestFocus()
|
||||
"submit" -> submitFocus.requestFocus()
|
||||
"clear" -> if (state.query.isNotEmpty()) clearFocus.requestFocus() else inputFocus.requestFocus()
|
||||
"footer" -> if (pageStartIndex == null || state.loadingMore) {
|
||||
if (state.hasMore && state.items.isNotEmpty()) {
|
||||
gridState.scrollToItem(state.items.size)
|
||||
delay(100)
|
||||
footerFocus.requestFocus()
|
||||
} else categoryFocus.getValue(state.category).requestFocus()
|
||||
}
|
||||
"category" -> categoryFocus.getValue(state.category).requestFocus()
|
||||
"input" -> inputFocus.requestFocus()
|
||||
else -> {
|
||||
val index = state.items.indexOfFirst { "item:${it.id}" == targetFocus }
|
||||
if (index >= 0) {
|
||||
gridState.scrollToItem(index)
|
||||
delay(100)
|
||||
cardFocus[state.items[index].id]?.requestFocus()
|
||||
} else inputFocus.requestFocus()
|
||||
}
|
||||
}
|
||||
suspendedFocus = null
|
||||
}
|
||||
LaunchedEffect(state.loading, state.items, state.error, active) {
|
||||
if (!active || !focusResultsWhenReady || state.loading) return@LaunchedEffect
|
||||
delay(100)
|
||||
if (state.query.trim() != state.submittedQuery) {
|
||||
focusResultsWhenReady = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val first = state.items.firstOrNull()
|
||||
if (first != null) {
|
||||
gridState.scrollToItem(0)
|
||||
delay(100)
|
||||
cardFocus[first.id]?.requestFocus()
|
||||
} else categoryFocus.getValue(state.category).requestFocus()
|
||||
focusResultsWhenReady = false
|
||||
}
|
||||
LaunchedEffect(state.items, state.hasMore, state.loadingMore, state.error, active) {
|
||||
if (!active || state.loadingMore || pageStartIndex == null) return@LaunchedEffect
|
||||
run {
|
||||
val firstNew = pageStartIndex?.takeIf { it < state.items.size }
|
||||
val target = firstNew ?: state.items.lastIndex.takeIf { !state.hasMore && it >= 0 }
|
||||
when {
|
||||
target != null -> {
|
||||
gridState.scrollToItem(target)
|
||||
delay(100)
|
||||
cardFocus[state.items[target].id]?.requestFocus()
|
||||
}
|
||||
pageStartIndex != null && state.hasMore -> {
|
||||
gridState.scrollToItem(state.items.size)
|
||||
delay(100)
|
||||
footerFocus.requestFocus()
|
||||
}
|
||||
}
|
||||
}
|
||||
pageStartIndex = null
|
||||
}
|
||||
BackHandler(active) {
|
||||
pageStartIndex = null
|
||||
when {
|
||||
imeVisible -> keyboard?.hide()
|
||||
gridHasFocus -> categoryFocus.getValue(state.category).requestFocus()
|
||||
else -> { keyboard?.hide(); onBack() }
|
||||
}
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalTvFocusEnabled provides active) {
|
||||
Column(
|
||||
Modifier.fillMaxSize()
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (state.loadingMore && event.type == KeyEventType.KeyDown && event.key in listOf(Key.DirectionUp, Key.DirectionDown, Key.DirectionLeft, Key.DirectionRight)) {
|
||||
// Deliberate navigation during a request cancels its focus handoff.
|
||||
pageStartIndex = null
|
||||
}
|
||||
false
|
||||
}
|
||||
.background(Brush.verticalGradient(listOf(Color(0xFF1B1C2A), TvBackground), endY = 700f))
|
||||
.padding(horizontal = 38.dp, vertical = 24.dp),
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
TvAction("返回", { keyboard?.hide(); onBack() }, Modifier.focusRequester(backFocus).onFocusChanged { if (it.isFocused) lastFocus = "back" })
|
||||
Spacer(Modifier.width(16.dp))
|
||||
OutlinedTextField(
|
||||
value = state.query,
|
||||
onValueChange = { pageStartIndex = null; onQueryChange(it) },
|
||||
placeholder = { Text("输入视频、电影或番剧名称", fontSize = 15.sp) },
|
||||
singleLine = true,
|
||||
enabled = active,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
textStyle = TextStyle(color = TvText, fontSize = 16.sp),
|
||||
colors = OutlinedTextFieldDefaults.colors(
|
||||
focusedBorderColor = TvAccent, unfocusedBorderColor = TvMuted.copy(alpha = 0.35f),
|
||||
focusedContainerColor = TvPanel, unfocusedContainerColor = TvPanel,
|
||||
cursorColor = TvAccent, focusedTextColor = TvText, unfocusedTextColor = TvText,
|
||||
),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { submit() }),
|
||||
modifier = Modifier.weight(1f).testTag("search_query")
|
||||
.focusRequester(inputFocus)
|
||||
.focusProperties {
|
||||
canFocus = active
|
||||
down = categoryFocus.getValue(state.category)
|
||||
left = backFocus
|
||||
right = submitFocus
|
||||
}
|
||||
.onFocusChanged { if (it.isFocused) lastFocus = "input" }
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (!active) return@onPreviewKeyEvent false
|
||||
when (event.key) {
|
||||
Key.DirectionDown -> {
|
||||
if (event.type == KeyEventType.KeyDown) {
|
||||
keyboard?.hide()
|
||||
categoryFocus.getValue(state.category).requestFocus()
|
||||
}
|
||||
true
|
||||
}
|
||||
Key.Enter, Key.NumPadEnter -> {
|
||||
if (event.type == KeyEventType.KeyUp) submit()
|
||||
true
|
||||
}
|
||||
Key.DirectionCenter -> {
|
||||
if (event.type == KeyEventType.KeyUp) keyboard?.show()
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
},
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
TvAction("搜索", ::submit, Modifier.testTag("search_submit").focusRequester(submitFocus).onFocusChanged { if (it.isFocused) lastFocus = "submit" }, enabled = state.query.isNotBlank())
|
||||
Spacer(Modifier.width(10.dp))
|
||||
TvAction("清空", {
|
||||
focusResultsWhenReady = false
|
||||
pageStartIndex = null
|
||||
onClear()
|
||||
inputFocus.requestFocus()
|
||||
}, Modifier.focusRequester(clearFocus).onFocusChanged { if (it.isFocused) lastFocus = "clear" }, enabled = state.query.isNotEmpty() || state.submittedQuery.isNotEmpty())
|
||||
}
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("搜索", color = TvText, fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.width(24.dp))
|
||||
Row(Modifier.focusGroup(), horizontalArrangement = Arrangement.spacedBy(9.dp)) {
|
||||
SearchCategory.entries.forEach { category ->
|
||||
TvAction(category.title, {
|
||||
keyboard?.hide()
|
||||
focusResultsWhenReady = false
|
||||
pageStartIndex = null
|
||||
onCategorySelected(category)
|
||||
}, Modifier.focusRequester(categoryFocus.getValue(category)).onFocusChanged { if (it.isFocused) lastFocus = "category" }, selected = state.category == category)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(20.dp))
|
||||
if (state.submittedQuery.isNotEmpty()) {
|
||||
Text(
|
||||
"“${state.submittedQuery}”" + (state.totalResults?.let { " · $it 个结果" } ?: ""),
|
||||
color = TvMuted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(14.dp))
|
||||
if (state.items.isEmpty()) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
when {
|
||||
state.loading -> {
|
||||
CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp)
|
||||
Text("正在搜索…", color = TvMuted, fontSize = 15.sp)
|
||||
}
|
||||
state.error != null -> {
|
||||
Text(state.error, color = TvText, fontSize = 17.sp)
|
||||
TvAction("重试", { focusResultsWhenReady = true; onRetry() })
|
||||
}
|
||||
state.submittedQuery.isBlank() -> {
|
||||
Text("想看什么?", color = TvText, fontSize = 24.sp, fontWeight = FontWeight.Medium)
|
||||
Text("输入名称,再按搜索开始", color = TvMuted, fontSize = 14.sp)
|
||||
}
|
||||
else -> {
|
||||
Text("没有找到相关内容", color = TvText, fontSize = 21.sp)
|
||||
Text("换个关键词,或试试其他分类", color = TvMuted, fontSize = 14.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LazyVerticalGrid(
|
||||
columns = GridCells.Fixed(columns), state = gridState,
|
||||
horizontalArrangement = Arrangement.spacedBy(18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||
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 ->
|
||||
VideoCard(item, state.category.portrait, cardFocus.getOrPut(item.id) { FocusRequester() }, { lastFocus = "item:${item.id}" }, { keyboard?.hide(); pageStartIndex = null; onItemSelected(item) })
|
||||
}
|
||||
item(span = { GridItemSpan(columns) }, key = "search-footer") {
|
||||
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) }
|
||||
when {
|
||||
state.hasMore || state.loadingMore -> TvAction(
|
||||
when { state.loadingMore -> "正在加载…"; state.error != null -> "重试"; else -> "加载更多" },
|
||||
{
|
||||
if (!state.loadingMore) {
|
||||
pageStartIndex = state.items.size
|
||||
if (state.error == null) onLoadMore() else onRetry()
|
||||
}
|
||||
},
|
||||
Modifier.focusRequester(footerFocus).onFocusChanged { if (it.isFocused) lastFocus = "footer" },
|
||||
)
|
||||
else -> Text("已经到底了", color = TvMuted, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("确认输入关键词 方向键浏览 返回上一级", color = TvMuted.copy(alpha = 0.7f), fontSize = 11.sp, modifier = Modifier.padding(start = 5.dp, top = 8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.bulubulu.tv.ui
|
||||
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
|
||||
data class SearchUiState(
|
||||
val visible: Boolean = false,
|
||||
val query: String = "",
|
||||
val submittedQuery: String = "",
|
||||
val category: SearchCategory = SearchCategory.VIDEO,
|
||||
val items: List<VideoItem> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val loadingMore: Boolean = false,
|
||||
val error: String? = null,
|
||||
val hasMore: Boolean = false,
|
||||
val totalResults: Int? = null,
|
||||
)
|
||||
@@ -0,0 +1,220 @@
|
||||
package dev.bulubulu.tv
|
||||
|
||||
import dev.bulubulu.tv.core.BiliApiException
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.data.SearchJson
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SearchJsonTest {
|
||||
private val video = """{"type":"video","id":117546359458096,"aid":117546359458096,"bvid":"BV1YP4w6aErA","title":"一口气看完《<em class=\"keyword\">三体</em>》","pic":"//i2.hdslb.com/cover.jpg","author":"A & B","duration":"220:7"}"""
|
||||
|
||||
@Test
|
||||
fun videoResultsPreserveLargeIdsCleanHighlightsAndDeduplicate() {
|
||||
val result = SearchJson.parse(envelope("[$video,$video]"), SearchCategory.VIDEO, 1)
|
||||
assertEquals(1, result.items.size)
|
||||
val item = result.items.single()
|
||||
assertEquals(117546359458096L, item.aid)
|
||||
assertEquals("BV1YP4w6aErA", item.bvid)
|
||||
assertEquals("一口气看完《三体》", item.title)
|
||||
assertEquals("A & B · 3:40:07", item.subtitle)
|
||||
assertEquals("https://i2.hdslb.com/cover.jpg", item.coverUrl)
|
||||
assertEquals(2, result.nextPage)
|
||||
assertEquals(100, result.totalResults)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun videoCanUseAidWhenBvidIsMissing() {
|
||||
val result = SearchJson.parse(
|
||||
envelope("""[{"type":"video","aid":"117546359458096","title":"视频","pic":"http://i0.hdslb.com/cover.jpg"}]"""),
|
||||
SearchCategory.VIDEO,
|
||||
1,
|
||||
)
|
||||
assertEquals("av117546359458096", result.items.single().id)
|
||||
assertNull(result.items.single().bvid)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun movieUsesSeasonIdRatherThanMediaIdAndPreservesMembershipBadge() {
|
||||
val result = SearchJson.parse(
|
||||
envelope("""[{"type":"media_ft","media_id":28480858,"season_id":44847,"title":"<em class=\"keyword\">流浪地球</em>2","cover":"https://i0.hdslb.com/poster.jpg","url":"https://www.bilibili.com/bangumi/play/ep744327?theme=movie","badges":[{"text":"大会员"}],"styles":"科幻/冒险"}]""", total = 1, pages = 1),
|
||||
SearchCategory.MOVIE,
|
||||
1,
|
||||
)
|
||||
val item = result.items.single()
|
||||
assertEquals("ss44847", item.id)
|
||||
assertEquals(44847L, item.seasonId)
|
||||
assertEquals(744327L, item.epId)
|
||||
assertEquals("流浪地球2", item.title)
|
||||
assertEquals("大会员 · 科幻/冒险", item.subtitle)
|
||||
assertNull(result.nextPage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bangumiKeepsFirstEpisodeAndDoesNotConfuseMetadataId() {
|
||||
val result = SearchJson.parse(
|
||||
envelope("""[{"type":"media_bangumi","media_id":4315402,"season_id":26257,"title":"三体","eps":[{"id":704473},{"id":704474}],"index_show":"全15话"}]""", total = 1, pages = 1),
|
||||
SearchCategory.BANGUMI,
|
||||
1,
|
||||
)
|
||||
assertEquals(26257L, result.items.single().seasonId)
|
||||
assertEquals(704473L, result.items.single().epId)
|
||||
assertEquals("全15话", result.items.single().subtitle)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pgcCanUseVerifiedOfficialSeasonOrEpisodeUrlWhenIdsAreMissing() {
|
||||
val result = SearchJson.parse(
|
||||
envelope("""[
|
||||
{"type":"media_bangumi","media_id":123,"title":"番剧甲","url":"http://www.bilibili.com/bangumi/play/ss44"},
|
||||
{"type":"media_bangumi","media_id":456,"title":"番剧乙","url":"https://www.bilibili.com/bangumi/play/ep55?from=search"}
|
||||
]""", total = 2, pages = 1),
|
||||
SearchCategory.BANGUMI,
|
||||
1,
|
||||
)
|
||||
assertEquals(listOf("ss44", "ep55"), result.items.map { it.id })
|
||||
assertNull(result.items[1].seasonId)
|
||||
assertEquals(55L, result.items[1].epId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaIdAloneOrUntrustedUrlCannotBecomeAPlayableSeason() {
|
||||
for (url in listOf("", "https://bilibili.com.evil.example/bangumi/play/ss123", "file:///ep123")) {
|
||||
val item = JSONObject().put("type", "media_ft").put("media_id", 999)
|
||||
.put("title", "没有有效引用").put("url", url)
|
||||
assertThrows<ClientException> {
|
||||
SearchJson.parse(envelope(JSONArray().put(item).toString(), total = 1, pages = 1), SearchCategory.MOVIE, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun plainTextDecodesBasicNumericAndAstralEntitiesWithoutHtmlExecution() {
|
||||
assertEquals(
|
||||
"三体 & \"TV\" ' 🚀 <原著>",
|
||||
SearchJson.plainText("<em class=\"keyword\">三体</em> & "TV" ' 🚀 <原著>"),
|
||||
)
|
||||
assertEquals("三体", SearchJson.plainText("<!--注释--><script>ignore()</script><style>ignore</style>三体"))
|
||||
assertEquals("\uFFFD\uFFFD", SearchJson.plainText("��"))
|
||||
assertEquals("&unknown;", SearchJson.plainText("&unknown;"))
|
||||
assertFalse(SearchJson.plainText("甲乙").contains('\u0001'))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun durationNormalizesShortFieldsAndRejectsInvalidOrOverflowingValues() {
|
||||
assertEquals("1:03", SearchJson.duration("1:3"))
|
||||
assertEquals("3:40:07", SearchJson.duration("220:7"))
|
||||
assertEquals("1:02:03", SearchJson.duration("1:2:3"))
|
||||
assertEquals("0:59", SearchJson.duration("59"))
|
||||
for (value in listOf("1:99", "-2:01", "1:2:3:4", "1:9223372036854775807", "garbage")) {
|
||||
assertEquals("", SearchJson.duration(value))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun explicitZeroCountAllowsMissingResultInRealMovieEmptyResponse() {
|
||||
val root = JSONObject("""{"code":0,"data":{"page":1,"pagesize":20,"numResults":0,"numPages":0}}""")
|
||||
val result = SearchJson.parse(root, SearchCategory.MOVIE, 1)
|
||||
assertTrue(result.items.isEmpty())
|
||||
assertEquals(0, result.totalResults)
|
||||
assertNull(result.nextPage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun voucherChallengeIsRiskFailureEvenWhenTopLevelCodeIsZero() {
|
||||
val error = assertThrows<BiliApiException> {
|
||||
SearchJson.parse(JSONObject("""{"code":0,"data":{"v_voucher":"test-challenge"}}"""), SearchCategory.VIDEO, 1)
|
||||
}
|
||||
assertEquals(-352, error.apiCode)
|
||||
assertTrue(error.message.orEmpty().contains("风控"))
|
||||
assertFalse(error.message.orEmpty().contains("test-challenge"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingOrWrongResultCannotMasqueradeAsNoMatches() {
|
||||
for (data in listOf(
|
||||
"""{"page":1,"numResults":7,"numPages":1}""",
|
||||
"""{"page":1,"numPages":0}""",
|
||||
"""{"page":1,"numResults":0,"result":{}}""",
|
||||
"""{"numResults":0,"result":[]}""",
|
||||
)) {
|
||||
assertThrows<ClientException> {
|
||||
SearchJson.parse(JSONObject("""{"code":0,"data":$data}"""), SearchCategory.VIDEO, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unavailableTypesAndUnplayableCardsDoNotBecomeAnEmptySuccess() {
|
||||
assertThrows<ClientException> {
|
||||
SearchJson.parse(
|
||||
envelope("""[{"type":"live_room","id":123,"title":"直播"},{"type":"video","title":"缺少标识"}]"""),
|
||||
SearchCategory.VIDEO,
|
||||
1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun usesServerActualPageAndNeverLoopsBackwards() {
|
||||
assertEquals(4, SearchJson.parse(envelope("[$video]", page = 3), SearchCategory.VIDEO, 1).nextPage)
|
||||
assertNull(SearchJson.parse(envelope("[$video]", page = 1), SearchCategory.VIDEO, 3).nextPage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nextPageIsBoundedAndStopsAtReportedTotal() {
|
||||
assertNull(SearchJson.parse(envelope("[$video]", page = 50, pages = 500), SearchCategory.VIDEO, 50).nextPage)
|
||||
assertNull(SearchJson.parse(envelope("[$video]", page = 5, pages = 5), SearchCategory.VIDEO, 5).nextPage)
|
||||
assertThrows<ClientException> { SearchJson.parse(envelope("[$video]"), SearchCategory.VIDEO, 51) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fallsBackToTotalAndPageSizeWhenNumPagesIsAbsent() {
|
||||
val root = envelope("[$video]", total = 21)
|
||||
root.getJSONObject("data").remove("numPages")
|
||||
assertEquals(2, SearchJson.parse(root, SearchCategory.VIDEO, 1).nextPage)
|
||||
root.getJSONObject("data").put("page", 2)
|
||||
assertNull(SearchJson.parse(root, SearchCategory.VIDEO, 2).nextPage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun absentPaginationDoesNotCauseUnboundedMoreRequests() {
|
||||
val root = envelope("[$video]")
|
||||
root.getJSONObject("data").remove("numPages")
|
||||
root.getJSONObject("data").remove("numResults")
|
||||
val page = SearchJson.parse(root, SearchCategory.VIDEO, 1)
|
||||
assertNull(page.nextPage)
|
||||
assertNull(page.totalResults)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverErrorRetainsCodeAndDoesNotNeedDataObject() {
|
||||
val error = assertThrows<BiliApiException> {
|
||||
SearchJson.parse(JSONObject("""{"code":-101,"message":"请登录"}"""), SearchCategory.VIDEO, 1)
|
||||
}
|
||||
assertEquals(-101, error.apiCode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mediaCoverCannotUseLocalOrCredentialBearingUrl() {
|
||||
val root = envelope("""[{"type":"media_ft","season_id":44,"title":"电影","cover":"file:///private/session.enc"}]""", total = 1, pages = 1)
|
||||
assertEquals("", SearchJson.parse(root, SearchCategory.MOVIE, 1).items.single().coverUrl)
|
||||
}
|
||||
|
||||
private fun envelope(items: String, page: Int = 1, total: Int = 100, pages: Int = 5): JSONObject =
|
||||
JSONObject("""{"code":0,"data":{"page":$page,"pagesize":20,"numResults":$total,"numPages":$pages,"result":$items}}""")
|
||||
|
||||
private inline fun <reified T : Throwable> assertThrows(block: () -> Unit): T {
|
||||
try { block() } catch (error: Throwable) {
|
||||
if (error is T) return error
|
||||
throw AssertionError("Expected ${T::class.java.simpleName}, got ${error.javaClass.simpleName}", error)
|
||||
}
|
||||
throw AssertionError("Expected ${T::class.java.simpleName}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package dev.bulubulu.tv.search
|
||||
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.SearchDataSource
|
||||
import dev.bulubulu.tv.core.SearchPage
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
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 SearchControllerTest {
|
||||
private fun item(id: String) = VideoItem(id, "内容 $id", "")
|
||||
|
||||
@Test fun typingAndBlankSubmitDoNotRequestAndDuplicateSubmitIsIgnored() = runTest {
|
||||
val pending = mutableListOf<Continuation<SearchPage>>()
|
||||
val queries = mutableListOf<String>()
|
||||
val controller = SearchController(this, SearchDataSource { query, _, _ ->
|
||||
queries += query
|
||||
suspendCoroutine { pending += it }
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery(" ")
|
||||
controller.submit()
|
||||
controller.updateQuery(" 三体 ")
|
||||
runCurrent()
|
||||
assertTrue(queries.isEmpty())
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
assertEquals(listOf("三体"), queries)
|
||||
pending.single().resume(SearchPage(listOf(item("a")), null))
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.loading)
|
||||
}
|
||||
|
||||
@Test fun lateUncooperativeResponseCannotReplaceNewQueryOrCategory() = runTest {
|
||||
val pending = mutableListOf<Continuation<SearchPage>>()
|
||||
val categories = mutableListOf<SearchCategory>()
|
||||
val controller = SearchController(this, SearchDataSource { _, category, _ ->
|
||||
categories += category
|
||||
suspendCoroutine { pending += it }
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery("旧搜索")
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
controller.updateQuery("新搜索")
|
||||
controller.selectCategory(SearchCategory.BANGUMI)
|
||||
runCurrent()
|
||||
pending[1].resume(SearchPage(listOf(item("new")), null))
|
||||
runCurrent()
|
||||
pending[0].resume(SearchPage(listOf(item("old")), 2))
|
||||
runCurrent()
|
||||
assertEquals(listOf(SearchCategory.VIDEO, SearchCategory.BANGUMI), categories)
|
||||
assertEquals("新搜索", controller.state.value.submittedQuery)
|
||||
assertEquals(listOf("new"), controller.state.value.items.map { it.id })
|
||||
assertFalse(controller.state.value.hasMore)
|
||||
}
|
||||
|
||||
@Test fun clearAndCloseRejectLateResultsAndDoNotRetainHistory() = runTest {
|
||||
for (close in listOf(false, true)) {
|
||||
lateinit var pending: Continuation<SearchPage>
|
||||
val controller = SearchController(this, SearchDataSource { _, _, _ ->
|
||||
suspendCoroutine { pending = it }
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery("临时关键词")
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
if (close) controller.close() else controller.clear()
|
||||
pending.resume(SearchPage(listOf(item("late")), 2))
|
||||
runCurrent()
|
||||
assertEquals(!close, controller.state.value.visible)
|
||||
assertEquals("", controller.state.value.query)
|
||||
assertEquals("", controller.state.value.submittedQuery)
|
||||
assertTrue(controller.state.value.items.isEmpty())
|
||||
assertFalse(controller.state.value.hasMore)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun pagingKeepsSubmittedQueryDeduplicatesAndStopsRepeatedPages() = runTest {
|
||||
val calls = mutableListOf<Pair<String, Int>>()
|
||||
val controller = SearchController(this, SearchDataSource { query, _, page ->
|
||||
calls += query to page
|
||||
when (page) {
|
||||
1 -> SearchPage(listOf(item("a"), item("a")), 2, 3)
|
||||
2 -> SearchPage(listOf(item("a"), item("b")), 3, 3)
|
||||
else -> SearchPage(listOf(item("b")), 4, 3)
|
||||
}
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery("已提交")
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
controller.updateQuery("尚未提交")
|
||||
controller.loadMore()
|
||||
runCurrent()
|
||||
controller.loadMore()
|
||||
runCurrent()
|
||||
controller.loadMore()
|
||||
runCurrent()
|
||||
assertEquals(listOf("已提交" to 1, "已提交" to 2, "已提交" to 3), calls)
|
||||
assertEquals("尚未提交", controller.state.value.query)
|
||||
assertEquals(listOf("a", "b"), controller.state.value.items.map { it.id })
|
||||
assertFalse(controller.state.value.hasMore)
|
||||
}
|
||||
|
||||
@Test fun failedPagePreservesResultsAndRetriesTheSamePage() = runTest {
|
||||
var failures = 1
|
||||
val pages = mutableListOf<Int>()
|
||||
val controller = SearchController(this, SearchDataSource { _, _, page ->
|
||||
pages += page
|
||||
if (page == 2 && failures-- > 0) throw ClientException("请重试")
|
||||
SearchPage(listOf(item(page.toString())), if (page == 1) 2 else null)
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery("测试")
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
controller.loadMore()
|
||||
runCurrent()
|
||||
assertEquals(listOf("1"), controller.state.value.items.map { it.id })
|
||||
assertEquals("请重试", controller.state.value.error)
|
||||
assertTrue(controller.state.value.hasMore)
|
||||
controller.retry()
|
||||
runCurrent()
|
||||
assertEquals(listOf(1, 2, 2), pages)
|
||||
assertEquals(listOf("1", "2"), controller.state.value.items.map { it.id })
|
||||
assertNull(controller.state.value.error)
|
||||
}
|
||||
|
||||
@Test fun firstPageRetryAndCategoryChangeStartAtPageOne() = runTest {
|
||||
val calls = mutableListOf<Pair<SearchCategory, Int>>()
|
||||
var fail = true
|
||||
val controller = SearchController(this, SearchDataSource { _, category, page ->
|
||||
calls += category to page
|
||||
if (fail) { fail = false; throw ClientException("暂时不可用") }
|
||||
SearchPage(listOf(item("$category$page")), 2)
|
||||
})
|
||||
controller.open()
|
||||
controller.updateQuery("三体")
|
||||
controller.submit()
|
||||
runCurrent()
|
||||
assertEquals("暂时不可用", controller.state.value.error)
|
||||
controller.retry()
|
||||
runCurrent()
|
||||
controller.selectCategory(SearchCategory.MOVIE)
|
||||
runCurrent()
|
||||
assertEquals(listOf(SearchCategory.VIDEO to 1, SearchCategory.VIDEO to 1, SearchCategory.MOVIE to 1), calls)
|
||||
assertEquals(SearchCategory.MOVIE, controller.state.value.category)
|
||||
assertEquals(listOf("MOVIE1"), controller.state.value.items.map { it.id })
|
||||
}
|
||||
|
||||
@Test fun inputIsBoundedWithoutSplittingUnicodeAndHiddenScreenCannotSubmit() = runTest {
|
||||
var requests = 0
|
||||
val controller = SearchController(this, SearchDataSource { _, _, _ ->
|
||||
requests++
|
||||
SearchPage(emptyList(), null, 0)
|
||||
})
|
||||
controller.updateQuery("a".repeat(99) + "😀")
|
||||
assertEquals("a".repeat(99), controller.state.value.query)
|
||||
controller.submit()
|
||||
controller.selectCategory(SearchCategory.MOVIE)
|
||||
runCurrent()
|
||||
assertEquals(0, requests)
|
||||
controller.open()
|
||||
controller.clear()
|
||||
controller.selectCategory(SearchCategory.MOVIE)
|
||||
runCurrent()
|
||||
assertEquals(SearchCategory.MOVIE, controller.state.value.category)
|
||||
assertEquals(0, requests)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ The application has one Android app module and no backend service.
|
||||
- `BiliHttpClient` validates official HTTPS API destinations, scopes cookies per network hop, bounds response sizes and propagates coroutine cancellation to OkHttp calls.
|
||||
- `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.
|
||||
- `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.
|
||||
|
||||
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.
|
||||
@@ -13,6 +13,10 @@
|
||||
|
||||
播放请求按普通 Web 客户端获取服务端允许的视频流,优先选择不高于常规 1080P 的 H.264 与 AAC,适合已知的 32 位 ARM Android 11 电视。清晰度由实际返回的轨道决定,登录和会员权益仍以 B 站接口结果为准。HTTP 图片/CDN链接升级到 HTTPS。
|
||||
|
||||
获取播放地址和下载音视频必须共用 `BiliHttpClient.USER_AGENT`。播放器的独立 HTTP 数据源由 `mediaHttpDataSourceFactory` 创建,携带内容 Referer,保留 Range 请求,不携带账号 Cookie。2026-11-04 目标电视对照验证:旧 Android 播放器标识使多个 CDN 返回 HTTP 403;同一批地址改用接口的浏览器标识后,三个视频地址及三个音频地址均可读取 MP4 数据。
|
||||
|
||||
`PlaybackNetworkDiagnosticTest` 提供显式启用的真实网络诊断,默认测试不访问外部服务。它使用独立匿名内存会话,比较旧标识和生产数据源,仅报告 CDN 主机、状态码和媒体文件头,不读取用户登录状态,不输出 Cookie 或带签名的完整地址。
|
||||
|
||||
## 明确处理的限制
|
||||
|
||||
- 不绕过登录、会员、购买、区域、付费或 DRM 检查。
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# 搜索接口与范围
|
||||
|
||||
搜索直接使用 B 站官方 HTTPS 接口 `/x/web-interface/search/type`。三个分类分别传入 `video`、`media_ft` 和 `media_bangumi`,不使用第三方搜索、解析服务或作者自建接口。
|
||||
|
||||
## 搜索会话
|
||||
|
||||
官方搜索可能要求普通网站会话,即使用户没有登录。客户端首次搜索时,若没有对 `api.bilibili.com` 有效且未过期的 `buvid3` Cookie,就以现有浏览器 User-Agent 访问一次固定官方首页 `https://www.bilibili.com/`,只接收 Cookie 响应头并关闭响应,不读取、解析或执行首页内容。
|
||||
|
||||
该流程使用已有的 Cookie 域名、HTTPS、过期时间和登录 epoch 检查,Cookie 仍由 Android Keystore 加密保存,不输出值,不发送给图片或媒体 CDN。不伪造 `buvid3`,不额外提交设备指纹,不引入统计 SDK。有效会话存在时直接复用,Mutex 避免并发重复初始化。用户退出登录会清除这些 Cookie。
|
||||
|
||||
## 接口验证
|
||||
|
||||
2026-11-03 电脑侧匿名只读探测:
|
||||
|
||||
- 无有效网站 Cookie 时,服务端可能返回 `code=0`、`data={v_voucher: ...}`。这是一种风控挑战,不是“没有搜索结果”。客户端明确显示风控失败,不静默变成空列表。
|
||||
- 从官方首页获得真实 `buvid3` 后,普通 type 接口对“三体”的视频、番剧查询返回真实结果,对“流浪地球”的电影查询返回真实结果。
|
||||
- 对“三体”的电影查询确实无结果;响应有 `numResults=0`,但缺少 `result` 字段。只有明确的零数量元数据才允许把缺失结果当作空列表。
|
||||
- 同一真实会话、有效 WBI 签名下的 `/x/web-interface/wbi/search/type` 仍返回风控凭据。因此当前采用经过验证的普通官方 type 路径,不因接口名包含 WBI 就假定可用,也不反复重试风控挑战。
|
||||
|
||||
## 解析与分页
|
||||
|
||||
视频卡片保留 64 位 AV 标识及 BV 号,移除服务端标题的高亮标签,安全解码常见/numeric HTML 实体。时长如 `220:7` 规范为 `3:40:07`。
|
||||
|
||||
电影和番剧使用 `season_id` / `pgc_season_id` 及有效集数 ID,绝不把 `media_id` 当作季 ID。必要时只从 B 站官方播放 URL 识别 `ss` 或 `ep` 引用。卡片保留会员标签并复用现有详情、选集和权益检查。
|
||||
|
||||
分页以服务端实际页码、总页数或总数量为准,最多 50 页;未知分页停止追加,倒退页码不会导致循环加载。单页按内容标识去重,跨页去重由搜索状态控制器负责。
|
||||
|
||||
纯解析测试覆盖真实响应结构、标题/实体、长 ID、PGC 标识、会员标签、安全 URL、真正空结果、风控挑战、格式异常、分页边界及去重。上述接口探测不涉及用户账号或电视,应用验证另见 [VALIDATION.md](VALIDATION.md)。
|
||||
@@ -7,13 +7,18 @@ At a typical 960 × 540 dp TV viewport, the home screen has 38 dp horizontal and
|
||||
## Remote
|
||||
|
||||
- Home: direction keys move among tabs, cards, refresh, account and load more. Confirm selects a tab or opens video details. Back from the grid returns focus to the selected tab. Android's normal back handling applies from the header.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
The player requests signed CDN URLs with a Bilibili Referer and browser User-Agent, without account cookies. It merges separate AVC/AAC fMP4 tracks through Media3, can use official backup CDN URLs after connection failure, and hides raw decoder/network exceptions that might include signed URLs. Actual decoder/remote behavior still needs testing on the target TV.
|
||||
|
||||
## Visual review
|
||||
|
||||
Prefer an emulator screenshot of the real Compose UI. If an HTML preview is used before an emulator is available, label it as a layout preview, use the dimensions/palette above and real fetched API data, and do not treat it as runtime verification. Community screenshots from unrelated clients are not assets for this app.
|
||||
|
||||
Current search runtime screenshots: [video results](screenshots/search.png) and [bangumi results](screenshots/search-bangumi.png).
|
||||
+30
-4
@@ -1,8 +1,8 @@
|
||||
# v0.1.0-alpha 验证记录
|
||||
# 验证记录
|
||||
|
||||
日期:2026-11-03。
|
||||
记录范围:2026-11-03 至 2026-11-04。
|
||||
|
||||
## 已验证
|
||||
## v0.1.0-alpha 已验证
|
||||
|
||||
- 使用 Gradle 8.9、JDK 17、Android SDK 35 构建开发版 APK。
|
||||
- JVM 单元测试:30 项通过,0 失败。覆盖 Cookie 域名/路径/HTTPS/有效期隔离、账号切换与退出后的迟到响应、WBI 签名、内容解析、播放格式与权限判断、遥控器跳转边界、错误提示不泄露原始网络地址。
|
||||
@@ -20,7 +20,33 @@
|
||||
- ARM32 雷鸟/TCL 电视的真实解码器、遥控器、焦点和分辨率适配。
|
||||
- 网络变化、官方接口或风控策略变化下的长期稳定性。
|
||||
|
||||
本次没有连接或安装到用户电视;设备测试固定使用 `emulator-5580`。
|
||||
首个 alpha 验证时没有连接或安装到用户电视;该阶段设备测试固定使用 `emulator-5580`。后续实机记录见下文。
|
||||
|
||||
## v0.1.1 搜索功能
|
||||
|
||||
- 开发版构建和 Android Lint 通过。
|
||||
- JVM 测试共 55 项通过,0 失败;新增 18 项搜索解析测试和 7 项搜索状态测试。覆盖官方响应格式、长 ID、会员标签、空结果和风控区别、分页边界、重复提交、取消后的迟到响应、清空/关闭、分类切换、跨页去重、草稿与已提交关键词隔离、失败重试及 Unicode 输入边界。
|
||||
- Android 11 ARM64 模拟器共 11 项设备测试通过,0 失败;新增 6 项搜索测试,验证从首页用方向键打开、中文输入和 IME 搜索提交、方向键切换分类、覆盖层焦点隔离和返回恢复、分页中焦点保持、追加结果后进入第一张新卡片及末页恢复。
|
||||
- 电脑侧匿名官方接口探测验证“三体”视频/番剧、“流浪地球”电影及真正零结果;Android 应用在模拟器中实际搜索“Switch”视频(1000 个结果)、“Fate”番剧(14 个结果)和“2”电影(56 个结果),显示远程封面、标题、附加信息和结果数量。`screenshots/search.png` 和 `screenshots/search-bangumi.png` 是真实运行截图。
|
||||
- 真实电影搜索追加第二页后,已在模拟器确认滚动并聚焦到第一张新增卡片。
|
||||
- 搜索复用既有详情和播放功能。完整真实账号与播放验证、目标电视输入法和遥控器仍待实测。
|
||||
- 搜索功能最初在电脑模拟器验证,之后随播放修复部署到目标电视,见后续记录。原 `v0.1.0-alpha` Git 标签保留。
|
||||
|
||||
## 目标电视安装 — 2026-11-04
|
||||
|
||||
- 已通过 ADB 在雷鸟/TCL 电视 `192.168.1.20:5555` 安装包含搜索功能的开发版,安装返回 `Success`。
|
||||
- 电视型号标识 `t982_ar31a8`,支持 `armeabi-v7a,armeabi`。
|
||||
- 启动返回 `Status: ok`,前台 Activity 确认为 `dev.bulubulu.tv/.MainActivity`。
|
||||
- 安装和启动通过;真实遥控器、输入法、登录和播放效果等待用户实测。
|
||||
|
||||
## 电视播放 HTTP 403 修复 — 2026-11-04
|
||||
|
||||
- 用户实测多段视频均提示“视频地址暂不可用”。通过独立匿名内存会话在目标电视对同一批地址进行对照:旧播放器 Android User-Agent 在四个备选 CDN 请求上得到 HTTP 403,而接口所用的浏览器 User-Agent 能读取全部三个视频和三个音频地址。
|
||||
- 播放器改用 `mediaHttpDataSourceFactory`,与接口共用 `BiliHttpClient.USER_AGENT`;内容 Referer、Range 和 CDN Cookie 隔离保持原有策略。
|
||||
- 修复版已覆盖安装;生产数据源的显式实机网络诊断通过,六个音视频候选地址均读取到 MP4 文件头。诊断不访问用户 Cookie,也不记录完整签名地址;临时安装的测试包已移除。
|
||||
- 电视实际播放投稿视频,界面显示 1080P,画面和播放进度正常推进至 `00:37 / 07:25`。`screenshots/playback-tv.png` 是实机运行截图。未据此宣称完整片长、听感、音画同步和所有会员内容均已验证。
|
||||
- 此次构建、55 项 JVM 测试和 Android Lint 通过。新增的真实网络诊断默认跳过,须传入 `livePlayback=true` 显式启用。
|
||||
- 用户实测后确认播放恢复正常,并同意提交为 `v0.1.1`;应用版本号为 `0.1.1`,Android `versionCode` 递增为 `2`。
|
||||
|
||||
## 复现
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 526 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 835 KiB |
Reference in new issue
Block a user