Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8cd96eb5e | ||
|
|
93f1221e6a |
No files matched your search
@@ -1,5 +1,26 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.1.2 — 2026-11-04
|
||||||
|
|
||||||
|
新增播放清晰度选择;电视实机验证待进行。
|
||||||
|
|
||||||
|
- 新增遥控器清晰度菜单:播放中按上键,再确认打开;只展示当前视频实际可用的 H.264 档位。
|
||||||
|
- 手动切换保留播放进度和暂停状态,加载失败时尝试恢复原清晰度;选择当前档位不会重新加载。
|
||||||
|
- 沿用官方接口返回的清晰度名称与账号权限,默认仍选择不高于普通 1080P 的最佳档位。
|
||||||
|
- 完善清晰度菜单的窗口焦点恢复和全屏处理,沿用播放器的请求头与备用 CDN。
|
||||||
|
- 69 项 JVM 测试、14 项常规模拟器设备测试及构建、Android Lint 通过。真实视频曾成功切换;后续模拟器解码异常,完整双向切换、暂停后切换与电视实机表现仍待验证。
|
||||||
|
|
||||||
|
## v0.1.1 — 2026-11-04
|
||||||
|
|
||||||
|
新增搜索,并修复目标电视上视频服务器返回 HTTP 403 导致无法播放的问题。
|
||||||
|
|
||||||
|
- 修复播放接口与播放器 User-Agent 不一致导致多个 CDN 返回 HTTP 403、视频无法播放的问题。
|
||||||
|
- 顶部新增搜索入口,系统输入法输入,确认后请求官方视频 / 电影 / 番剧搜索。
|
||||||
|
- 支持结果分页、去重、失败重试和空结果;风控挑战单独提示。
|
||||||
|
- 复用详情、选集和播放,返回恢复搜索结果焦点;关闭搜索清空临时内容,不保存历史。
|
||||||
|
- 取消或切换查询后隔离迟到响应,退出登录时清除搜索状态。
|
||||||
|
- 55 项 JVM 测试、11 项模拟器设备测试及显式实机网络诊断通过;目标电视已验证 1080P 短时播放,用户确认恢复正常。
|
||||||
|
|
||||||
## v0.1.0-alpha — 2026-11-03
|
## v0.1.0-alpha — 2026-11-03
|
||||||
|
|
||||||
第一个可以构建并在模拟器运行的个人使用版本。
|
第一个可以构建并在模拟器运行的个人使用版本。
|
||||||
|
|||||||
@@ -1,21 +1,27 @@
|
|||||||
# bulubulu
|
# bulubulu
|
||||||
|
|
||||||
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧和播放,把交互留给遥控器。
|
一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧、搜索和播放,把交互留给遥控器。
|
||||||
|
|
||||||
当前版本:**v0.1.0-alpha**。
|
当前版本:**v0.1.2**。新增清晰度选择,电视实机验证待进行,详见 [验证记录](docs/VALIDATION.md)。
|
||||||
|
|
||||||

|

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

|
||||||
|
|
||||||
|
## 已有功能
|
||||||
|
|
||||||
- 使用哔哩哔哩手机客户端扫码并确认登录,不输入账号密码。
|
- 使用哔哩哔哩手机客户端扫码并确认登录,不输入账号密码。
|
||||||
- 推荐视频、电影和番剧三个页签,接入真实官方接口,支持刷新和分页。
|
- 推荐视频、电影和番剧三个页签,接入真实官方接口,支持刷新和分页。
|
||||||
|
- 顶部「搜索」入口:系统输入法输入关键词,确认后搜索;支持视频 / 电影 / 番剧分类、分页和失败重试。
|
||||||
- 视频详情、投稿分 P、番剧选集。
|
- 视频详情、投稿分 P、番剧选集。
|
||||||
- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。
|
- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。
|
||||||
|
- 播放中手动选择清晰度,保留播放进度和暂停状态;切换失败时尝试恢复原档位。
|
||||||
- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。
|
- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。
|
||||||
- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。
|
- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。
|
||||||
|
|
||||||
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。第一版没有搜索、弹幕、历史同步、追番管理和播放清晰度菜单。
|
这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。目前没有弹幕、历史同步和追番管理。
|
||||||
|
|
||||||
## 遥控器
|
## 遥控器
|
||||||
|
|
||||||
@@ -23,12 +29,17 @@
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 首页 / 选集 | 方向键移动,确认键选择 |
|
| 首页 / 选集 | 方向键移动,确认键选择 |
|
||||||
| 首页内容区 | 返回键把焦点移回当前页签 |
|
| 首页内容区 | 返回键把焦点移回当前页签 |
|
||||||
|
| 搜索 | 确认输入框打开系统键盘,键盘搜索键或页面「搜索」提交;向下进入分类和结果 |
|
||||||
|
| 搜索结果 | 确认打开详情;返回键先收起键盘,再返回分类,最后退出搜索 |
|
||||||
| 弹窗 | 返回键关闭 |
|
| 弹窗 | 返回键关闭 |
|
||||||
| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 |
|
| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 |
|
||||||
| 播放中 | 上下显示控制栏,返回退出播放器 |
|
| 播放中 | 上键聚焦「清晰度」,确认打开菜单;下键回到画面,返回退出播放器 |
|
||||||
|
| 清晰度菜单 | 上下选择,确认切换;返回关闭菜单 |
|
||||||
|
|
||||||
在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。
|
在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。
|
||||||
|
|
||||||
|
清晰度菜单只列出官方接口本次实际返回的 H.264 档位,可选项取决于视频和账号权限。默认选择不高于普通 1080P 的最佳档位;手动切换会短暂重新缓冲,新视频重新使用默认选择,不自动按网速调整清晰度。
|
||||||
|
|
||||||
## 构建
|
## 构建
|
||||||
|
|
||||||
需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。
|
需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。
|
||||||
@@ -63,15 +74,18 @@ Cookie 通过 Android Keystore 的 AES-GCM 密钥加密,保存到禁止备份
|
|||||||
|
|
||||||
扫码使用独立内存会话,确认并验证账号后才保存;取消扫码会作废该尝试。退出先清除本地凭据,再尝试注销旧的官方会话。过期或迟到的网络响应不能把旧会话恢复回来。错误提示不会展示带签名的播放地址或原始网络异常。
|
扫码使用独立内存会话,确认并验证账号后才保存;取消扫码会作废该尝试。退出先清除本地凭据,再尝试注销旧的官方会话。过期或迟到的网络响应不能把旧会话恢复回来。错误提示不会展示带签名的播放地址或原始网络异常。
|
||||||
|
|
||||||
这不代表第三方客户端可以保证永久兼容:官方网页接口、风控和账号协议可能变化,目标电视的解码和遥控器还需实机检查。当前没有在用户电视上安装。
|
搜索关键词只在提交时发给 B 站官方接口,不逐字上传,不保存本地搜索历史,关闭搜索页即清空。首次搜索可能访问官方首页获取正常的网站 Cookie,只接收响应头,不执行网页脚本。系统输入法的联网和隐私行为取决于设备安装的输入法。
|
||||||
|
|
||||||
|
这不代表第三方客户端可以保证永久兼容:官方网页接口、风控和账号协议可能变化。已于 2026-11-04 在目标电视安装包含搜索功能的开发版,并修复 CDN 请求头不一致导致的 HTTP 403,实机验证了 1080P 短时播放。完整遥控器、输入法和长期播放表现仍需实测。
|
||||||
|
|
||||||
## 项目结构
|
## 项目结构
|
||||||
|
|
||||||
- `core/Models.kt`:共享数据模型与可展示的错误。
|
- `core/Models.kt`:共享数据模型与可展示的错误。
|
||||||
- `data/`:官方接口、WBI 签名、扫码会话与加密存储。
|
- `data/`:官方接口、WBI 签名、扫码会话与加密存储。
|
||||||
- `ui/`:首页、登录与选集弹窗、电视焦点组件。
|
- `search/`:临时搜索状态、取消与迟到响应隔离、跨页去重。
|
||||||
|
- `ui/`:首页、搜索、登录与选集弹窗、电视焦点组件。
|
||||||
- `player/`:Media3 播放、备选 CDN 和遥控器控制。
|
- `player/`:Media3 播放、备选 CDN 和遥控器控制。
|
||||||
- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。
|
- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。
|
||||||
- `docs/`:接口说明、设计说明和真实运行截图。
|
- `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"
|
applicationId = "dev.bulubulu.tv"
|
||||||
minSdk = 23
|
minSdk = 23
|
||||||
targetSdk = 34
|
targetSdk = 34
|
||||||
versionCode = 1
|
versionCode = 3
|
||||||
versionName = "0.1.0-alpha"
|
versionName = "0.1.2"
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
}
|
}
|
||||||
buildFeatures { compose = true; buildConfig = true }
|
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,60 @@
|
|||||||
|
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
|
||||||
|
|
||||||
|
package dev.bulubulu.tv.player
|
||||||
|
|
||||||
|
import androidx.compose.ui.input.key.Key
|
||||||
|
import androidx.compose.ui.test.assertIsFocused
|
||||||
|
import androidx.compose.ui.test.assertIsNotEnabled
|
||||||
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
|
import androidx.compose.ui.test.onNodeWithTag
|
||||||
|
import androidx.compose.ui.test.performKeyInput
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import dev.bulubulu.tv.core.PlaybackQuality
|
||||||
|
import dev.bulubulu.tv.core.PlaybackStream
|
||||||
|
import dev.bulubulu.tv.ui.BulubuluTheme
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class QualityNavigationTest {
|
||||||
|
@get:Rule val compose = createComposeRule()
|
||||||
|
private fun quality(id: Int) = PlaybackQuality(id, "清晰度 $id", PlaybackStream("https://cdn.example/$id.m4s"))
|
||||||
|
|
||||||
|
@Test fun currentQualityGetsFocusAndRemoteSelectsNextOption() {
|
||||||
|
var selected: Int? = null
|
||||||
|
compose.setContent {
|
||||||
|
BulubuluTheme {
|
||||||
|
QualityDialog(listOf(quality(80), quality(64), quality(32)), 80, false, { selected = it.id }, {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compose.mainClock.advanceTimeBy(300)
|
||||||
|
compose.onNodeWithTag("quality_80").assertIsFocused().performKeyInput {
|
||||||
|
keyDown(Key.DirectionDown); keyUp(Key.DirectionDown)
|
||||||
|
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
|
||||||
|
}
|
||||||
|
compose.runOnIdle { assertEquals(64, selected) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun lowerCurrentQualityIsScrolledIntoViewAndBackDismisses() {
|
||||||
|
var dismissed = false
|
||||||
|
compose.setContent {
|
||||||
|
BulubuluTheme {
|
||||||
|
QualityDialog(listOf(120, 116, 112, 80, 74, 64, 32, 16).map(::quality), 16, false, {}, { dismissed = true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compose.mainClock.advanceTimeBy(400)
|
||||||
|
compose.onNodeWithTag("quality_16").assertIsFocused()
|
||||||
|
InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(android.view.KeyEvent.KEYCODE_BACK)
|
||||||
|
compose.runOnIdle { assertEquals(true, dismissed) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun inFlightChangePreventsDuplicateSelectionAndKeepsCloseFocusable() {
|
||||||
|
compose.setContent {
|
||||||
|
BulubuluTheme { QualityDialog(listOf(quality(80), quality(32)), 80, true, {}, {}) }
|
||||||
|
}
|
||||||
|
compose.mainClock.advanceTimeBy(250)
|
||||||
|
compose.onNodeWithTag("quality_80").assertIsNotEnabled()
|
||||||
|
compose.onNodeWithTag("quality_32").assertIsNotEnabled()
|
||||||
|
compose.onNodeWithTag("quality_close").assertIsFocused()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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.VideoDetails
|
||||||
import dev.bulubulu.tv.core.VideoEpisode
|
import dev.bulubulu.tv.core.VideoEpisode
|
||||||
import dev.bulubulu.tv.core.VideoItem
|
import dev.bulubulu.tv.core.VideoItem
|
||||||
|
import dev.bulubulu.tv.core.SearchCategory
|
||||||
|
import dev.bulubulu.tv.search.SearchController
|
||||||
import dev.bulubulu.tv.ui.HomeUiState
|
import dev.bulubulu.tv.ui.HomeUiState
|
||||||
import java.net.SocketTimeoutException
|
import java.net.SocketTimeoutException
|
||||||
import java.net.UnknownHostException
|
import java.net.UnknownHostException
|
||||||
@@ -51,6 +53,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
val playback = _playback.asStateFlow()
|
val playback = _playback.asStateFlow()
|
||||||
private val _notice = MutableStateFlow<String?>(null)
|
private val _notice = MutableStateFlow<String?>(null)
|
||||||
val notice = _notice.asStateFlow()
|
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 data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?)
|
||||||
private val feeds = mutableMapOf<ContentTab, CachedFeed>()
|
private val feeds = mutableMapOf<ContentTab, CachedFeed>()
|
||||||
@@ -197,6 +201,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
dismissLogin()
|
dismissLogin()
|
||||||
dismissDetails()
|
dismissDetails()
|
||||||
closePlayer()
|
closePlayer()
|
||||||
|
closeSearch()
|
||||||
feedJob?.cancel()
|
feedJob?.cancel()
|
||||||
feeds.clear()
|
feeds.clear()
|
||||||
_home.update { it.copy(account = null, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
|
_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 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) {
|
fun playbackError(message: String) {
|
||||||
showNotice(message)
|
showNotice(message)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import dev.bulubulu.tv.data.AuthRepository
|
|||||||
import dev.bulubulu.tv.data.BiliHttpClient
|
import dev.bulubulu.tv.data.BiliHttpClient
|
||||||
import dev.bulubulu.tv.data.ContentRepository
|
import dev.bulubulu.tv.data.ContentRepository
|
||||||
import dev.bulubulu.tv.data.SessionStore
|
import dev.bulubulu.tv.data.SessionStore
|
||||||
|
import dev.bulubulu.tv.data.SearchRepository
|
||||||
|
|
||||||
class BulubuluApplication : Application() {
|
class BulubuluApplication : Application() {
|
||||||
val sessionStore by lazy { SessionStore(this) }
|
val sessionStore by lazy { SessionStore(this) }
|
||||||
val http by lazy { BiliHttpClient(sessionStore) }
|
val http by lazy { BiliHttpClient(sessionStore) }
|
||||||
val auth by lazy { AuthRepository(http, sessionStore) }
|
val auth by lazy { AuthRepository(http, sessionStore) }
|
||||||
val content by lazy { ContentRepository(http) }
|
val content by lazy { ContentRepository(http) }
|
||||||
|
val search by lazy { SearchRepository(http) }
|
||||||
}
|
}
|
||||||
@@ -28,6 +28,7 @@ import dev.bulubulu.tv.ui.BulubuluHome
|
|||||||
import dev.bulubulu.tv.ui.BulubuluTheme
|
import dev.bulubulu.tv.ui.BulubuluTheme
|
||||||
import dev.bulubulu.tv.ui.DetailsDialog
|
import dev.bulubulu.tv.ui.DetailsDialog
|
||||||
import dev.bulubulu.tv.ui.LoginDialog
|
import dev.bulubulu.tv.ui.LoginDialog
|
||||||
|
import dev.bulubulu.tv.ui.SearchScreen
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
private val model: AppViewModel by viewModels()
|
private val model: AppViewModel by viewModels()
|
||||||
@@ -45,13 +46,21 @@ class MainActivity : ComponentActivity() {
|
|||||||
val details by model.details.collectAsStateWithLifecycle()
|
val details by model.details.collectAsStateWithLifecycle()
|
||||||
val playback by model.playback.collectAsStateWithLifecycle()
|
val playback by model.playback.collectAsStateWithLifecycle()
|
||||||
val notice by model.notice.collectAsStateWithLifecycle()
|
val notice by model.notice.collectAsStateWithLifecycle()
|
||||||
|
val search by model.search.collectAsStateWithLifecycle()
|
||||||
var focusRestoreKey by remember { mutableIntStateOf(0) }
|
var focusRestoreKey by remember { mutableIntStateOf(0) }
|
||||||
var hadOverlay by remember { mutableStateOf(false) }
|
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) {
|
LaunchedEffect(overlay) {
|
||||||
if (hadOverlay && !overlay) focusRestoreKey++
|
if (hadOverlay && !overlay) focusRestoreKey++
|
||||||
hadOverlay = overlay
|
hadOverlay = overlay
|
||||||
}
|
}
|
||||||
|
LaunchedEffect(secondaryOverlay) {
|
||||||
|
if (hadSearchOverlay && !secondaryOverlay) searchFocusRestoreKey++
|
||||||
|
hadSearchOverlay = secondaryOverlay
|
||||||
|
}
|
||||||
Box(Modifier.fillMaxSize()) {
|
Box(Modifier.fillMaxSize()) {
|
||||||
BulubuluHome(
|
BulubuluHome(
|
||||||
state = home,
|
state = home,
|
||||||
@@ -63,7 +72,23 @@ class MainActivity : ComponentActivity() {
|
|||||||
onLogout = model::logout,
|
onLogout = model::logout,
|
||||||
focusRestoreKey = focusRestoreKey,
|
focusRestoreKey = focusRestoreKey,
|
||||||
active = !overlay,
|
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) {
|
if (login.visible) {
|
||||||
LoginDialog(login.code, login.status, login.loading, login.error, model::startQrLogin, model::dismissLogin)
|
LoginDialog(login.code, login.status, login.loading, login.error, model::startQrLogin, model::dismissLogin)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ data class VideoEpisode(
|
|||||||
)
|
)
|
||||||
data class VideoDetails(val title: String, val description: String, val episodes: List<VideoEpisode>)
|
data class VideoDetails(val title: String, val description: String, val episodes: List<VideoEpisode>)
|
||||||
data class PlaybackStream(val url: String, val backupUrls: List<String> = emptyList())
|
data class PlaybackStream(val url: String, val backupUrls: List<String> = emptyList())
|
||||||
|
data class PlaybackQuality(val id: Int, val label: String, val video: PlaybackStream)
|
||||||
data class PlaybackSource(
|
data class PlaybackSource(
|
||||||
val title: String,
|
val title: String,
|
||||||
val video: PlaybackStream,
|
val video: PlaybackStream,
|
||||||
@@ -34,6 +35,8 @@ data class PlaybackSource(
|
|||||||
val qualityLabel: String = "",
|
val qualityLabel: String = "",
|
||||||
val durationMs: Long = 0,
|
val durationMs: Long = 0,
|
||||||
val referer: String = "https://www.bilibili.com/",
|
val referer: String = "https://www.bilibili.com/",
|
||||||
|
val qualityId: Int = 0,
|
||||||
|
val qualities: List<PlaybackQuality> = emptyList(),
|
||||||
)
|
)
|
||||||
data class QrLoginCode(val url: String, val key: String)
|
data class QrLoginCode(val url: String, val key: String)
|
||||||
sealed interface QrLoginStatus {
|
sealed interface QrLoginStatus {
|
||||||
|
|||||||
@@ -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.Dispatchers
|
||||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import okhttp3.Call
|
import okhttp3.Call
|
||||||
import okhttp3.Callback
|
import okhttp3.Callback
|
||||||
import okhttp3.Cookie
|
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. */
|
/** Official HTTPS JSON API client. The raw client is also available for ordinary network consumers. */
|
||||||
class BiliHttpClient(storage: SessionCookieStore) {
|
class BiliHttpClient(storage: SessionCookieStore) {
|
||||||
private val cookies = BiliCookieJar(storage)
|
private val cookies = BiliCookieJar(storage)
|
||||||
|
private val webSessionMutex = Mutex()
|
||||||
|
|
||||||
val client: OkHttpClient = OkHttpClient.Builder()
|
val client: OkHttpClient = OkHttpClient.Builder()
|
||||||
.connectTimeout(15, TimeUnit.SECONDS)
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
@@ -89,7 +92,7 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
|||||||
chain.request().newBuilder()
|
chain.request().newBuilder()
|
||||||
.header("User-Agent", USER_AGENT)
|
.header("User-Agent", USER_AGENT)
|
||||||
.header("Referer", "https://www.bilibili.com/")
|
.header("Referer", "https://www.bilibili.com/")
|
||||||
.header("Accept", "application/json")
|
.header("Accept", chain.request().header("Accept") ?: "application/json")
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -136,6 +139,31 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
|||||||
return requestJson(Request.Builder().url(officialUrl(url)).post(body).build(), emptySet())
|
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()
|
fun clearSession() = cookies.clear()
|
||||||
|
|
||||||
internal fun adoptSession(newCookies: List<Cookie>) = cookies.replaceSession(newCookies)
|
internal fun adoptSession(newCookies: List<Cookie>) = cookies.replaceSession(newCookies)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import dev.bulubulu.tv.core.BiliApiException
|
|||||||
import dev.bulubulu.tv.core.ContentTab
|
import dev.bulubulu.tv.core.ContentTab
|
||||||
import dev.bulubulu.tv.core.FeedPage
|
import dev.bulubulu.tv.core.FeedPage
|
||||||
import dev.bulubulu.tv.core.PlaybackSource
|
import dev.bulubulu.tv.core.PlaybackSource
|
||||||
|
import dev.bulubulu.tv.core.PlaybackQuality
|
||||||
import dev.bulubulu.tv.core.PlaybackStream
|
import dev.bulubulu.tv.core.PlaybackStream
|
||||||
import dev.bulubulu.tv.core.VideoDetails
|
import dev.bulubulu.tv.core.VideoDetails
|
||||||
import dev.bulubulu.tv.core.VideoEpisode
|
import dev.bulubulu.tv.core.VideoEpisode
|
||||||
@@ -102,7 +103,9 @@ class ContentRepository(private val http: BiliHttpClient) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun resolvePlayback(episode: VideoEpisode): PlaybackSource {
|
suspend fun resolvePlayback(episode: VideoEpisode): PlaybackSource {
|
||||||
val common = mapOf("qn" to "80", "fnval" to "16", "fnver" to "0", "fourk" to "0")
|
// Ask for the available DASH ladder, but still start at no more than
|
||||||
|
// ordinary 1080P. The server enforces account rights for every URL.
|
||||||
|
val common = mapOf("qn" to "120", "fnval" to "16", "fnver" to "0", "fourk" to "1")
|
||||||
val response = if (episode.epId != null) {
|
val response = if (episode.epId != null) {
|
||||||
http.getJson(
|
http.getJson(
|
||||||
"$API/pgc/player/web/playurl",
|
"$API/pgc/player/web/playurl",
|
||||||
@@ -259,19 +262,18 @@ internal object ContentJson {
|
|||||||
}
|
}
|
||||||
val dash = data.optJSONObject("dash")
|
val dash = data.optJSONObject("dash")
|
||||||
if (dash != null) {
|
if (dash != null) {
|
||||||
val video = dash.optJSONArray("video").objects()
|
val candidates = dash.optJSONArray("video").objects()
|
||||||
.filter { stream ->
|
.filter { stream ->
|
||||||
val codec = stream.optString("codecs").lowercase()
|
val codec = stream.optString("codecs").lowercase()
|
||||||
(codec.startsWith("avc1") || stream.optInt("codecid") == 7) &&
|
(codec.startsWith("avc1") || (codec.isBlank() && stream.optInt("codecid") == 7)) &&
|
||||||
streamUrl(stream).isNotBlank()
|
stream.optInt("id") > 0 && streamUrl(stream).isNotBlank()
|
||||||
}
|
}
|
||||||
.let { candidates ->
|
.groupBy { it.optInt("id") }
|
||||||
val standard = candidates.filter { it.optInt("id", 80) <= 80 }
|
.values.map { variants -> variants.maxBy { it.optLong("bandwidth") } }
|
||||||
(standard.ifEmpty { candidates }).maxWithOrNull(
|
val standard = candidates.filter { it.optInt("id") <= 80 }
|
||||||
compareBy<JSONObject> { it.optInt("height") }
|
val video = (standard.ifEmpty { candidates }).maxWithOrNull(
|
||||||
.thenBy { it.optLong("bandwidth") },
|
compareBy<JSONObject> { it.optInt("height") }.thenBy { it.optLong("bandwidth") },
|
||||||
)
|
) ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
|
||||||
} ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
|
|
||||||
val audio = dash.optJSONArray("audio").objects()
|
val audio = dash.optJSONArray("audio").objects()
|
||||||
.filter { stream ->
|
.filter { stream ->
|
||||||
(stream.optString("codecs").startsWith("mp4a") || stream.optString("codecs").isBlank()) &&
|
(stream.optString("codecs").startsWith("mp4a") || stream.optString("codecs").isBlank()) &&
|
||||||
@@ -288,6 +290,11 @@ internal object ContentJson {
|
|||||||
durationMs = data.optLong("timelength").takeIf { it > 0 }
|
durationMs = data.optLong("timelength").takeIf { it > 0 }
|
||||||
?: (dash.optDouble("duration", 0.0) * 1_000).toLong(),
|
?: (dash.optDouble("duration", 0.0) * 1_000).toLong(),
|
||||||
referer = referer(episode),
|
referer = referer(episode),
|
||||||
|
qualityId = quality,
|
||||||
|
qualities = candidates.sortedByDescending { it.optInt("id") }.map { candidate ->
|
||||||
|
val id = candidate.optInt("id")
|
||||||
|
PlaybackQuality(id, qualityLabel(data, id), stream(candidate))
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val parts = data.optJSONArray("durl").objects()
|
val parts = data.optJSONArray("durl").objects()
|
||||||
@@ -305,6 +312,7 @@ internal object ContentJson {
|
|||||||
qualityLabel = qualityLabel(data, data.optInt("quality")),
|
qualityLabel = qualityLabel(data, data.optInt("quality")),
|
||||||
durationMs = data.optLong("timelength", part.optLong("length")),
|
durationMs = data.optLong("timelength", part.optLong("length")),
|
||||||
referer = referer(episode),
|
referer = referer(episode),
|
||||||
|
qualityId = data.optInt("quality"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
throw ClientException("没有获取到可播放的视频流,请确认已登录、账号权限及所在地区")
|
throw ClientException("没有获取到可播放的视频流,请确认已登录、账号权限及所在地区")
|
||||||
@@ -326,6 +334,8 @@ internal object ContentJson {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun qualityLabel(data: JSONObject, quality: Int): String {
|
private fun qualityLabel(data: JSONObject, quality: Int): String {
|
||||||
|
data.optJSONArray("support_formats").objects().firstOrNull { it.optInt("quality") == quality }
|
||||||
|
?.optString("new_description")?.takeIf { it.isNotBlank() }?.let { return it }
|
||||||
val ids = data.optJSONArray("accept_quality")
|
val ids = data.optJSONArray("accept_quality")
|
||||||
val descriptions = data.optJSONArray("accept_description")
|
val descriptions = data.optJSONArray("accept_description")
|
||||||
if (ids != null && descriptions != null) {
|
if (ids != null && descriptions != null) {
|
||||||
|
|||||||
@@ -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,35 @@
|
|||||||
|
@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
|
||||||
|
import dev.bulubulu.tv.core.PlaybackSource
|
||||||
|
import dev.bulubulu.tv.core.PlaybackStream
|
||||||
|
import androidx.media3.common.MediaItem
|
||||||
|
import androidx.media3.datasource.DataSource
|
||||||
|
import androidx.media3.exoplayer.source.MediaSource
|
||||||
|
import androidx.media3.exoplayer.source.MergingMediaSource
|
||||||
|
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||||
|
|
||||||
|
/** CDN requests must use the same browser identity as the playback API request. */
|
||||||
|
internal fun mediaHttpDataSourceFactory(referer: String): DefaultHttpDataSource.Factory =
|
||||||
|
DefaultHttpDataSource.Factory()
|
||||||
|
.setUserAgent(BiliHttpClient.USER_AGENT)
|
||||||
|
.setDefaultRequestProperties(mapOf("Referer" to referer))
|
||||||
|
.setConnectTimeoutMs(15_000)
|
||||||
|
.setReadTimeoutMs(20_000)
|
||||||
|
.setAllowCrossProtocolRedirects(false)
|
||||||
|
|
||||||
|
internal fun playbackMediaSource(source: PlaybackSource, video: PlaybackStream = source.video): MediaSource {
|
||||||
|
val http = mediaHttpDataSourceFactory(source.referer)
|
||||||
|
val alternatives = buildMap {
|
||||||
|
put(video.url, video.backupUrls)
|
||||||
|
source.audio?.let { put(it.url, it.backupUrls) }
|
||||||
|
}
|
||||||
|
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
|
||||||
|
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
|
||||||
|
.createMediaSource(MediaItem.fromUri(url))
|
||||||
|
val videoSource = track(video.url)
|
||||||
|
return source.audio?.let { MergingMediaSource(true, true, videoSource, track(it.url)) } ?: videoSource
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package dev.bulubulu.tv.player
|
||||||
|
|
||||||
|
import dev.bulubulu.tv.core.PlaybackQuality
|
||||||
|
import dev.bulubulu.tv.core.PlaybackSource
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
internal data class PlaybackCheckpoint(val positionMs: Long, val playWhenReady: Boolean)
|
||||||
|
internal data class QualitySelectionState(
|
||||||
|
val current: PlaybackQuality,
|
||||||
|
val switchingTo: PlaybackQuality? = null,
|
||||||
|
val restoring: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Keeps a quality change transactional until both tracks are ready. Main-thread owned. */
|
||||||
|
internal class PlaybackQualitySwitcher(
|
||||||
|
source: PlaybackSource,
|
||||||
|
private val checkpoint: () -> PlaybackCheckpoint,
|
||||||
|
private val load: (PlaybackQuality, PlaybackCheckpoint) -> Unit,
|
||||||
|
) {
|
||||||
|
private val initial = source.qualities.firstOrNull { it.id == source.qualityId }
|
||||||
|
?: source.qualities.firstOrNull { it.video.url == source.video.url }
|
||||||
|
?: PlaybackQuality(source.qualityId, source.qualityLabel.ifBlank { "当前清晰度" }, source.video)
|
||||||
|
val options = (source.qualities + initial).distinctBy { it.id }.sortedByDescending { it.id }
|
||||||
|
private val _state = MutableStateFlow(QualitySelectionState(initial))
|
||||||
|
val state = _state.asStateFlow()
|
||||||
|
private data class Request(
|
||||||
|
val previous: PlaybackQuality,
|
||||||
|
val target: PlaybackQuality,
|
||||||
|
val checkpoint: PlaybackCheckpoint,
|
||||||
|
val restoring: Boolean = false,
|
||||||
|
)
|
||||||
|
private var pending: Request? = null
|
||||||
|
private var closed = false
|
||||||
|
|
||||||
|
fun select(id: Int): Boolean {
|
||||||
|
if (closed || pending != null || id == _state.value.current.id) return false
|
||||||
|
val target = options.firstOrNull { it.id == id } ?: return false
|
||||||
|
val request = Request(_state.value.current, target, checkpoint())
|
||||||
|
pending = request
|
||||||
|
_state.value = QualitySelectionState(request.previous, target)
|
||||||
|
return try {
|
||||||
|
load(target, request.checkpoint)
|
||||||
|
true
|
||||||
|
} catch (_: Exception) {
|
||||||
|
onFailure()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns true only after recovery is ready, so the UI can report it accurately. */
|
||||||
|
fun onReady(): Boolean {
|
||||||
|
if (closed) return false
|
||||||
|
val request = pending ?: return false
|
||||||
|
pending = null
|
||||||
|
_state.value = QualitySelectionState(if (request.restoring) request.previous else request.target)
|
||||||
|
return request.restoring
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A failed new source is restored once; failure of the original source is surfaced normally. */
|
||||||
|
fun onFailure(): Boolean {
|
||||||
|
if (closed) return false
|
||||||
|
val request = pending ?: return false
|
||||||
|
if (request.restoring) {
|
||||||
|
pending = null
|
||||||
|
_state.value = QualitySelectionState(request.previous)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
pending = request.copy(restoring = true)
|
||||||
|
_state.value = QualitySelectionState(request.previous, request.previous, restoring = true)
|
||||||
|
return try {
|
||||||
|
load(request.previous, request.checkpoint)
|
||||||
|
true
|
||||||
|
} catch (_: Exception) {
|
||||||
|
pending = null
|
||||||
|
_state.value = QualitySelectionState(request.previous)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() { closed = true; pending = null }
|
||||||
|
}
|
||||||
@@ -34,11 +34,14 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.focus.FocusRequester
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
import androidx.compose.ui.focus.focusRequester
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.focus.onFocusChanged
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.graphics.Brush
|
import androidx.compose.ui.graphics.Brush
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.platform.LocalWindowInfo
|
||||||
|
import androidx.compose.ui.platform.testTag
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -47,19 +50,14 @@ import androidx.compose.ui.viewinterop.AndroidView
|
|||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.LifecycleEventObserver
|
import androidx.lifecycle.LifecycleEventObserver
|
||||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import androidx.media3.common.AudioAttributes
|
import androidx.media3.common.AudioAttributes
|
||||||
import androidx.media3.common.C
|
import androidx.media3.common.C
|
||||||
import androidx.media3.common.MediaItem
|
|
||||||
import androidx.media3.common.PlaybackException
|
import androidx.media3.common.PlaybackException
|
||||||
import androidx.media3.common.Player
|
import androidx.media3.common.Player
|
||||||
import androidx.media3.datasource.DefaultHttpDataSource
|
|
||||||
import androidx.media3.datasource.DataSource
|
|
||||||
import androidx.media3.exoplayer.DefaultLoadControl
|
import androidx.media3.exoplayer.DefaultLoadControl
|
||||||
import androidx.media3.exoplayer.DefaultRenderersFactory
|
import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
import androidx.media3.exoplayer.source.MediaSource
|
|
||||||
import androidx.media3.exoplayer.source.MergingMediaSource
|
|
||||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
|
||||||
import androidx.media3.ui.PlayerView
|
import androidx.media3.ui.PlayerView
|
||||||
import dev.bulubulu.tv.core.PlaybackSource
|
import dev.bulubulu.tv.core.PlaybackSource
|
||||||
import dev.bulubulu.tv.ui.TvAccent
|
import dev.bulubulu.tv.ui.TvAccent
|
||||||
@@ -73,9 +71,14 @@ import kotlinx.coroutines.isActive
|
|||||||
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) {
|
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val lifecycleOwner = LocalLifecycleOwner.current
|
val lifecycleOwner = LocalLifecycleOwner.current
|
||||||
|
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||||
val errorCallback by rememberUpdatedState(onPlaybackError)
|
val errorCallback by rememberUpdatedState(onPlaybackError)
|
||||||
val focusRequester = remember { FocusRequester() }
|
val focusRequester = remember { FocusRequester() }
|
||||||
val retryFocus = remember { FocusRequester() }
|
val retryFocus = remember { FocusRequester() }
|
||||||
|
val qualityFocus = remember { FocusRequester() }
|
||||||
|
var qualityMenuOpen by remember(source) { mutableStateOf(false) }
|
||||||
|
var qualityButtonFocused by remember(source) { mutableStateOf(false) }
|
||||||
|
var focusQualityRequested by remember(source) { mutableStateOf(false) }
|
||||||
var isPlaying by remember(source) { mutableStateOf(false) }
|
var isPlaying by remember(source) { mutableStateOf(false) }
|
||||||
var buffering by remember(source) { mutableStateOf(true) }
|
var buffering by remember(source) { mutableStateOf(true) }
|
||||||
var ended by remember(source) { mutableStateOf(false) }
|
var ended by remember(source) { mutableStateOf(false) }
|
||||||
@@ -87,33 +90,35 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
var lastSeekEvent by remember(source) { mutableLongStateOf(0) }
|
var lastSeekEvent by remember(source) { mutableLongStateOf(0) }
|
||||||
val player = remember(context, source) {
|
val player = remember(context, source) {
|
||||||
androidx.media3.common.util.Log.setLogLevel(androidx.media3.common.util.Log.LOG_LEVEL_OFF)
|
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 alternatives = buildMap {
|
|
||||||
put(source.video.url, source.video.backupUrls)
|
|
||||||
source.audio?.let { put(it.url, it.backupUrls) }
|
|
||||||
}
|
|
||||||
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
|
|
||||||
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
|
|
||||||
.createMediaSource(MediaItem.fromUri(url))
|
|
||||||
val video = track(source.video.url)
|
|
||||||
val media = source.audio?.let { MergingMediaSource(true, true, video, track(it.url)) } ?: video
|
|
||||||
ExoPlayer.Builder(context)
|
ExoPlayer.Builder(context)
|
||||||
.setRenderersFactory(DefaultRenderersFactory(context).setEnableDecoderFallback(true))
|
.setRenderersFactory(DefaultRenderersFactory(context).setEnableDecoderFallback(true))
|
||||||
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(10_000, 30_000, 1_000, 2_000).build())
|
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(10_000, 30_000, 1_000, 2_000).build())
|
||||||
.build().apply {
|
.build().apply {
|
||||||
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
|
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
|
||||||
setHandleAudioBecomingNoisy(true)
|
setHandleAudioBecomingNoisy(true)
|
||||||
setMediaSource(media)
|
setMediaSource(playbackMediaSource(source))
|
||||||
playWhenReady = true
|
playWhenReady = true
|
||||||
prepare()
|
prepare()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DisposableEffect(player, lifecycleOwner) {
|
val qualitySwitcher = remember(player, source) {
|
||||||
|
PlaybackQualitySwitcher(
|
||||||
|
source,
|
||||||
|
checkpoint = { PlaybackCheckpoint(player.currentPosition.coerceAtLeast(0), player.playWhenReady) },
|
||||||
|
load = { quality, checkpoint ->
|
||||||
|
// Separate progressive tracks can change decoder dimensions/profile.
|
||||||
|
// Release the old track resources before preparing the replacement.
|
||||||
|
player.stop()
|
||||||
|
player.setMediaSource(playbackMediaSource(source, quality.video))
|
||||||
|
player.seekTo(checkpoint.positionMs)
|
||||||
|
player.playWhenReady = checkpoint.playWhenReady && lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
|
||||||
|
player.prepare()
|
||||||
|
position = checkpoint.positionMs
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val qualityState by qualitySwitcher.state.collectAsStateWithLifecycle()
|
||||||
|
DisposableEffect(player, lifecycleOwner, qualitySwitcher) {
|
||||||
val listener = object : Player.Listener {
|
val listener = object : Player.Listener {
|
||||||
override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }
|
override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }
|
||||||
override fun onPlaybackStateChanged(state: Int) {
|
override fun onPlaybackStateChanged(state: Int) {
|
||||||
@@ -121,9 +126,18 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
ended = state == Player.STATE_ENDED
|
ended = state == Player.STATE_ENDED
|
||||||
if (ended) controlsVisible = true
|
if (ended) controlsVisible = true
|
||||||
if (player.duration > 0) duration = player.duration
|
if (player.duration > 0) duration = player.duration
|
||||||
|
if (state == Player.STATE_READY && qualitySwitcher.onReady()) {
|
||||||
|
errorCallback("切换未成功,已恢复原清晰度")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
override fun onPlayerError(exception: PlaybackException) {
|
override fun onPlayerError(exception: PlaybackException) {
|
||||||
|
if (qualitySwitcher.onFailure()) {
|
||||||
|
buffering = true
|
||||||
|
return
|
||||||
|
}
|
||||||
buffering = false
|
buffering = false
|
||||||
|
qualityMenuOpen = false
|
||||||
|
focusQualityRequested = false
|
||||||
val message = when (exception.errorCode) {
|
val message = when (exception.errorCode) {
|
||||||
PlaybackException.ERROR_CODE_DECODING_FAILED,
|
PlaybackException.ERROR_CODE_DECODING_FAILED,
|
||||||
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
|
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
|
||||||
@@ -153,6 +167,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
onDispose {
|
onDispose {
|
||||||
lifecycleOwner.lifecycle.removeObserver(observer)
|
lifecycleOwner.lifecycle.removeObserver(observer)
|
||||||
player.removeListener(listener)
|
player.removeListener(listener)
|
||||||
|
qualitySwitcher.close()
|
||||||
player.release()
|
player.release()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -165,14 +180,21 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
delay(400)
|
delay(400)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LaunchedEffect(lastInteraction, isPlaying, error) {
|
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen) {
|
||||||
if (isPlaying && error == null) {
|
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen) {
|
||||||
delay(4_000)
|
delay(4_000)
|
||||||
controlsVisible = false
|
controlsVisible = false
|
||||||
} else {
|
} else {
|
||||||
controlsVisible = true
|
controlsVisible = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused) {
|
||||||
|
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && error == null && windowFocused) {
|
||||||
|
delay(100)
|
||||||
|
qualityFocus.requestFocus()
|
||||||
|
focusQualityRequested = false
|
||||||
|
}
|
||||||
|
}
|
||||||
LaunchedEffect(error) {
|
LaunchedEffect(error) {
|
||||||
if (error != null) { delay(100); retryFocus.requestFocus() }
|
if (error != null) { delay(100); retryFocus.requestFocus() }
|
||||||
}
|
}
|
||||||
@@ -190,9 +212,13 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
modifier = Modifier.fillMaxSize().background(Color.Black)
|
modifier = Modifier.fillMaxSize().background(Color.Black)
|
||||||
.focusRequester(focusRequester)
|
.focusRequester(focusRequester)
|
||||||
.onPreviewKeyEvent { event ->
|
.onPreviewKeyEvent { event ->
|
||||||
if (error != null) return@onPreviewKeyEvent false
|
if (error != null || qualityMenuOpen) return@onPreviewKeyEvent false
|
||||||
val native = event.nativeKeyEvent
|
val native = event.nativeKeyEvent
|
||||||
val key = native.keyCode
|
val key = native.keyCode
|
||||||
|
// Let the focused action receive its own confirm events.
|
||||||
|
if (qualityButtonFocused && key in setOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)) {
|
||||||
|
return@onPreviewKeyEvent false
|
||||||
|
}
|
||||||
val supported = key in setOf(
|
val supported = key in setOf(
|
||||||
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
|
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
|
||||||
KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY,
|
KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||||
@@ -214,7 +240,14 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
}
|
}
|
||||||
interact()
|
interact()
|
||||||
}
|
}
|
||||||
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> interact()
|
KeyEvent.KEYCODE_DPAD_UP -> {
|
||||||
|
interact()
|
||||||
|
focusQualityRequested = true
|
||||||
|
}
|
||||||
|
KeyEvent.KEYCODE_DPAD_DOWN -> {
|
||||||
|
interact()
|
||||||
|
focusRequester.requestFocus()
|
||||||
|
}
|
||||||
KeyEvent.KEYCODE_MEDIA_PLAY -> if (native.repeatCount == 0) { player.play(); interact() }
|
KeyEvent.KEYCODE_MEDIA_PLAY -> if (native.repeatCount == 0) { player.play(); interact() }
|
||||||
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (native.repeatCount == 0) { player.pause(); interact() }
|
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (native.repeatCount == 0) { player.pause(); interact() }
|
||||||
else -> if (native.repeatCount == 0) togglePlayback()
|
else -> if (native.repeatCount == 0) togglePlayback()
|
||||||
@@ -246,9 +279,20 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
}
|
}
|
||||||
if (controlsVisible && error == null) {
|
if (controlsVisible && error == null) {
|
||||||
Box(Modifier.fillMaxWidth().height(110.dp).align(Alignment.TopCenter).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent))))
|
Box(Modifier.fillMaxWidth().height(110.dp).align(Alignment.TopCenter).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent))))
|
||||||
Column(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp)) {
|
Row(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
Text(source.title, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
Text(source.title, color = TvText, fontSize = 21.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
if (source.qualityLabel.isNotBlank()) Text(source.qualityLabel, color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp))
|
Text(
|
||||||
|
when {
|
||||||
|
qualityState.restoring -> "正在恢复 ${qualityState.current.label}…"
|
||||||
|
qualityState.switchingTo != null -> "正在切换到 ${qualityState.switchingTo?.label}…"
|
||||||
|
else -> qualityState.current.label
|
||||||
|
},
|
||||||
|
color = TvMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus)
|
||||||
|
.onFocusChanged { qualityButtonFocused = it.isFocused }.testTag("quality_button"))
|
||||||
}
|
}
|
||||||
Column(
|
Column(
|
||||||
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||||
@@ -265,7 +309,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
|
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
|
||||||
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
|
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
|
||||||
}
|
}
|
||||||
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
error?.let { message ->
|
error?.let { message ->
|
||||||
@@ -283,5 +327,21 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (qualityMenuOpen) {
|
||||||
|
QualityDialog(
|
||||||
|
options = qualitySwitcher.options,
|
||||||
|
selectedId = qualityState.current.id,
|
||||||
|
switching = qualityState.switchingTo != null,
|
||||||
|
onSelected = { quality ->
|
||||||
|
qualityMenuOpen = false
|
||||||
|
focusQualityRequested = true
|
||||||
|
interact()
|
||||||
|
if (quality.id != qualityState.current.id && !qualitySwitcher.select(quality.id)) {
|
||||||
|
errorCallback("暂时无法切换清晰度,请重试")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onDismiss = { qualityMenuOpen = false; focusQualityRequested = true; interact() },
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package dev.bulubulu.tv.player
|
||||||
|
|
||||||
|
import androidx.compose.foundation.border
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.focus.FocusRequester
|
||||||
|
import androidx.compose.ui.focus.focusRequester
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.testTag
|
||||||
|
import androidx.compose.ui.platform.LocalView
|
||||||
|
import androidx.compose.ui.platform.LocalWindowInfo
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import androidx.compose.ui.window.DialogWindowProvider
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.core.view.WindowInsetsCompat
|
||||||
|
import androidx.core.view.WindowInsetsControllerCompat
|
||||||
|
import dev.bulubulu.tv.core.PlaybackQuality
|
||||||
|
import dev.bulubulu.tv.ui.TvAction
|
||||||
|
import dev.bulubulu.tv.ui.TvMuted
|
||||||
|
import dev.bulubulu.tv.ui.TvPanel
|
||||||
|
import dev.bulubulu.tv.ui.TvText
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun QualityDialog(
|
||||||
|
options: List<PlaybackQuality>,
|
||||||
|
selectedId: Int,
|
||||||
|
switching: Boolean,
|
||||||
|
onSelected: (PlaybackQuality) -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
val selectedFocus = remember { FocusRequester() }
|
||||||
|
val closeFocus = remember { FocusRequester() }
|
||||||
|
val list = rememberLazyListState()
|
||||||
|
val selectedIndex = options.indexOfFirst { it.id == selectedId }.coerceAtLeast(0)
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
|
||||||
|
) {
|
||||||
|
val view = LocalView.current
|
||||||
|
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||||
|
LaunchedEffect(view) {
|
||||||
|
// Keep the video surface at its fullscreen size while the menu owns focus.
|
||||||
|
(view.parent as? DialogWindowProvider)?.window?.let { window ->
|
||||||
|
WindowCompat.getInsetsController(window, view).apply {
|
||||||
|
hide(WindowInsetsCompat.Type.systemBars())
|
||||||
|
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LaunchedEffect(switching, windowFocused) {
|
||||||
|
if (!windowFocused) return@LaunchedEffect
|
||||||
|
if (switching || options.isEmpty()) {
|
||||||
|
delay(100)
|
||||||
|
closeFocus.requestFocus()
|
||||||
|
} else {
|
||||||
|
list.scrollToItem(selectedIndex)
|
||||||
|
delay(100)
|
||||||
|
selectedFocus.requestFocus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Surface(
|
||||||
|
color = TvPanel, contentColor = TvText, shape = RoundedCornerShape(22.dp),
|
||||||
|
modifier = Modifier.widthIn(max = 460.dp).fillMaxWidth(0.9f)
|
||||||
|
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)).testTag("quality_menu"),
|
||||||
|
) {
|
||||||
|
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Text("清晰度", fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
|
||||||
|
Text(
|
||||||
|
if (switching) "正在切换,请稍候…" else "切换后从当前进度继续",
|
||||||
|
color = TvMuted, fontSize = 14.sp,
|
||||||
|
)
|
||||||
|
LazyColumn(
|
||||||
|
state = list, modifier = Modifier.fillMaxWidth().heightIn(max = 210.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
items(options, key = { it.id }) { quality ->
|
||||||
|
val selected = quality.id == options.getOrNull(selectedIndex)?.id
|
||||||
|
TvAction(
|
||||||
|
quality.label + if (quality.id == selectedId) " · 当前" else "",
|
||||||
|
{ onSelected(quality) },
|
||||||
|
Modifier.fillMaxWidth().testTag("quality_${quality.id}").then(
|
||||||
|
if (selected) Modifier.focusRequester(selectedFocus) else Modifier,
|
||||||
|
),
|
||||||
|
selected = quality.id == selectedId, enabled = !switching,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
if (options.size == 1) "当前仅提供这一档清晰度" else "可选项取决于视频、账号权限和设备兼容性",
|
||||||
|
color = TvMuted, fontSize = 12.sp,
|
||||||
|
)
|
||||||
|
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus).testTag("quality_close"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
onLogout: () -> Unit,
|
||||||
focusRestoreKey: Int = 0,
|
focusRestoreKey: Int = 0,
|
||||||
active: Boolean = true,
|
active: Boolean = true,
|
||||||
|
onSearch: () -> Unit = {},
|
||||||
) {
|
) {
|
||||||
val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } }
|
val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } }
|
||||||
val accountFocus = remember { FocusRequester() }
|
val accountFocus = remember { FocusRequester() }
|
||||||
val refreshFocus = remember { FocusRequester() }
|
val refreshFocus = remember { FocusRequester() }
|
||||||
|
val searchFocus = remember { FocusRequester() }
|
||||||
val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
|
val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
|
||||||
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
|
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
|
||||||
val recommendGrid = rememberLazyGridState()
|
val recommendGrid = rememberLazyGridState()
|
||||||
@@ -92,6 +94,7 @@ fun BulubuluHome(
|
|||||||
when {
|
when {
|
||||||
lastFocusToken == "account" -> accountFocus.requestFocus()
|
lastFocusToken == "account" -> accountFocus.requestFocus()
|
||||||
lastFocusToken == "refresh" -> refreshFocus.requestFocus()
|
lastFocusToken == "refresh" -> refreshFocus.requestFocus()
|
||||||
|
lastFocusToken == "search" -> searchFocus.requestFocus()
|
||||||
lastFocusToken.startsWith("item:") -> {
|
lastFocusToken.startsWith("item:") -> {
|
||||||
val prefix = "item:${state.selectedTab.name}:"
|
val prefix = "item:${state.selectedTab.name}:"
|
||||||
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
|
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
|
||||||
@@ -121,6 +124,8 @@ fun BulubuluHome(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.weight(1f))
|
Spacer(Modifier.weight(1f))
|
||||||
|
TvAction("搜索", onSearch, Modifier.focusRequester(searchFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "search" })
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
if (state.authBusy) {
|
if (state.authBusy) {
|
||||||
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
|
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
|
||||||
} else if (state.account != null) {
|
} else if (state.account != null) {
|
||||||
@@ -209,7 +214,7 @@ fun BulubuluHome(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@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) }
|
var focused by remember { mutableStateOf(false) }
|
||||||
val focusEnabled = LocalTvFocusEnabled.current
|
val focusEnabled = LocalTvFocusEnabled.current
|
||||||
val scale by animateFloatAsState(if (focused) 1.025f else 1f, label = "posterFocus")
|
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,71 @@
|
|||||||
|
package dev.bulubulu.tv
|
||||||
|
|
||||||
|
import dev.bulubulu.tv.core.ClientException
|
||||||
|
import dev.bulubulu.tv.core.VideoEpisode
|
||||||
|
import dev.bulubulu.tv.data.ContentJson
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class PlaybackQualityJsonTest {
|
||||||
|
private val episode = VideoEpisode("p1", "P1", "视频", bvid = "BV1test", cid = 123)
|
||||||
|
|
||||||
|
@Test fun advertisedButUnavailableQualitiesAreNotSelectable() {
|
||||||
|
val source = parse("""{
|
||||||
|
"quality":64,"accept_quality":[112,80,64,32,16],
|
||||||
|
"accept_description":["1080P+","1080P","720P","480P","360P"],
|
||||||
|
"dash":{"video":[${video(32, 480)},${video(16, 360)}],"audio":[$audio]}
|
||||||
|
}""")
|
||||||
|
assertEquals(listOf(32, 16), source.qualities.map { it.id })
|
||||||
|
assertEquals(32, source.qualityId)
|
||||||
|
assertEquals("480P", source.qualityLabel)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun onlyCompatibleTracksAreKeptAndDuplicateRenditionsAreCombined() {
|
||||||
|
val higherBitrate = JSONObject(video(64, 720)).put("bandwidth", 2_000).put("baseUrl", "https://cdn.example/better.m4s")
|
||||||
|
.put("backupUrl", org.json.JSONArray("""["https://backup.example/better.m4s"]"""))
|
||||||
|
val source = parse("""{"dash":{"video":[
|
||||||
|
${video(80, 1080, "hvc1.1.6", 12)},${video(74, 720, "av01.0.08", 13)},
|
||||||
|
${video(64, 720)},$higherBitrate,${video(16, 360)}
|
||||||
|
],"audio":[$audio]}}""")
|
||||||
|
assertEquals(listOf(64, 16), source.qualities.map { it.id })
|
||||||
|
assertEquals("https://cdn.example/better.m4s", source.video.url)
|
||||||
|
assertEquals(listOf("https://backup.example/better.m4s"), source.qualities.first().video.backupUrls)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun higherAvailableQualitiesAreOfferedButDefaultRemainsOrdinary1080p() {
|
||||||
|
val source = parse("""{"support_formats":[{"quality":112,"new_description":"1080P 高码率"}],
|
||||||
|
"dash":{"video":[${video(120, 2160)},${video(112, 1080)},${video(80, 1080)},${video(32, 480)}],"audio":[$audio]}}
|
||||||
|
""")
|
||||||
|
assertEquals(80, source.qualityId)
|
||||||
|
assertEquals(listOf(120, 112, 80, 32), source.qualities.map { it.id })
|
||||||
|
assertEquals("1080P 高码率", source.qualities.first { it.id == 112 }.label)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun brokenAndContradictoryCodecTracksCannotBecomeOptions() {
|
||||||
|
val invalid = JSONObject(video(80, 1080)).put("baseUrl", "file:///private/data")
|
||||||
|
val source = parse("""{"dash":{"video":[
|
||||||
|
${video(80, 1080, "hvc1.1.6", 7)},$invalid,${video(16, 360)}
|
||||||
|
],"audio":[$audio]}}""")
|
||||||
|
assertEquals(listOf(16), source.qualities.map { it.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun missingAacIsRejectedForEveryQuality() {
|
||||||
|
try {
|
||||||
|
parse("""{"dash":{"video":[${video(80, 1080)}],"audio":[]}}""")
|
||||||
|
fail("A silent source must not be offered")
|
||||||
|
} catch (_: ClientException) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun progressiveSourceKeepsItsActualQuality() {
|
||||||
|
val source = parse("""{"quality":32,"durl":[{"url":"https://cdn.example/file.mp4"}]}""")
|
||||||
|
assertEquals(32, source.qualityId)
|
||||||
|
assertEquals("480P", source.qualityLabel)
|
||||||
|
assertTrue(source.qualities.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parse(value: String) = ContentJson.playback(JSONObject(value), episode)
|
||||||
|
private fun video(id: Int, height: Int, codec: String = "avc1.64001f", codecId: Int = 7) =
|
||||||
|
"""{"id":$id,"height":$height,"bandwidth":1000,"codecs":"$codec","codecid":$codecId,"baseUrl":"https://cdn.example/$id.m4s"}"""
|
||||||
|
private val audio = """{"codecs":"mp4a.40.2","baseUrl":"https://cdn.example/audio.m4s"}"""
|
||||||
|
}
|
||||||
@@ -0,0 +1,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,101 @@
|
|||||||
|
package dev.bulubulu.tv.player
|
||||||
|
|
||||||
|
import dev.bulubulu.tv.core.PlaybackQuality
|
||||||
|
import dev.bulubulu.tv.core.PlaybackSource
|
||||||
|
import dev.bulubulu.tv.core.PlaybackStream
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class PlaybackQualitySwitcherTest {
|
||||||
|
private val hd = PlaybackQuality(80, "1080P", PlaybackStream("https://cdn.example/hd.m4s"))
|
||||||
|
private val low = PlaybackQuality(32, "480P", PlaybackStream("https://cdn.example/low.m4s"))
|
||||||
|
private val source = PlaybackSource("投稿", hd.video, qualityLabel = hd.label, qualityId = hd.id, qualities = listOf(hd, low))
|
||||||
|
|
||||||
|
@Test fun selectionKeepsPositionAndOnlyCommitsAfterTracksAreReady() {
|
||||||
|
val checkpoint = PlaybackCheckpoint(94_600, true)
|
||||||
|
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
|
||||||
|
assertTrue(switcher.select(32))
|
||||||
|
assertEquals(listOf(low to checkpoint), loaded)
|
||||||
|
assertEquals(hd, switcher.state.value.current)
|
||||||
|
assertEquals(low, switcher.state.value.switchingTo)
|
||||||
|
assertFalse(switcher.onReady())
|
||||||
|
assertEquals(low, switcher.state.value.current)
|
||||||
|
assertNull(switcher.state.value.switchingTo)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun switchingPausedVideoDoesNotStartPlayback() {
|
||||||
|
var captured: PlaybackCheckpoint? = null
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(120_000, false) }) { _, at -> captured = at }
|
||||||
|
switcher.select(32)
|
||||||
|
assertEquals(PlaybackCheckpoint(120_000, false), captured)
|
||||||
|
switcher.onReady()
|
||||||
|
assertEquals(32, switcher.state.value.current.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun currentUnknownAndOverlappingChoicesDoNotReload() {
|
||||||
|
var requests = 0
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(100, true) }) { _, _ -> requests++ }
|
||||||
|
assertFalse(switcher.select(80))
|
||||||
|
assertFalse(switcher.select(120))
|
||||||
|
assertTrue(switcher.select(32))
|
||||||
|
assertFalse(switcher.select(80))
|
||||||
|
assertFalse(switcher.select(32))
|
||||||
|
assertEquals(1, requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun failedNewQualityRestoresOriginalProgressAndPausedStateOnce() {
|
||||||
|
val checkpoint = PlaybackCheckpoint(81_300, false)
|
||||||
|
val loaded = mutableListOf<Pair<PlaybackQuality, PlaybackCheckpoint>>()
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { checkpoint }) { quality, at -> loaded += quality to at }
|
||||||
|
switcher.select(32)
|
||||||
|
assertTrue(switcher.onFailure())
|
||||||
|
assertTrue(switcher.state.value.restoring)
|
||||||
|
assertEquals(listOf(low to checkpoint, hd to checkpoint), loaded)
|
||||||
|
assertTrue(switcher.onReady())
|
||||||
|
assertEquals(hd, switcher.state.value.current)
|
||||||
|
assertFalse(switcher.state.value.restoring)
|
||||||
|
assertNull(switcher.state.value.switchingTo)
|
||||||
|
assertFalse(switcher.onFailure())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun recoveryFailureIsSurfacedWithoutRetryLoop() {
|
||||||
|
var requests = 0
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(30_000, true) }) { _, _ -> requests++ }
|
||||||
|
switcher.select(32)
|
||||||
|
assertTrue(switcher.onFailure())
|
||||||
|
assertFalse(switcher.onFailure())
|
||||||
|
assertEquals(2, requests)
|
||||||
|
assertNull(switcher.state.value.switchingTo)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun closingRejectsLateCallbacksAndNewRequests() {
|
||||||
|
var requests = 0
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(0, true) }) { _, _ -> requests++ }
|
||||||
|
switcher.select(32)
|
||||||
|
switcher.close()
|
||||||
|
assertFalse(switcher.onReady())
|
||||||
|
assertFalse(switcher.onFailure())
|
||||||
|
assertFalse(switcher.select(80))
|
||||||
|
assertEquals(hd, switcher.state.value.current)
|
||||||
|
assertEquals(1, requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun progressiveVideoHasOneHonestChoice() {
|
||||||
|
val progressive = source.copy(qualities = emptyList())
|
||||||
|
val switcher = PlaybackQualitySwitcher(progressive, { PlaybackCheckpoint(0, true) }) { _, _ -> error("Unexpected reload") }
|
||||||
|
assertEquals(listOf(hd), switcher.options)
|
||||||
|
assertFalse(switcher.select(80))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun synchronousSourceFailureAlsoAttemptsRecovery() {
|
||||||
|
val loaded = mutableListOf<Int>()
|
||||||
|
val switcher = PlaybackQualitySwitcher(source, { PlaybackCheckpoint(42_000, true) }) { quality, _ ->
|
||||||
|
loaded += quality.id
|
||||||
|
if (quality.id == 32) throw IllegalArgumentException("invalid source")
|
||||||
|
}
|
||||||
|
assertTrue(switcher.select(32))
|
||||||
|
assertEquals(listOf(32, 80), loaded)
|
||||||
|
assertTrue(switcher.onReady())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,10 @@ 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.
|
- `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`.
|
- `SessionStore` encrypts cookies with an Android Keystore AES-GCM key and writes an atomic file in `noBackupFilesDir`.
|
||||||
- `ContentRepository` retrieves official catalogue/details/playback responses; `WbiSigner` caches official signing material; pure `ContentJson` parsing separates format and entitlement checks from transport.
|
- `ContentRepository` retrieves official catalogue/details/playback responses; `WbiSigner` caches official signing material; pure `ContentJson` parsing separates format and entitlement checks from transport.
|
||||||
|
- `SearchRepository` uses official category search and the shared first-party session; pure `SearchJson` parses highlights, content identifiers, rights badges and bounded pagination. `SearchController` owns draft/submitted queries, category, deduplicated pages and cancellable requests. A generation guard also rejects non-cooperative late responses after a new query, category, clear, close or logout. It keeps no durable history.
|
||||||
- `BulubuluHome`, dialogs and `TvAction` own TV layout/focus. Home stays composed beneath overlays, with focus/clicks disabled while inactive.
|
- `BulubuluHome`, dialogs and `TvAction` own TV layout/focus. Home stays composed beneath overlays, with focus/clicks disabled while inactive.
|
||||||
|
- `SearchScreen` uses the device IME and the existing card components. It stays composed beneath details/player and restores result focus independently of Home.
|
||||||
- `PlayerScreen` creates and releases Media3 with the composable lifecycle, merges separate AVC/AAC tracks and handles D-pad/media keys. CDN requests never receive account cookies.
|
- `PlayerScreen` creates and releases Media3 with the composable lifecycle, merges separate AVC/AAC tracks and handles D-pad/media keys. CDN requests never receive account cookies.
|
||||||
|
- `PlaybackQualitySwitcher` owns manual quality changes and commits the selected label only when the replacement source is ready. It preserves position/play intent, rejects overlapping requests and attempts the original source once after failure. `playbackMediaSource` shares HTTP identity, backup CDN handling and track merging between initial playback and changes. `QualityDialog` scrolls to and focuses the current actual track; one ExoPlayer is retained throughout the screen lifecycle.
|
||||||
|
|
||||||
There is no analytics, self-update service, local media scanning or private server. Login credentials and signed playback URLs must never appear in application logs or raw error messages. Account entitlements and region/DRM restrictions remain server-controlled. Tests use fake sessions in isolated storage and do not require a real account.
|
There is no analytics, self-update service, local media scanning or private server. Login credentials and signed playback URLs must never appear in application logs or raw error messages. Account entitlements and region/DRM restrictions remain server-controlled. Tests use fake sessions in isolated storage and do not require a real account.
|
||||||
@@ -13,6 +13,14 @@
|
|||||||
|
|
||||||
播放请求按普通 Web 客户端获取服务端允许的视频流,优先选择不高于常规 1080P 的 H.264 与 AAC,适合已知的 32 位 ARM Android 11 电视。清晰度由实际返回的轨道决定,登录和会员权益仍以 B 站接口结果为准。HTTP 图片/CDN链接升级到 HTTPS。
|
播放请求按普通 Web 客户端获取服务端允许的视频流,优先选择不高于常规 1080P 的 H.264 与 AAC,适合已知的 32 位 ARM Android 11 电视。清晰度由实际返回的轨道决定,登录和会员权益仍以 B 站接口结果为准。HTTP 图片/CDN链接升级到 HTTPS。
|
||||||
|
|
||||||
|
播放接口使用 `qn=120`、`fnval=16`、`fourk=1` 请求账号可用的 DASH 档位,首次播放仍优先选择不高于普通 1080P 的轨道。请求高档位不会预先下载该档位媒体,也不会扩大账号权益。菜单按实际 `dash.video` 中的 H.264 轨道生成,同一清晰度的重复轨道取码率较高的一条,并保留官方备用地址;音频复用本次返回的 AAC 轨道。只有单文件 progressive 时只显示当前一档。
|
||||||
|
|
||||||
|
清晰度名称优先读取 `support_formats[].new_description`,其次读取 `accept_description`,最后使用已知档位名称。`accept_quality` 和 `support_formats` 仅供描述,不能证明账号实际拿到了对应视频流。2026-11-04 匿名只读探测中,响应曾声明 1080P 高码率、1080P、720P 等档位,但实际 H.264 视频只有 480P / 360P;菜单据此只提供这两档。非 H.264、无有效 HTTPS 地址的轨道不会成为选项,会员、试看和 DRM 检查保持原有处理。
|
||||||
|
|
||||||
|
获取播放地址和下载音视频必须共用 `BiliHttpClient.USER_AGENT`。播放器的独立 HTTP 数据源由 `mediaHttpDataSourceFactory` 创建,携带内容 Referer,保留 Range 请求,不携带账号 Cookie。2026-11-04 目标电视对照验证:旧 Android 播放器标识使多个 CDN 返回 HTTP 403;同一批地址改用接口的浏览器标识后,三个视频地址及三个音频地址均可读取 MP4 数据。
|
||||||
|
|
||||||
|
`PlaybackNetworkDiagnosticTest` 提供显式启用的真实网络诊断,默认测试不访问外部服务。它使用独立匿名内存会话,比较旧标识和生产数据源,仅报告 CDN 主机、状态码和媒体文件头,不读取用户登录状态,不输出 Cookie 或带签名的完整地址。
|
||||||
|
|
||||||
## 明确处理的限制
|
## 明确处理的限制
|
||||||
|
|
||||||
- 不绕过登录、会员、购买、区域、付费或 DRM 检查。
|
- 不绕过登录、会员、购买、区域、付费或 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
-1
@@ -7,13 +7,19 @@ At a typical 960 × 540 dp TV viewport, the home screen has 38 dp horizontal and
|
|||||||
## Remote
|
## 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.
|
- 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.
|
- Details: first episode receives focus after loading. Confirm starts playback. Multi-part videos and series have an episode grid. Back closes the dialog.
|
||||||
- Login: QR code is generated locally with ZXing, not uploaded to a QR service. Refresh and close are D-pad targets. Closing cancels the parent-owned poll task. No password input is present.
|
- Login: QR code is generated locally with ZXing, not uploaded to a QR service. Refresh and close are D-pad targets. Closing cancels the parent-owned poll task. No password input is present.
|
||||||
- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up/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.
|
- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up reveals controls and focuses the top-right quality action; confirm opens its menu. Down returns focus to the video. Back exits playback directly. Both key-down and key-up are consumed so Android PlayerView cannot apply the same event twice. Controls remain visible when paused/end/error, while the quality action is focused or while its menu is open, and otherwise hide after four seconds during playback.
|
||||||
|
- Quality menu: the current option is marked and receives focus, scrolling into view if necessary. Up/down navigate and confirm selects. Back/Close returns focus to the quality action. Only actual compatible tracks are shown; a single available option is explained. Changes briefly rebuffer at the same position and retain pause/play intent. An in-flight change disables duplicate selection; failure attempts the original quality once and reports recovery after it is ready. Choosing the current option closes without reloading. This is manual selection; each new video starts at the default quality and there is no automatic bitrate adaptation.
|
||||||
- App backgrounding pauses the player; foregrounding resumes only if it was previously playing. Leaving the player releases Media3 and screen-on state.
|
- App backgrounding pauses the player; foregrounding resumes only if it was previously playing. Leaving the player releases Media3 and screen-on state.
|
||||||
|
|
||||||
|
Search remains composed beneath details and playback, with focus/clicks disabled while inactive. Returning restores the selected result and scroll position. Load more retains its focus during the request, then moves focus to the first appended result. If the final page adds no items, focus returns to the last result. Empty, error, risk-control and loading states do not use placeholder search results.
|
||||||
|
|
||||||
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.
|
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
|
## 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.
|
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).
|
||||||
+39
-5
@@ -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。
|
- 使用 Gradle 8.9、JDK 17、Android SDK 35 构建开发版 APK。
|
||||||
- JVM 单元测试:30 项通过,0 失败。覆盖 Cookie 域名/路径/HTTPS/有效期隔离、账号切换与退出后的迟到响应、WBI 签名、内容解析、播放格式与权限判断、遥控器跳转边界、错误提示不泄露原始网络地址。
|
- JVM 单元测试:30 项通过,0 失败。覆盖 Cookie 域名/路径/HTTPS/有效期隔离、账号切换与退出后的迟到响应、WBI 签名、内容解析、播放格式与权限判断、遥控器跳转边界、错误提示不泄露原始网络地址。
|
||||||
@@ -20,13 +20,47 @@
|
|||||||
- ARM32 雷鸟/TCL 电视的真实解码器、遥控器、焦点和分辨率适配。
|
- 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`。
|
||||||
|
|
||||||
|
## v0.1.2 清晰度选择 — 2026-11-04
|
||||||
|
|
||||||
|
- 匿名官方播放接口探测确认可取得多档 DASH 视频流;`qn=120`、`fnval=16`、`fourk=1` 请求成功,但账号无权取得的档位仍不会返回。样本中的 `accept_quality` 声明了 1080P / 720P 等档位,实际 H.264 轨道只有 480P / 360P;菜单以实际轨道为准。
|
||||||
|
- 开发版构建、Android Lint 和 69 项 JVM 测试通过,0 失败。新增 6 项解析测试和 8 项切换状态测试,覆盖实际轨道与声明档位的区别、编码过滤、重复轨道、默认清晰度、备用地址、位置与暂停意图保持、就绪后才提交选择、重复请求隔离、失败恢复和关闭后迟到回调。
|
||||||
|
- Android 11 ARM64 模拟器的 14 项常规设备测试通过,0 失败;另有 1 项显式网络诊断按默认设置跳过。新增 3 项清晰度菜单测试验证当前档位焦点、方向键选择、长列表滚动、返回关闭以及切换期间禁止重复选择。
|
||||||
|
- 实际匿名投稿视频曾从 480P 切到 360P,画面和进度继续推进至 `00:42 / 03:31`。后续双向切换与暂停状态的完整复测未完成:模拟器出现绿屏、Codec2 超时和宿主图形缓冲错误,重新启动后的首次播放也能复现,尚未完成原因隔离。单元测试通过不代表真实解码、音画同步和所有清晰度已经端到端验证。
|
||||||
|
- 本轮 ADB 连接目标电视超时,未把本功能覆盖安装到电视;最终实机双向切换、暂停后切换和高档位解码仍待验证。用户决定先提交为 `v0.1.2`,晚上进行电视实机验证;应用版本号更新为 `0.1.2`,Android `versionCode` 递增为 `3`,既有 `v0.1.1` 标签保留。
|
||||||
|
|
||||||
## 复现
|
## 复现
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
./gradlew assembleDebug testDebugUnitTest lintDebug
|
./gradlew assembleDebug testDebugUnitTest lintDebug
|
||||||
ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest
|
ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest -Pandroid.injected.device.serial=emulator-5580
|
||||||
```
|
```
|
||||||
|
|
||||||
设备测试需要已启动的模拟器。测试使用独立存储目录和假测试会话,不需要用户账号;Gradle 的 connected 测试任务可能在结束后移除测试安装的 APK。如需继续查看,运行 `./scripts/preview.sh` 重新部署到预览模拟器。
|
设备测试需要已启动的模拟器。测试使用独立存储目录和假测试会话,不需要用户账号;Gradle 的 connected 测试任务可能在结束后移除测试安装的 APK。如需继续查看,运行 `./scripts/preview.sh` 重新部署到预览模拟器。
|
||||||
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