feat: release v0.1.1 with search and playback fix

This commit is contained in:
loveuer committed 2026-11-04 08:33:41 +08:00
1 parent 52c840661b
commit 93f1221e6a
27 files changed
+1576 -23

No files matched your search

+2 -2
View File
@@ -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 &amp; 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>&nbsp;&amp; &quot;TV&quot; &#39; &#x1F680; &lt;原著&gt;"),
)
assertEquals("三体", SearchJson.plainText("<!--注释--><script>ignore()</script><style>ignore</style>三体"))
assertEquals("\uFFFD\uFFFD", SearchJson.plainText("&#x110000;&#55296;"))
assertEquals("&unknown;", SearchJson.plainText("&unknown;"))
assertFalse(SearchJson.plainText("甲&#1;乙").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)
}
}