feat: add bulubulu Android TV client v0.1.0-alpha

Implement official QR login with encrypted sessions, recommendation/movie/bangumi tabs, TV focus navigation and Media3 playback controls. Include Gradle wrapper, preview tooling, privacy protections, tests and documented alpha validation limits.
This commit is contained in:
loveuer committed 2026-11-03 22:57:04 +08:00
commit 52c840661b
52 files changed
+3766

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose")
}
android {
namespace = "dev.bulubulu.tv"
compileSdk = 35
buildToolsVersion = "35.0.0"
defaultConfig {
applicationId = "dev.bulubulu.tv"
minSdk = 23
targetSdk = 34
versionCode = 1
versionName = "0.1.0-alpha"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures { compose = true; buildConfig = true }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions { jvmTarget = "17" }
buildTypes {
release {
isMinifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" }
lint { abortOnError = true }
}
dependencies {
implementation(platform("androidx.compose:compose-bom:2024.10.01"))
implementation("androidx.core:core-ktx:1.13.1")
implementation("androidx.activity:activity-compose:1.9.3")
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.ui:ui-tooling-preview")
debugImplementation("androidx.compose.ui:ui-tooling")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("io.coil-kt:coil-compose:2.7.0")
implementation("com.google.zxing:core:3.5.3")
implementation("androidx.media3:media3-exoplayer:1.5.1")
implementation("androidx.media3:media3-exoplayer-dash:1.5.1")
implementation("androidx.media3:media3-ui:1.5.1")
testImplementation("junit:junit:4.13.2")
testImplementation("org.json:json:20240303")
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
androidTestImplementation(platform("androidx.compose:compose-bom:2024.10.01"))
androidTestImplementation("androidx.test.ext:junit:1.2.1")
androidTestImplementation("androidx.test:runner:1.6.2")
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
+2
View File
@@ -0,0 +1,2 @@
# Models and network payloads are parsed explicitly; no reflection-based JSON mapper.
-keepattributes Signature,InnerClasses,EnclosingMethod
@@ -0,0 +1,64 @@
package dev.bulubulu.tv
import android.content.Context
import android.content.ContextWrapper
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import dev.bulubulu.tv.data.SessionStore
import java.io.File
import java.util.UUID
import okhttp3.Cookie
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SessionStoreInstrumentedTest {
private lateinit var directory: File
private lateinit var context: Context
@Before fun setUp() {
val target = InstrumentationRegistry.getInstrumentation().targetContext
directory = File(target.cacheDir, "session-test-${UUID.randomUUID()}").apply { mkdirs() }
context = object : ContextWrapper(target) {
override fun getApplicationContext(): Context = this
override fun getNoBackupFilesDir(): File = directory
}
}
@After fun cleanUp() { directory.deleteRecursively() }
@Test fun keystoreEncryptedSessionSurvivesRecreationWithoutPlaintext() {
val sentinel = "test-private-session-${UUID.randomUUID()}"
val cookie = Cookie.Builder().name("SESSDATA").value(sentinel)
.domain("bilibili.com").path("/").secure().httpOnly()
.expiresAt(System.currentTimeMillis() + 60_000).build()
val first = SessionStore(context)
first.replaceCookies(listOf(cookie))
val encoded = File(directory, "session.enc").readBytes()
assertTrue(encoded.isNotEmpty())
assertFalse(encoded.toString(Charsets.ISO_8859_1).contains(sentinel))
assertFalse(encoded.toString(Charsets.ISO_8859_1).contains("SESSDATA"))
val reopened = SessionStore(context)
assertEquals(sentinel, reopened.allCookies().single().value)
assertTrue(reopened.allCookies().single().secure)
assertTrue(reopened.allCookies().single().httpOnly)
reopened.clear()
assertFalse(File(directory, "session.enc").exists())
assertTrue(SessionStore(context).allCookies().isEmpty())
}
@Test fun damagedCiphertextFailsClosedAndIsRemoved() {
val cookie = Cookie.Builder().name("SESSDATA").value("test-not-a-real-account")
.domain("bilibili.com").path("/").secure()
.expiresAt(System.currentTimeMillis() + 60_000).build()
SessionStore(context).replaceCookies(listOf(cookie))
val file = File(directory, "session.enc")
val bytes = file.readBytes()
bytes[bytes.lastIndex] = (bytes.last().toInt() xor 0x01).toByte()
file.writeBytes(bytes)
assertTrue(SessionStore(context).allCookies().isEmpty())
assertFalse(file.exists())
}
}
@@ -0,0 +1,93 @@
@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.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.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.onNodeWithText
import androidx.compose.ui.test.performKeyInput
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
class TvRemoteNavigationTest {
@get:Rule val compose = createComposeRule()
@Test fun tabsCanBeSelectedWithDpadAndCenter() {
val state = mutableStateOf(HomeUiState(loading = false, hasMore = false))
compose.setContent {
BulubuluTheme {
BulubuluHome(
state = state.value,
onTabSelected = { state.value = state.value.copy(selectedTab = it) },
onItemSelected = {}, onLoadMore = {}, onRefresh = {}, onLogin = {}, onLogout = {},
)
}
}
compose.mainClock.advanceTimeBy(200)
compose.onNode(hasText("推荐") and hasClickAction()).assertIsFocused().performKeyInput {
keyDown(Key.DirectionRight); keyUp(Key.DirectionRight)
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
}
compose.runOnIdle { assertEquals(ContentTab.MOVIE, state.value.selectedTab) }
compose.onNode(hasText("电影") and hasClickAction()).assertIsFocused()
}
@Test fun hiddenHomeDoesNotStealOverlayFocus() {
compose.setContent {
BulubuluTheme {
Box {
BulubuluHome(
state = HomeUiState(loading = false, hasMore = false),
onTabSelected = {}, onItemSelected = {}, onLoadMore = {}, onRefresh = {}, onLogin = {}, onLogout = {},
active = false,
)
val focus = remember { FocusRequester() }
Text("播放覆盖层", Modifier.focusRequester(focus).focusable())
LaunchedEffect(Unit) { focus.requestFocus() }
}
}
}
compose.mainClock.advanceTimeBy(250)
compose.onNodeWithText("播放覆盖层").assertIsFocused()
compose.onNode(hasText("推荐") and hasClickAction()).assertIsNotEnabled()
}
@Test fun episodesCanBeChosenWithDpadWithoutTouch() {
val episodes = listOf(
VideoEpisode(id = "first", label = "第1集", title = "第一集"),
VideoEpisode(id = "second", label = "第2集", title = "第二集"),
)
var chosen: VideoEpisode? = null
compose.setContent {
BulubuluTheme {
DetailsDialog(
details = VideoDetails("导航测试", "", episodes), loading = false, error = null,
onPlay = { chosen = it }, onRetry = {}, onDismiss = {},
)
}
}
compose.mainClock.advanceTimeBy(200)
compose.onNodeWithText("第1集").assertIsFocused().performKeyInput {
keyDown(Key.DirectionRight); keyUp(Key.DirectionRight)
keyDown(Key.DirectionCenter); keyUp(Key.DirectionCenter)
}
compose.runOnIdle { assertEquals(episodes[1], chosen) }
}
}
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.software.leanback" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application
android:name=".BulubuluApplication"
android:allowBackup="false"
android:fullBackupContent="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:usesCleartextTraffic="false"
android:icon="@drawable/app_icon"
android:banner="@drawable/app_banner"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Bulubulu">
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,294 @@
package dev.bulubulu.tv
import android.app.Application
import android.os.SystemClock
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.ClientException
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.core.QrLoginCode
import dev.bulubulu.tv.core.QrLoginStatus
import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode
import dev.bulubulu.tv.core.VideoItem
import dev.bulubulu.tv.ui.HomeUiState
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
data class LoginUiState(
val visible: Boolean = false,
val code: QrLoginCode? = null,
val status: QrLoginStatus? = null,
val loading: Boolean = false,
val error: String? = null,
)
data class DetailsUiState(
val visible: Boolean = false,
val details: VideoDetails? = null,
val loading: Boolean = false,
val error: String? = null,
)
class AppViewModel(application: Application) : AndroidViewModel(application) {
private val graph = application as BulubuluApplication
private val _home = MutableStateFlow(HomeUiState())
val home = _home.asStateFlow()
private val _login = MutableStateFlow(LoginUiState())
val login = _login.asStateFlow()
private val _details = MutableStateFlow(DetailsUiState())
val details = _details.asStateFlow()
private val _playback = MutableStateFlow<PlaybackSource?>(null)
val playback = _playback.asStateFlow()
private val _notice = MutableStateFlow<String?>(null)
val notice = _notice.asStateFlow()
private data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?)
private val feeds = mutableMapOf<ContentTab, CachedFeed>()
private var feedJob: Job? = null
private var loginJob: Job? = null
private var detailsJob: Job? = null
private var noticeJob: Job? = null
private var accountJob: Job? = null
private var logoutJob: Job? = null
private var selectedItem: VideoItem? = null
init {
accountJob = viewModelScope.launch {
try {
val account = graph.auth.currentAccount()
_home.update { it.copy(account = account) }
} catch (error: Exception) {
error.rethrowCancellation()
showNotice("登录状态暂时无法验证,已保留本地登录信息")
}
}
loadTab(ContentTab.RECOMMEND)
}
fun selectTab(tab: ContentTab) {
if (_home.value.authBusy) return
if (tab == _home.value.selectedTab) return
loadTab(tab)
}
fun refresh() {
if (!_home.value.authBusy) loadTab(_home.value.selectedTab, force = true)
}
private fun loadTab(tab: ContentTab, force: Boolean = false) {
feedJob?.cancel()
val cached = feeds[tab].takeUnless { force }
_home.update {
it.copy(
selectedTab = tab,
items = cached?.items.orEmpty(),
loading = cached == null,
loadingMore = false,
hasMore = cached?.nextPage != null,
error = null,
)
}
if (cached != null) return
feedJob = viewModelScope.launch {
try {
val result = graph.content.loadFeed(tab)
feeds[tab] = CachedFeed(result.items.distinctBy(VideoItem::id), result.nextPage)
_home.update {
it.copy(items = feeds.getValue(tab).items, loading = false, hasMore = result.nextPage != null)
}
} catch (error: Exception) {
error.rethrowCancellation()
_home.update { it.copy(loading = false, error = userMessage(error)) }
}
}
}
fun loadMore() {
val current = _home.value
if (current.loading || current.loadingMore || current.authBusy) return
val nextPage = feeds[current.selectedTab]?.nextPage ?: return
_home.update { it.copy(loadingMore = true, error = null) }
feedJob = viewModelScope.launch {
try {
val result = graph.content.loadFeed(current.selectedTab, nextPage)
val merged = (current.items + result.items).distinctBy(VideoItem::id)
// A repeated backend page must not leave an endless "load more" loop.
val following = result.nextPage.takeIf { merged.size > current.items.size }
feeds[current.selectedTab] = CachedFeed(merged, following)
_home.update { it.copy(items = merged, loadingMore = false, hasMore = following != null) }
} catch (error: Exception) {
error.rethrowCancellation()
_home.update { it.copy(loadingMore = false, error = userMessage(error)) }
}
}
}
fun openLogin() {
if (logoutJob?.isActive == true) return
accountJob?.cancel()
_login.value = LoginUiState(visible = true, loading = true)
startQrLogin()
}
fun startQrLogin() {
if (logoutJob?.isActive == true) return
accountJob?.cancel()
loginJob?.cancel()
graph.auth.cancelPendingLogin()
_login.value = LoginUiState(visible = true, loading = true)
loginJob = viewModelScope.launch {
try {
val code = graph.auth.generateQrCode()
_login.value = LoginUiState(visible = true, code = code, status = QrLoginStatus.WaitingForScan)
val deadline = SystemClock.elapsedRealtime() + 180_000L
while (SystemClock.elapsedRealtime() < deadline) {
delay(2_000)
val status = graph.auth.pollQrCode(code)
_login.update { it.copy(status = status) }
when (status) {
is QrLoginStatus.Success -> {
_home.update { it.copy(account = status.account) }
feeds.clear()
_login.value = LoginUiState()
refresh()
showNotice("已登录 ${status.account.name}")
return@launch
}
QrLoginStatus.Expired -> return@launch
else -> Unit
}
}
_login.update { it.copy(status = QrLoginStatus.Expired) }
} catch (error: Exception) {
error.rethrowCancellation()
_login.update { it.copy(loading = false, error = userMessage(error)) }
}
}
}
fun dismissLogin() {
loginJob?.cancel()
graph.auth.cancelPendingLogin()
_login.value = LoginUiState()
}
/** QR polling belongs to a visible foreground login screen. */
fun pauseLogin() {
loginJob?.cancel()
graph.auth.cancelPendingLogin()
if (_login.value.visible && _login.value.status !is QrLoginStatus.Success) {
_login.update { it.copy(loading = false, error = "扫码已暂停,请刷新二维码后继续") }
}
}
fun logout() {
if (logoutJob?.isActive == true) return
accountJob?.cancel()
dismissLogin()
dismissDetails()
closePlayer()
feedJob?.cancel()
feeds.clear()
_home.update { it.copy(account = null, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
logoutJob = viewModelScope.launch {
try {
graph.auth.logout()
} catch (error: Exception) {
error.rethrowCancellation()
// Local credentials are cleared even when the official logout endpoint is unavailable.
} finally {
_home.update { it.copy(account = null, authBusy = false) }
feeds.clear()
refresh()
}
showNotice("已退出登录并清除本机凭据")
}
}
fun openDetails(item: VideoItem) {
if (_home.value.authBusy) return
selectedItem = item
detailsJob?.cancel()
_details.value = DetailsUiState(visible = true, loading = true)
detailsJob = viewModelScope.launch {
try {
val result = graph.content.loadDetails(item)
_details.value = DetailsUiState(visible = true, details = result)
} catch (error: Exception) {
error.rethrowCancellation()
_details.update { it.copy(loading = false, error = userMessage(error)) }
}
}
}
fun retryDetails() {
val previous = _details.value.details
if (previous != null) {
_details.update { it.copy(error = null, loading = false) }
} else {
selectedItem?.let(::openDetails)
}
}
fun dismissDetails() {
detailsJob?.cancel()
_details.value = DetailsUiState()
}
fun play(episode: VideoEpisode) {
if (_details.value.loading) return
detailsJob?.cancel()
_details.update { it.copy(loading = true, error = null) }
detailsJob = viewModelScope.launch {
try {
val source = graph.content.resolvePlayback(episode)
val heading = _details.value.details?.title.orEmpty()
_playback.value = if (heading.isNotBlank() && heading != source.title) {
source.copy(title = "$heading · ${source.title}")
} else source
_details.value = DetailsUiState()
} catch (error: Exception) {
error.rethrowCancellation()
_details.update { it.copy(loading = false, error = userMessage(error)) }
}
}
}
fun closePlayer() { _playback.value = null }
fun playbackError(message: String) {
showNotice(message)
}
private fun showNotice(message: String) {
noticeJob?.cancel()
_notice.value = message
noticeJob = viewModelScope.launch {
delay(6_000)
_notice.value = null
}
}
}
internal fun userMessage(error: Throwable): String = when (error) {
is BiliApiException -> error.message?.take(180) ?: "B 站暂时无法完成此请求"
is ClientException -> error.message?.take(180) ?: "暂时无法完成请求,请重试"
is UnknownHostException -> "暂时无法连接网络,请检查网络后重试"
is SocketTimeoutException -> "请求超时,请稍后重试"
is java.io.IOException -> "网络请求失败,请稍后重试"
else -> "暂时无法完成请求,请重试"
}
private fun Throwable.rethrowCancellation() {
if (this is CancellationException) throw this
}
@@ -0,0 +1,14 @@
package dev.bulubulu.tv
import android.app.Application
import dev.bulubulu.tv.data.AuthRepository
import dev.bulubulu.tv.data.BiliHttpClient
import dev.bulubulu.tv.data.ContentRepository
import dev.bulubulu.tv.data.SessionStore
class BulubuluApplication : Application() {
val sessionStore by lazy { SessionStore(this) }
val http by lazy { BiliHttpClient(sessionStore) }
val auth by lazy { AuthRepository(http, sessionStore) }
val content by lazy { ContentRepository(http) }
}
@@ -0,0 +1,93 @@
package dev.bulubulu.tv
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
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.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import dev.bulubulu.tv.player.PlayerScreen
import dev.bulubulu.tv.ui.BulubuluHome
import dev.bulubulu.tv.ui.BulubuluTheme
import dev.bulubulu.tv.ui.DetailsDialog
import dev.bulubulu.tv.ui.LoginDialog
class MainActivity : ComponentActivity() {
private val model: AppViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.getInsetsController(window, window.decorView).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
setContent {
BulubuluTheme {
val home by model.home.collectAsStateWithLifecycle()
val login by model.login.collectAsStateWithLifecycle()
val details by model.details.collectAsStateWithLifecycle()
val playback by model.playback.collectAsStateWithLifecycle()
val notice by model.notice.collectAsStateWithLifecycle()
var focusRestoreKey by remember { mutableIntStateOf(0) }
var hadOverlay by remember { mutableStateOf(false) }
val overlay = login.visible || details.visible || playback != null || home.authBusy
LaunchedEffect(overlay) {
if (hadOverlay && !overlay) focusRestoreKey++
hadOverlay = overlay
}
Box(Modifier.fillMaxSize()) {
BulubuluHome(
state = home,
onTabSelected = model::selectTab,
onItemSelected = model::openDetails,
onLoadMore = model::loadMore,
onRefresh = model::refresh,
onLogin = model::openLogin,
onLogout = model::logout,
focusRestoreKey = focusRestoreKey,
active = !overlay,
)
if (login.visible) {
LoginDialog(login.code, login.status, login.loading, login.error, model::startQrLogin, model::dismissLogin)
}
if (details.visible) {
DetailsDialog(details.details, details.loading, details.error, model::play, model::retryDetails, model::dismissDetails)
}
playback?.let { PlayerScreen(it, model::closePlayer, model::playbackError) }
notice?.let { message ->
Surface(
modifier = Modifier.align(Alignment.BottomCenter).padding(24.dp),
color = Color(0xF0181F29),
contentColor = Color(0xFFF5F1ED),
shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp),
) {
Text(message, Modifier.padding(horizontal = 22.dp, vertical = 12.dp))
}
}
}
}
}
}
override fun onStop() {
model.pauseLogin()
super.onStop()
}
}
@@ -0,0 +1,47 @@
package dev.bulubulu.tv.core
enum class ContentTab(val title: String) {
RECOMMEND("推荐"), MOVIE("电影"), BANGUMI("番剧")
}
data class Account(val uid: Long, val name: String, val avatarUrl: String = "")
data class VideoItem(
val id: String,
val title: String,
val coverUrl: String,
val subtitle: String = "",
val bvid: String? = null,
val aid: Long? = null,
val seasonId: Long? = null,
val epId: Long? = null,
)
data class FeedPage(val items: List<VideoItem>, val nextPage: Int?)
data class VideoEpisode(
val id: String,
val label: String,
val title: String,
val bvid: String? = null,
val aid: Long? = null,
val cid: Long? = null,
val epId: Long? = null,
)
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 PlaybackSource(
val title: String,
val video: PlaybackStream,
val audio: PlaybackStream? = null,
val qualityLabel: String = "",
val durationMs: Long = 0,
val referer: String = "https://www.bilibili.com/",
)
data class QrLoginCode(val url: String, val key: String)
sealed interface QrLoginStatus {
data object WaitingForScan : QrLoginStatus
data object WaitingForConfirmation : QrLoginStatus
data object Expired : QrLoginStatus
data class Success(val account: Account) : QrLoginStatus
}
class BiliApiException(val apiCode: Int, message: String) : java.io.IOException(message)
/** A deliberately written user-facing failure, never a raw transport/URL exception. */
class ClientException(message: String) : java.io.IOException(message)
@@ -0,0 +1,161 @@
package dev.bulubulu.tv.data
import dev.bulubulu.tv.core.Account
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.QrLoginCode
import dev.bulubulu.tv.core.QrLoginStatus
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import java.io.IOException
import dev.bulubulu.tv.core.ClientException
/** Uses the official phone-confirmed QR flow; this application never asks for a password. */
class AuthRepository(
private val http: BiliHttpClient,
private val sessionStore: SessionStore,
) {
private class PendingLogin(
val store: InMemorySessionCookieStore = InMemorySessionCookieStore(),
) {
val http = BiliHttpClient(store)
var key: String? = null
}
private val pendingLock = Any()
private var pendingLogin: PendingLogin? = null
suspend fun currentAccount(): Account? = readAccount(http, clearUnauthenticatedSession = true)
private suspend fun readAccount(client: BiliHttpClient, clearUnauthenticatedSession: Boolean): Account? {
val json = client.getJson(NAV_URL, allowedApiCodes = setOf(-101))
val data = json.optJSONObject("data")
if (json.optInt("code") == -101) {
// Only an explicit unauthenticated response clears credentials. Network and risk-control
// failures propagate without destroying a potentially valid saved session.
if (clearUnauthenticatedSession) client.clearSession()
return null
}
if (data == null || !data.has("isLogin")) throw ClientException("登录验证响应不完整,请重试")
if (!data.optBoolean("isLogin")) {
if (clearUnauthenticatedSession) client.clearSession()
return null
}
val uid = data.optLong("mid")
if (uid <= 0) throw ClientException("登录验证返回了无效的账号信息,请重试")
return Account(
uid = uid,
name = data.optString("uname").ifBlank { "哔哩哔哩用户" },
avatarUrl = data.optString("face").let {
if (it.startsWith("http://")) "https://" + it.removePrefix("http://") else it
},
)
}
suspend fun generateQrCode(): QrLoginCode {
val attempt = PendingLogin()
synchronized(pendingLock) {
pendingLogin?.http?.clearSession()
pendingLogin = attempt
}
try {
val data = attempt.http.getJson("https://passport.bilibili.com/x/passport-login/web/qrcode/generate")
.optJSONObject("data") ?: throw ClientException("无法获取登录二维码,请重试")
val url = data.optString("url")
val key = data.optString("qrcode_key")
if (!url.startsWith("https://") || key.isBlank()) throw ClientException("登录二维码数据无效,请重试")
currentCoroutineContext().ensureActive()
synchronized(pendingLock) {
if (pendingLogin !== attempt) throw CancellationException("QR login replaced")
attempt.key = key
}
return QrLoginCode(url = url, key = key)
} catch (error: Exception) {
discard(attempt)
throw error
}
}
suspend fun pollQrCode(code: QrLoginCode): QrLoginStatus {
val attempt = synchronized(pendingLock) { pendingLogin?.takeIf { it.key == code.key } }
?: return QrLoginStatus.Expired
try {
val data = attempt.http.getJson(
"https://passport.bilibili.com/x/passport-login/web/qrcode/poll",
mapOf("qrcode_key" to code.key),
).optJSONObject("data") ?: throw ClientException("无法确认二维码状态,请重试")
return when (val status = data.optInt("code", -1)) {
86101 -> QrLoginStatus.WaitingForScan
86090 -> QrLoginStatus.WaitingForConfirmation
86038 -> {
discard(attempt)
QrLoginStatus.Expired
}
0 -> {
// Poll cookies remain in this attempt's memory until foreground verification
// completes. Cancelling/dismissing a QR dialog never silently signs in later.
val account = readAccount(attempt.http, clearUnauthenticatedSession = false)
?: throw ClientException("登录确认尚未完成,请重新生成二维码")
currentCoroutineContext().ensureActive()
synchronized(pendingLock) {
if (pendingLogin !== attempt) throw CancellationException("QR login cancelled")
http.adoptSession(attempt.store.allCookies())
attempt.http.clearSession()
pendingLogin = null
}
QrLoginStatus.Success(account)
}
else -> throw BiliApiException(
status,
data.optString("message").ifBlank { "二维码状态异常,请刷新重试" },
)
}
} catch (cancelled: CancellationException) {
discard(attempt)
throw cancelled
}
}
/** Call when the QR dialog closes or the activity leaves the foreground. */
fun cancelPendingLogin() = synchronized(pendingLock) {
pendingLogin?.let {
it.http.clearSession()
pendingLogin = null
}
}
suspend fun logout() {
cancelPendingLogin()
// Detach the old account before the network request. Its late response must never erase
// or replace a newer login, and offline users should not keep local credentials for 30s.
val revocationStore = InMemorySessionCookieStore(sessionStore.allCookies())
val revocationClient = BiliHttpClient(revocationStore)
http.clearSession()
try {
val csrf = revocationClient.csrfToken()
if (!csrf.isNullOrBlank()) {
try {
revocationClient.postFormJson(
"https://passport.bilibili.com/login/exit/v2",
mapOf("biliCSRF" to csrf, "gourl" to "https://www.bilibili.com/"),
)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (_: IOException) {
// Offline logout still erased the durable local session before this request.
}
}
} finally {
revocationClient.clearSession()
}
}
private fun discard(attempt: PendingLogin) = synchronized(pendingLock) {
attempt.http.clearSession()
if (pendingLogin === attempt) pendingLogin = null
}
private companion object {
const val NAV_URL = "https://api.bilibili.com/x/web-interface/nav"
}
}
@@ -0,0 +1,211 @@
package dev.bulubulu.tv.data
import dev.bulubulu.tv.core.BiliApiException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.FormBody
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import dev.bulubulu.tv.core.ClientException
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resumeWithException
/** Host/path/expiry checks are shared by persistence and actual network requests. */
internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJar {
private var epoch = 0L
@Synchronized
fun currentEpoch(): Long = epoch
@Synchronized
fun clear() {
epoch++
storage.clear()
}
@Synchronized
fun replaceSession(newCookies: List<Cookie>) {
// A verified login replaces the old account atomically and invalidates older responses.
val live = newCookies.filter {
isBilibiliHost(it.domain) && it.expiresAt > System.currentTimeMillis()
}.distinctBy { Triple(it.name, it.domain, it.path) }
storage.replaceCookies(live)
epoch++
}
@Synchronized
override fun loadForRequest(url: HttpUrl): List<Cookie> {
if (url.scheme != "https" || !isBilibiliHost(url.host)) return emptyList()
val now = System.currentTimeMillis()
return storage.allCookies().filter {
isBilibiliHost(it.domain) && it.expiresAt > now && it.matches(url)
}
}
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
saveFromResponseIfCurrent(url, cookies, currentEpoch())
}
@Synchronized
fun saveFromResponseIfCurrent(url: HttpUrl, cookies: List<Cookie>, expectedEpoch: Long) {
if (expectedEpoch != epoch || url.scheme != "https" || !isBilibiliHost(url.host)) return
val accepted = cookies.filter { cookie ->
isBilibiliHost(cookie.domain) &&
(url.host == cookie.domain || (!cookie.hostOnly && url.host.endsWith(".${cookie.domain}")))
}
if (accepted.isEmpty()) return
val updated = storage.allCookies().toMutableList()
accepted.forEach { incoming ->
updated.removeAll {
it.name == incoming.name && it.domain == incoming.domain && it.path == incoming.path
}
if (incoming.expiresAt > System.currentTimeMillis()) updated += incoming
}
storage.replaceCookies(updated.filter { it.expiresAt > System.currentTimeMillis() })
}
}
/** Official HTTPS JSON API client. The raw client is also available for ordinary network consumers. */
class BiliHttpClient(storage: SessionCookieStore) {
private val cookies = BiliCookieJar(storage)
val client: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.followSslRedirects(false)
.addInterceptor { chain ->
chain.proceed(
chain.request().newBuilder()
.header("User-Agent", USER_AGENT)
.header("Referer", "https://www.bilibili.com/")
.header("Accept", "application/json")
.build(),
)
}
// Set cookies per network hop, so redirects cannot copy them to a CDN/third party.
// The epoch also prevents an in-flight login response restoring cookies after logout.
.addNetworkInterceptor { chain ->
val request = chain.request()
val epoch = cookies.currentEpoch()
val scopedCookies = cookies.loadForRequest(request.url)
val builder = request.newBuilder().removeHeader("Cookie")
if (scopedCookies.isNotEmpty()) {
builder.header("Cookie", scopedCookies.joinToString("; ") { "${it.name}=${it.value}" })
}
val response = chain.proceed(builder.build())
try {
cookies.saveFromResponseIfCurrent(
response.request.url,
Cookie.parseAll(response.request.url, response.headers),
epoch,
)
response
} catch (error: Exception) {
response.close()
throw error
}
}
.build()
suspend fun getJson(
url: String,
params: Map<String, String> = emptyMap(),
allowedApiCodes: Set<Int> = emptySet(),
): JSONObject {
val target = officialUrl(url).newBuilder().apply {
params.forEach { (key, value) -> setQueryParameter(key, value) }
}.build()
return requestJson(Request.Builder().url(target).get().build(), allowedApiCodes)
}
suspend fun postFormJson(url: String, params: Map<String, String>): JSONObject {
val body = FormBody.Builder().apply {
params.forEach { (key, value) -> add(key, value) }
}.build()
return requestJson(Request.Builder().url(officialUrl(url)).post(body).build(), emptySet())
}
fun clearSession() = cookies.clear()
internal fun adoptSession(newCookies: List<Cookie>) = cookies.replaceSession(newCookies)
fun csrfToken(): String? = cookies.loadForRequest(officialUrl("https://passport.bilibili.com/"))
.firstOrNull { it.name == "bili_jct" }?.value
private suspend fun requestJson(request: Request, allowedApiCodes: Set<Int>): JSONObject =
withContext(Dispatchers.IO) {
client.newCall(request).awaitResponse().use { response ->
if (!response.isSuccessful) {
val message = when (response.code) {
412 -> "请求被哔哩哔哩风控拦截,请稍后重试或切换正常网络"
429 -> "请求太频繁,请稍后再试"
403 -> "哔哩哔哩服务器拒绝访问,请稍后重试"
else -> "连接哔哩哔哩失败(HTTP ${response.code})"
}
throw BiliApiException(-response.code, message)
}
val body = response.body ?: throw ClientException("服务器返回了空响应,请重试")
val source = body.source()
source.request(MAX_JSON_BYTES + 1)
if (source.buffer.size > MAX_JSON_BYTES) throw ClientException("服务器响应过大,请重试")
val json = try {
JSONObject(source.readUtf8())
} catch (_: Exception) {
throw ClientException("哔哩哔哩返回了无法识别的数据,请稍后重试")
}
val code = json.optInt("code", 0)
if (code != 0 && code !in allowedApiCodes) {
val serverMessage = json.optString("message").ifBlank { json.optString("msg") }
throw BiliApiException(code, apiErrorMessage(code, serverMessage))
}
json
}
}
private fun officialUrl(url: String): HttpUrl {
val target = url.toHttpUrlOrNull() ?: throw ClientException("接口地址无效")
require(target.scheme == "https" && target.port == 443 && isBilibiliHost(target.host)) {
"只允许访问哔哩哔哩官方 HTTPS 接口"
}
require(target.username.isEmpty() && target.password.isEmpty()) { "接口地址不能包含凭据" }
return target
}
private suspend fun Call.awaitResponse(): Response = suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() }
enqueue(object : Callback {
override fun onFailure(call: Call, error: IOException) {
if (continuation.isActive) continuation.resumeWithException(error)
}
override fun onResponse(call: Call, response: Response) {
continuation.resume(response, onCancellation = { _, resource, _ -> resource.close() })
}
})
}
companion object {
const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
private const val MAX_JSON_BYTES = 4L * 1024L * 1024L
private fun apiErrorMessage(code: Int, serverMessage: String): String = when (code) {
-101 -> "登录已失效,请重新扫码登录"
-111 -> "登录验证失败,请重新登录后重试"
-352, -412 -> "请求被哔哩哔哩风控拦截,请稍后重试"
-10403, 10015002 -> "该内容需要相应会员权限或不支持当前地区播放"
else -> serverMessage.take(180).ifBlank { "哔哩哔哩接口错误($code)" }
}
}
}
@@ -0,0 +1,384 @@
package dev.bulubulu.tv.data
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.FeedPage
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.core.PlaybackStream
import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode
import dev.bulubulu.tv.core.VideoItem
import java.io.IOException
import dev.bulubulu.tv.core.ClientException
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONArray
import org.json.JSONObject
/** Read-only official web APIs. Cookies and account rights are handled by Bilibili. */
class ContentRepository(private val http: BiliHttpClient) {
private val signer = WbiSigner(http)
suspend fun loadFeed(tab: ContentTab, page: Int = 1): FeedPage {
require(page >= 1)
return when (tab) {
ContentTab.RECOMMEND -> recommendations(page)
ContentTab.MOVIE -> seasonIndex(seasonType = 2, page = page)
ContentTab.BANGUMI -> seasonIndex(seasonType = 1, page = page)
}
}
private suspend fun recommendations(page: Int): FeedPage {
val response = try {
signedGet(
"$API/x/web-interface/wbi/index/top/feed/rcmd",
mapOf(
"ps" to PAGE_SIZE.toString(),
"fresh_type" to "3",
"fresh_idx" to page.toString(),
"fresh_idx_1h" to page.toString(),
"brush" to (page - 1).toString(),
"homepage_ver" to "1",
"feed_version" to "V8",
"platform" to "web",
"web_location" to "1430650",
"y_num" to "5",
),
)
} catch (error: BiliApiException) {
// A public popular feed keeps the generic 推荐 tab useful when web
// recommendation itself is temporarily unavailable. It changes no rights.
if (error.apiCode !in setOf(-352, -403, -412)) throw error
return popular(page)
}
val data = ContentJson.payload(response)
val items = ContentJson.recommendationItems(data.optJSONArray("item"))
if (items.isEmpty()) return popular(page)
return FeedPage(items, if (items.isEmpty()) null else page + 1)
}
private suspend fun popular(page: Int): FeedPage {
val data = ContentJson.payload(
http.getJson(
"$API/x/web-interface/popular",
mapOf("pn" to page.toString(), "ps" to PAGE_SIZE.toString()),
),
)
val items = ContentJson.recommendationItems(data.optJSONArray("list"))
val next = if (items.isEmpty() || data.optBoolean("no_more")) null else page + 1
return FeedPage(items, next)
}
private suspend fun seasonIndex(seasonType: Int, page: Int): FeedPage {
val data = ContentJson.payload(
http.getJson(
"$API/pgc/season/index/result",
mapOf(
"season_type" to seasonType.toString(),
"st" to seasonType.toString(),
"type" to "1",
"page" to page.toString(),
"pagesize" to PAGE_SIZE.toString(),
"order" to "2",
"sort" to "0",
),
),
)
val items = ContentJson.seasonItems(data.optJSONArray("list"))
return FeedPage(items, if (items.isNotEmpty() && data.optInt("has_next") == 1) page + 1 else null)
}
suspend fun loadDetails(item: VideoItem): VideoDetails {
if (item.seasonId != null || item.epId != null) {
val parameters = item.seasonId?.let { mapOf("season_id" to it.toString()) }
?: mapOf("ep_id" to item.epId.toString())
return ContentJson.seasonDetails(
ContentJson.payload(http.getJson("$API/pgc/view/web/season", parameters)),
)
}
val parameters = videoIdentity(item.bvid, item.aid)
return ContentJson.videoDetails(
ContentJson.payload(http.getJson("$API/x/web-interface/view", parameters)),
)
}
suspend fun resolvePlayback(episode: VideoEpisode): PlaybackSource {
val common = mapOf("qn" to "80", "fnval" to "16", "fnver" to "0", "fourk" to "0")
val response = if (episode.epId != null) {
http.getJson(
"$API/pgc/player/web/playurl",
common + ("ep_id" to episode.epId.toString()),
)
} else {
val cid = episode.cid ?: throw ClientException("视频缺少分 P 信息,请返回后重新打开")
signedGet(
"$API/x/player/wbi/playurl",
common + videoIdentity(episode.bvid, episode.aid) + mapOf(
"cid" to cid.toString(),
"platform" to "pc",
),
)
}
return ContentJson.playback(ContentJson.payload(response), episode)
}
private suspend fun signedGet(url: String, parameters: Map<String, String>): JSONObject {
return try {
http.getJson(url, signer.sign(parameters))
} catch (error: BiliApiException) {
if (error.apiCode != -403) throw error
signer.invalidate()
http.getJson(url, signer.sign(parameters))
}
}
private fun videoIdentity(bvid: String?, aid: Long?): Map<String, String> = when {
!bvid.isNullOrBlank() -> mapOf("bvid" to bvid)
aid != null && aid > 0L -> mapOf("aid" to aid.toString())
else -> throw ClientException("视频信息不完整,请刷新列表后重试")
}
private companion object {
const val API = "https://api.bilibili.com"
const val PAGE_SIZE = 20
}
}
/** Response parsing is separate from network code so rights handling can be tested. */
internal object ContentJson {
fun payload(root: JSONObject): JSONObject {
val code = root.optInt("code", 0)
if (code != 0) throw BiliApiException(code, root.optString("message").ifBlank { "B 站接口暂不可用" })
val data = root.optJSONObject("data") ?: root.optJSONObject("result") ?: root
val nestedCode = data.optInt("code", 0)
if (nestedCode != 0) {
throw BiliApiException(nestedCode, data.optString("message").ifBlank { "该内容当前无法播放" })
}
return data
}
fun recommendationItems(array: JSONArray?): List<VideoItem> = array.objects().mapNotNull { item ->
val type = item.optString("goto")
// Avoid ads, live rooms, links and other non-video cards in the minimal client.
if (type.isNotBlank() && type != "av") return@mapNotNull null
if (item.optJSONObject("business_info") != null || item.optInt("is_ad") != 0) return@mapNotNull null
val bvid = item.optString("bvid").takeIf { it.startsWith("BV") }
val aid = item.positiveLong("aid") ?: item.positiveLong("id")
if (bvid == null && aid == null) return@mapNotNull null
val title = item.optString("title").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val owner = item.optJSONObject("owner")?.optString("name").orEmpty()
val duration = item.optLong("duration").takeIf { it > 0 }?.let(::durationLabel).orEmpty()
VideoItem(
id = bvid ?: "av$aid",
title = title,
coverUrl = secureUrl(item.optString("pic")),
subtitle = listOf(owner, duration).filter { it.isNotBlank() }.joinToString(" · "),
bvid = bvid,
aid = aid,
)
}.distinctBy { it.id }
fun seasonItems(array: JSONArray?): List<VideoItem> = array.objects().mapNotNull { item ->
val seasonId = item.positiveLong("season_id") ?: return@mapNotNull null
val title = item.optString("title").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val badge = item.optString("badge")
val detail = item.optString("index_show").ifBlank { item.optString("subTitle") }
VideoItem(
id = "ss$seasonId",
title = title,
coverUrl = secureUrl(item.optString("cover")),
subtitle = listOf(badge, detail).filter { it.isNotBlank() }.joinToString(" · "),
seasonId = seasonId,
epId = item.optJSONObject("first_ep")?.positiveLong("ep_id"),
)
}.distinctBy { it.id }
fun videoDetails(data: JSONObject): VideoDetails {
val title = data.optString("title", "视频")
val bvid = data.optString("bvid").takeIf { it.isNotBlank() }
val aid = data.positiveLong("aid")
val episodes = data.optJSONArray("pages").objects().mapNotNull { page ->
val cid = page.positiveLong("cid") ?: return@mapNotNull null
val pageNumber = page.optInt("page", 1)
val part = page.optString("part").ifBlank { title }
VideoEpisode(
id = "cid$cid",
label = "P$pageNumber",
title = part,
bvid = bvid,
aid = aid,
cid = cid,
)
}.ifEmpty {
data.positiveLong("cid")?.let { cid ->
listOf(VideoEpisode("cid$cid", "播放", title, bvid = bvid, aid = aid, cid = cid))
}.orEmpty()
}
if (episodes.isEmpty()) throw ClientException("没有找到可播放的分 P,内容可能已下架")
return VideoDetails(title, data.optString("desc"), episodes)
}
fun seasonDetails(data: JSONObject): VideoDetails {
val title = data.optString("title", "剧集")
val episodes = data.optJSONArray("episodes").objects().mapNotNull { episode ->
val epId = episode.positiveLong("id") ?: episode.positiveLong("ep_id")
?: return@mapNotNull null
if (episode.optBoolean("is_view_hide")) return@mapNotNull null
val label = episode.optString("title").ifBlank { "播放" }
val episodeTitle = episode.optString("long_title").ifBlank {
episode.optString("show_title").ifBlank { title }
}
VideoEpisode(
id = "ep$epId",
label = label,
title = episodeTitle,
bvid = episode.optString("bvid").takeIf { it.isNotBlank() },
aid = episode.positiveLong("aid"),
cid = episode.positiveLong("cid"),
epId = epId,
)
}.distinctBy { it.id }
if (episodes.isEmpty()) throw ClientException("该剧集没有可播放的正片,可能已下架或在当前地区不可用")
return VideoDetails(title, data.optString("evaluate"), episodes)
}
fun playback(data: JSONObject, episode: VideoEpisode): PlaybackSource {
if (data.flag("is_drm") || data.optInt("drm_tech_type", 0) > 0) {
throw BiliApiException(-10_003, "该内容需要 DRM 保护播放,当前版本暂不支持")
}
if (data.flag("is_preview")) {
throw BiliApiException(-10_001, "该内容当前仅提供试看,请登录并确认账号拥有会员或购买权限")
}
if (data.flag("need_login")) {
throw BiliApiException(-101, "请先登录 B 站账号后播放该内容")
}
if (data.optInt("error_code", 0) != 0) {
throw BiliApiException(
data.optInt("error_code"),
data.optString("message").ifBlank { "该内容无法播放,请确认账号权限和所在地区" },
)
}
val dash = data.optJSONObject("dash")
if (dash != null) {
val video = dash.optJSONArray("video").objects()
.filter { stream ->
val codec = stream.optString("codecs").lowercase()
(codec.startsWith("avc1") || stream.optInt("codecid") == 7) &&
streamUrl(stream).isNotBlank()
}
.let { candidates ->
val standard = candidates.filter { it.optInt("id", 80) <= 80 }
(standard.ifEmpty { candidates }).maxWithOrNull(
compareBy<JSONObject> { it.optInt("height") }
.thenBy { it.optLong("bandwidth") },
)
} ?: throw ClientException("B 站未提供兼容这台电视的 H.264 视频流")
val audio = dash.optJSONArray("audio").objects()
.filter { stream ->
(stream.optString("codecs").startsWith("mp4a") || stream.optString("codecs").isBlank()) &&
streamUrl(stream).isNotBlank()
}
.maxByOrNull { it.optLong("bandwidth") }
?: throw ClientException("B 站未提供兼容这台电视的 AAC 音频流")
val quality = video.optInt("id", data.optInt("quality"))
return PlaybackSource(
title = episode.title,
video = stream(video),
audio = stream(audio),
qualityLabel = qualityLabel(data, quality),
durationMs = data.optLong("timelength").takeIf { it > 0 }
?: (dash.optDouble("duration", 0.0) * 1_000).toLong(),
referer = referer(episode),
)
}
val parts = data.optJSONArray("durl").objects()
if (parts.size > 1) {
throw ClientException("该内容只提供多段旧格式视频,当前版本暂不支持,请尝试其他内容")
}
val part = parts.singleOrNull()
if (part != null && secureUrl(part.optString("url")).isNotBlank()) {
return PlaybackSource(
title = episode.title,
video = PlaybackStream(
secureUrl(part.optString("url")),
part.optJSONArray("backup_url").strings().map(::secureUrl).filter(String::isNotBlank),
),
qualityLabel = qualityLabel(data, data.optInt("quality")),
durationMs = data.optLong("timelength", part.optLong("length")),
referer = referer(episode),
)
}
throw ClientException("没有获取到可播放的视频流,请确认已登录、账号权限及所在地区")
}
private fun stream(data: JSONObject) = PlaybackStream(
url = streamUrl(data),
backupUrls = (data.optJSONArray("backupUrl") ?: data.optJSONArray("backup_url"))
.strings().map(::secureUrl).filter(String::isNotBlank).distinct(),
)
private fun streamUrl(data: JSONObject): String =
secureUrl(data.optString("baseUrl").ifBlank { data.optString("base_url") })
private fun referer(episode: VideoEpisode): String = when {
episode.epId != null -> "https://www.bilibili.com/bangumi/play/ep${episode.epId}"
episode.bvid != null -> "https://www.bilibili.com/video/${episode.bvid}"
else -> "https://www.bilibili.com/"
}
private fun qualityLabel(data: JSONObject, quality: Int): String {
val ids = data.optJSONArray("accept_quality")
val descriptions = data.optJSONArray("accept_description")
if (ids != null && descriptions != null) {
for (index in 0 until ids.length()) {
if (ids.optInt(index) == quality) {
descriptions.optString(index).takeIf { it.isNotBlank() }?.let { return it }
}
}
}
return when (quality) {
6 -> "240P"
16 -> "360P"
32 -> "480P"
64 -> "720P"
74 -> "720P 60帧"
80 -> "1080P"
112 -> "1080P 高码率"
116 -> "1080P 60帧"
120 -> "4K"
else -> "自动画质"
}
}
internal fun secureUrl(value: String): String {
val normalized = when {
value.startsWith("//") -> "https:$value"
value.startsWith("http://") -> "https://${value.removePrefix("http://")}"
else -> value
}
val url = normalized.toHttpUrlOrNull() ?: return ""
return normalized.takeIf { url.isHttps && url.username.isBlank() && url.password.isBlank() }.orEmpty()
}
private fun durationLabel(seconds: Long): String = if (seconds >= 3_600) {
"%d:%02d:%02d".format(seconds / 3_600, seconds / 60 % 60, seconds % 60)
} else {
"%d:%02d".format(seconds / 60, seconds % 60)
}
private fun JSONObject.positiveLong(key: String): Long? = optLong(key).takeIf { it > 0 }
private fun JSONObject.flag(key: String): Boolean = when (val value = opt(key)) {
is Boolean -> value
is Number -> value.toInt() != 0
is String -> value == "1" || value.equals("true", ignoreCase = true)
else -> false
}
private fun JSONArray?.objects(): List<JSONObject> =
if (this == null) emptyList() else (0 until length()).mapNotNull(::optJSONObject)
private fun JSONArray?.strings(): List<String> =
if (this == null) emptyList() else (0 until length()).mapNotNull { index ->
optString(index).takeIf { it.isNotBlank() && it != "null" }
}
}
@@ -0,0 +1,174 @@
package dev.bulubulu.tv.data
import android.content.Context
import dev.bulubulu.tv.core.ClientException
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.AtomicFile
import okhttp3.Cookie
import org.json.JSONArray
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/** Deliberately small boundary so cookie scope can be tested without an Android runtime. */
interface SessionCookieStore {
fun allCookies(): List<Cookie>
fun replaceCookies(cookies: List<Cookie>)
fun clear()
}
/** Cookies never enter SharedPreferences, logs, Android backup, or a plaintext file. */
class SessionStore(context: Context) : SessionCookieStore {
private val file = AtomicFile(java.io.File(context.applicationContext.noBackupFilesDir, "session.enc"))
private var cookies: List<Cookie> = readEncryptedCookies()
@Synchronized
override fun allCookies(): List<Cookie> = cookies.toList()
@Synchronized
override fun replaceCookies(cookies: List<Cookie>) {
val live = cookies.filter { it.expiresAt > System.currentTimeMillis() }
if (live.isEmpty()) {
clear()
return
}
val payload = JSONArray().apply {
live.forEach { cookie ->
put(JSONObject().apply {
put("name", cookie.name)
put("value", cookie.value)
put("domain", cookie.domain)
put("path", cookie.path)
put("expiresAt", cookie.expiresAt)
put("persistent", cookie.persistent)
put("hostOnly", cookie.hostOnly)
put("secure", cookie.secure)
put("httpOnly", cookie.httpOnly)
})
}
}.toString().toByteArray(Charsets.UTF_8)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey())
val encrypted = cipher.doFinal(payload)
val encoded = ByteArrayOutputStream().use { bytes ->
DataOutputStream(bytes).use { output ->
output.writeInt(FORMAT_MAGIC)
output.writeInt(cipher.iv.size)
output.write(cipher.iv)
output.write(encrypted)
}
bytes.toByteArray()
}
var output: java.io.FileOutputStream? = null
try {
output = file.startWrite()
output.write(encoded)
file.finishWrite(output)
this.cookies = live.toList()
} catch (error: Exception) {
output?.let(file::failWrite)
throw ClientException("无法安全保存登录状态,请检查设备存储后重试")
} finally {
payload.fill(0)
}
}
@Synchronized
override fun clear() {
cookies = emptyList()
file.delete()
}
private fun readEncryptedCookies(): List<Cookie> {
if (!file.baseFile.exists()) return emptyList()
return try {
// A cookie collection is tiny. Reject damaged or unexpectedly large files before reading.
if (file.baseFile.length() > MAX_STORE_BYTES) throw IOException("Invalid session file")
val encoded = file.readFully()
val plaintext = DataInputStream(ByteArrayInputStream(encoded)).use { input ->
if (input.readInt() != FORMAT_MAGIC) throw IOException("Invalid session format")
val ivLength = input.readInt()
if (ivLength != 12) throw IOException("Invalid session IV")
val iv = ByteArray(ivLength).also(input::readFully)
val ciphertext = ByteArray(input.available()).also(input::readFully)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, encryptionKey(), GCMParameterSpec(128, iv))
cipher.doFinal(ciphertext)
}
try {
val array = JSONArray(plaintext.toString(Charsets.UTF_8))
buildList {
for (i in 0 until array.length()) {
val item = array.getJSONObject(i)
val builder = Cookie.Builder()
.name(item.getString("name"))
.value(item.getString("value"))
.path(item.getString("path"))
val domain = item.getString("domain")
if (!isBilibiliHost(domain)) continue
if (item.optBoolean("hostOnly")) builder.hostOnlyDomain(domain) else builder.domain(domain)
if (item.optBoolean("persistent")) builder.expiresAt(item.getLong("expiresAt"))
if (item.optBoolean("secure")) builder.secure()
if (item.optBoolean("httpOnly")) builder.httpOnly()
builder.build().takeIf { it.expiresAt > System.currentTimeMillis() }?.let(::add)
}
}
} finally {
plaintext.fill(0)
}
} catch (_: Exception) {
// A lost/invalid Keystore key must fail closed, never downgrade to plaintext storage.
file.delete()
emptyList()
}
}
private fun encryptionKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(true)
.build(),
)
}.generateKey()
}
private companion object {
const val KEY_ALIAS = "bulubulu.session.v1"
const val FORMAT_MAGIC = 0x42425431 // BBT1
const val MAX_STORE_BYTES = 256L * 1024L
}
}
internal fun isBilibiliHost(host: String): Boolean =
host == "bilibili.com" || host.endsWith(".bilibili.com")
/** QR confirmation and best-effort logout are isolated from the durable active account. */
internal class InMemorySessionCookieStore(initial: List<Cookie> = emptyList()) : SessionCookieStore {
private var cookies = initial.toList()
@Synchronized
override fun allCookies(): List<Cookie> = cookies.toList()
@Synchronized
override fun replaceCookies(cookies: List<Cookie>) { this.cookies = cookies.toList() }
@Synchronized
override fun clear() { cookies = emptyList() }
}
@@ -0,0 +1,91 @@
package dev.bulubulu.tv.data
import dev.bulubulu.tv.core.ClientException
import java.net.URLEncoder
import java.security.MessageDigest
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/** Signs normal Bilibili web requests; it does not change account permissions. */
class WbiSigner(
private val http: BiliHttpClient,
private val epochSeconds: () -> Long = { System.currentTimeMillis() / 1_000L },
) {
private data class Keys(val image: String, val sub: String, val fetchedAt: Long)
private val mutex = Mutex()
private var cachedKeys: Keys? = null
suspend fun sign(parameters: Map<String, String>): Map<String, String> {
val keys = mutex.withLock {
val current = cachedKeys
if (current != null && epochSeconds() - current.fetchedAt in 0..21_600) {
current
} else {
// Anonymous nav is -101 but still supplies the public signing keys.
val response = http.getJson(
"https://api.bilibili.com/x/web-interface/nav",
allowedApiCodes = setOf(-101),
)
val images = response.optJSONObject("data")?.optJSONObject("wbi_img")
?: throw ClientException("B 站未返回请求签名信息,请稍后重试")
Keys(
image = keyFromUrl(images.optString("img_url")),
sub = keyFromUrl(images.optString("sub_url")),
fetchedAt = epochSeconds(),
).also { cachedKeys = it }
}
}
return signParameters(parameters, keys.image, keys.sub, epochSeconds())
}
suspend fun invalidate() = mutex.withLock { cachedKeys = null }
companion object {
private val permutation = intArrayOf(
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35,
27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13,
37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4,
22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52,
)
private val forbidden = setOf('!', '\'', '(', ')', '*')
internal fun keyFromUrl(url: String): String {
val key = url.substringBefore('?').substringAfterLast('/').substringBeforeLast('.')
if (key.length != 32 || key.any { !it.isLetterOrDigit() }) {
throw ClientException("B 站请求签名信息格式异常,请稍后重试")
}
return key
}
internal fun mixinKey(imageKey: String, subKey: String): String {
require(imageKey.length == 32 && subKey.length == 32) { "Invalid WBI key length" }
val combined = imageKey + subKey
return permutation.take(32).map { combined[it] }.joinToString("")
}
/** Kept pure so canonical encoding and the signature can be verified on the JVM. */
fun signParameters(
parameters: Map<String, String>,
imageKey: String,
subKey: String,
timestampSeconds: Long,
): Map<String, String> {
val normalized = parameters.filterKeys { it != "w_rid" && it != "wts" }
.mapValues { (_, value) -> value.filterNot { it in forbidden } }
.toSortedMap()
normalized["wts"] = timestampSeconds.toString()
val query = normalized.entries.joinToString("&") { (key, value) ->
"${encode(key)}=${encode(value)}"
}
val digest = MessageDigest.getInstance("MD5")
.digest((query + mixinKey(imageKey, subKey)).toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it.toInt() and 0xff) }
return normalized + ("w_rid" to digest)
}
private fun encode(value: String): String =
URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("%7E", "~")
}
}
@@ -0,0 +1,56 @@
@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
package dev.bulubulu.tv.player
import android.net.Uri
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.TransferListener
import java.io.IOException
/** Keeps range/header requests intact while trying the official backup CDN for a failed open. */
internal class BackupDataSource(
private val upstream: DataSource.Factory,
private val alternatives: Map<String, List<String>>,
) : DataSource {
private var active: DataSource? = null
private val listeners = mutableListOf<TransferListener>()
override fun addTransferListener(transferListener: TransferListener) {
listeners += transferListener
active?.addTransferListener(transferListener)
}
override fun open(dataSpec: DataSpec): Long {
val primary = dataSpec.uri.toString()
val candidates = (listOf(primary) + alternatives[primary].orEmpty()).distinct()
var lastFailure: IOException? = null
for (candidate in candidates) {
val next = upstream.createDataSource()
listeners.forEach(next::addTransferListener)
active = next
try {
return next.open(dataSpec.buildUpon().setUri(candidate).build())
} catch (failure: IOException) {
lastFailure = failure
runCatching { next.close() }
active = null
if (Thread.currentThread().isInterrupted) throw failure
}
}
throw lastFailure ?: IOException("Video source unavailable")
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int =
active?.read(buffer, offset, length) ?: throw IOException("Video source is not open")
override fun getUri(): Uri? = active?.uri
override fun getResponseHeaders(): Map<String, List<String>> = active?.responseHeaders.orEmpty()
override fun close() {
val current = active
active = null
current?.close()
}
}
@@ -0,0 +1,14 @@
package dev.bulubulu.tv.player
internal fun formatPlaybackTime(milliseconds: Long): String {
val totalSeconds = (milliseconds.coerceAtLeast(0) / 1000)
val seconds = totalSeconds % 60
val minutes = (totalSeconds / 60) % 60
val hours = totalSeconds / 3600
return if (hours > 0) "%d:%02d:%02d".format(hours, minutes, seconds) else "%02d:%02d".format(minutes, seconds)
}
internal fun seekPosition(currentMs: Long, durationMs: Long, deltaMs: Long): Long {
val target = (currentMs + deltaMs).coerceAtLeast(0)
return if (durationMs > 0) target.coerceAtMost(durationMs) else target
}
@@ -0,0 +1,287 @@
@file:androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
package dev.bulubulu.tv.player
import android.os.SystemClock
import android.view.KeyEvent
import android.view.ViewGroup
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
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.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.DataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.exoplayer.source.MergingMediaSource
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.PlayerView
import dev.bulubulu.tv.core.PlaybackSource
import dev.bulubulu.tv.ui.TvAccent
import dev.bulubulu.tv.ui.TvAction
import dev.bulubulu.tv.ui.TvMuted
import dev.bulubulu.tv.ui.TvText
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
@Composable
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val errorCallback by rememberUpdatedState(onPlaybackError)
val focusRequester = remember { FocusRequester() }
val retryFocus = remember { FocusRequester() }
var isPlaying by remember(source) { mutableStateOf(false) }
var buffering by remember(source) { mutableStateOf(true) }
var ended by remember(source) { mutableStateOf(false) }
var error by remember(source) { mutableStateOf<String?>(null) }
var position by remember(source) { mutableLongStateOf(0) }
var duration by remember(source) { mutableLongStateOf(source.durationMs) }
var controlsVisible by remember(source) { mutableStateOf(true) }
var lastInteraction by remember(source) { mutableLongStateOf(SystemClock.elapsedRealtime()) }
var lastSeekEvent by remember(source) { mutableLongStateOf(0) }
val player = remember(context, source) {
androidx.media3.common.util.Log.setLogLevel(androidx.media3.common.util.Log.LOG_LEVEL_OFF)
val http = DefaultHttpDataSource.Factory()
.setUserAgent("Mozilla/5.0 (Linux; Android 11) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36")
.setDefaultRequestProperties(mapOf("Referer" to source.referer))
.setConnectTimeoutMs(15_000)
.setReadTimeoutMs(20_000)
.setAllowCrossProtocolRedirects(false)
val alternatives = buildMap {
put(source.video.url, source.video.backupUrls)
source.audio?.let { put(it.url, it.backupUrls) }
}
val dataSources = DataSource.Factory { BackupDataSource(http, alternatives) }
fun track(url: String): MediaSource = ProgressiveMediaSource.Factory(dataSources)
.createMediaSource(MediaItem.fromUri(url))
val video = track(source.video.url)
val media = source.audio?.let { MergingMediaSource(true, true, video, track(it.url)) } ?: video
ExoPlayer.Builder(context)
.setRenderersFactory(DefaultRenderersFactory(context).setEnableDecoderFallback(true))
.setLoadControl(DefaultLoadControl.Builder().setBufferDurationsMs(10_000, 30_000, 1_000, 2_000).build())
.build().apply {
setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(), true)
setHandleAudioBecomingNoisy(true)
setMediaSource(media)
playWhenReady = true
prepare()
}
}
DisposableEffect(player, lifecycleOwner) {
val listener = object : Player.Listener {
override fun onIsPlayingChanged(playing: Boolean) { isPlaying = playing }
override fun onPlaybackStateChanged(state: Int) {
buffering = state == Player.STATE_BUFFERING
ended = state == Player.STATE_ENDED
if (ended) controlsVisible = true
if (player.duration > 0) duration = player.duration
}
override fun onPlayerError(exception: PlaybackException) {
buffering = false
val message = when (exception.errorCode) {
PlaybackException.ERROR_CODE_DECODING_FAILED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES,
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED,
PlaybackException.ERROR_CODE_DECODER_INIT_FAILED -> "电视暂时无法解码这个视频。请返回后重试。"
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,
PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT -> "无法连接视频源,请检查网络后重试。"
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS -> "视频地址暂不可用,请返回后重新打开视频。"
else -> "播放失败,请返回后重试。"
}
error = message
controlsVisible = true
// Do not forward raw exception messages: CDN URLs can contain signed access parameters.
errorCallback(message)
}
}
var resumeAfterPause = false
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_PAUSE -> { resumeAfterPause = player.playWhenReady; player.pause() }
Lifecycle.Event.ON_RESUME -> if (resumeAfterPause) player.play()
else -> Unit
}
}
player.addListener(listener)
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
player.removeListener(listener)
player.release()
}
}
LaunchedEffect(player) {
delay(120)
focusRequester.requestFocus()
while (isActive) {
position = player.currentPosition.coerceAtLeast(0)
if (player.duration > 0) duration = player.duration
delay(400)
}
}
LaunchedEffect(lastInteraction, isPlaying, error) {
if (isPlaying && error == null) {
delay(4_000)
controlsVisible = false
} else {
controlsVisible = true
}
}
LaunchedEffect(error) {
if (error != null) { delay(100); retryFocus.requestFocus() }
}
fun interact() {
lastInteraction = SystemClock.elapsedRealtime()
controlsVisible = true
}
fun togglePlayback() {
if (ended) { player.seekTo(0); player.play() }
else if (player.playWhenReady) player.pause() else player.play()
interact()
}
BackHandler(onBack = onBack)
Box(
modifier = Modifier.fillMaxSize().background(Color.Black)
.focusRequester(focusRequester)
.onPreviewKeyEvent { event ->
if (error != null) return@onPreviewKeyEvent false
val native = event.nativeKeyEvent
val key = native.keyCode
val supported = key in setOf(
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
KeyEvent.KEYCODE_SPACE, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY,
KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_MEDIA_REWIND, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD,
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
)
if (!supported) return@onPreviewKeyEvent false
if (native.action == KeyEvent.ACTION_DOWN) {
when (key) {
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
KeyEvent.KEYCODE_MEDIA_REWIND, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> {
val now = SystemClock.elapsedRealtime()
if (native.repeatCount == 0 || now - lastSeekEvent >= 250) {
val delta = if (key == KeyEvent.KEYCODE_DPAD_LEFT || key == KeyEvent.KEYCODE_MEDIA_REWIND) -10_000L else 10_000L
player.seekTo(seekPosition(player.currentPosition, player.duration, delta))
position = player.currentPosition.coerceAtLeast(0)
lastSeekEvent = now
}
interact()
}
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> interact()
KeyEvent.KEYCODE_MEDIA_PLAY -> if (native.repeatCount == 0) { player.play(); interact() }
KeyEvent.KEYCODE_MEDIA_PAUSE -> if (native.repeatCount == 0) { player.pause(); interact() }
else -> if (native.repeatCount == 0) togglePlayback()
}
}
// Consume both key-down and key-up so PlayerView cannot also toggle/seek.
true
}
.focusable(),
) {
AndroidView(
factory = { ctx ->
PlayerView(ctx).apply {
this.player = player
useController = false
isFocusable = false
descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)
setShutterBackgroundColor(android.graphics.Color.BLACK)
}
},
update = { view -> view.player = player; view.keepScreenOn = isPlaying },
onReset = null,
onRelease = { view -> view.player = null; view.keepScreenOn = false },
modifier = Modifier.fillMaxSize(),
)
if (buffering && error == null) {
CircularProgressIndicator(Modifier.align(Alignment.Center).size(40.dp), color = TvAccent, strokeWidth = 3.dp)
}
if (controlsVisible && error == null) {
Box(Modifier.fillMaxWidth().height(110.dp).align(Alignment.TopCenter).background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent))))
Column(Modifier.align(Alignment.TopStart).fillMaxWidth().padding(horizontal = 40.dp, vertical = 25.dp)) {
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))
}
Column(
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(Brush.verticalGradient(listOf(Color.Transparent, Color.Black.copy(alpha = 0.92f))))
.padding(start = 40.dp, end = 40.dp, top = 35.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Text(if (ended) "已播放完毕 · 确认键重播" else if (isPlaying) "播放中" else if (buffering) "正在缓冲…" else "已暂停", color = TvText, fontSize = 16.sp)
Text("${formatPlaybackTime(position)} / ${formatPlaybackTime(duration)}", color = TvText, fontSize = 14.sp)
}
val progress = if (duration > 0) (position.toFloat() / duration).coerceIn(0f, 1f) else 0f
Canvas(Modifier.fillMaxWidth().height(4.dp)) {
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
}
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 返回键 退出", color = TvMuted, fontSize = 12.sp)
}
}
error?.let { message ->
Column(Modifier.align(Alignment.Center).background(Color.Black.copy(alpha = 0.9f)).padding(30.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(20.dp)) {
Text(message, color = TvText, fontSize = 18.sp)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
TvAction("重试播放", {
error = null
buffering = true
player.prepare()
player.play()
focusRequester.requestFocus()
}, Modifier.focusRequester(retryFocus))
TvAction("返回", onBack)
}
}
}
}
}
@@ -0,0 +1,244 @@
package dev.bulubulu.tv.ui
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
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.material3.CircularProgressIndicator
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.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.VideoItem
import kotlinx.coroutines.delay
@Composable
fun BulubuluHome(
state: HomeUiState,
onTabSelected: (ContentTab) -> Unit,
onItemSelected: (VideoItem) -> Unit,
onLoadMore: () -> Unit,
onRefresh: () -> Unit,
onLogin: () -> Unit,
onLogout: () -> Unit,
focusRestoreKey: Int = 0,
active: Boolean = true,
) {
val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } }
val accountFocus = remember { FocusRequester() }
val refreshFocus = remember { FocusRequester() }
val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
val recommendGrid = rememberLazyGridState()
val movieGrid = rememberLazyGridState()
val bangumiGrid = rememberLazyGridState()
val gridState = when (state.selectedTab) {
ContentTab.RECOMMEND -> recommendGrid
ContentTab.MOVIE -> movieGrid
ContentTab.BANGUMI -> bangumiGrid
}
val columns = if (state.selectedTab == ContentTab.RECOMMEND) 4 else 5
var gridHasFocus by remember { mutableStateOf(false) }
var logoutConfirmation by remember { mutableStateOf(false) }
LaunchedEffect(focusRestoreKey, active) {
if (!active) return@LaunchedEffect
// Parent keeps Home composed under overlays and increments this token on close.
delay(100)
when {
lastFocusToken == "account" -> accountFocus.requestFocus()
lastFocusToken == "refresh" -> refreshFocus.requestFocus()
lastFocusToken.startsWith("item:") -> {
val prefix = "item:${state.selectedTab.name}:"
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
if (index >= 0) {
gridState.scrollToItem(index)
delay(100)
cardFocus[lastFocusToken]?.requestFocus()
} else tabFocus.getValue(state.selectedTab).requestFocus()
}
else -> tabFocus.getValue(state.selectedTab).requestFocus()
}
}
BackHandler(active && gridHasFocus) { tabFocus.getValue(state.selectedTab).requestFocus() }
CompositionLocalProvider(LocalTvFocusEnabled provides active) {
Column(
Modifier.fillMaxSize()
.background(Brush.verticalGradient(listOf(Color(0xFF1B1C2A), TvBackground), endY = 700f))
.padding(horizontal = 38.dp, vertical = 24.dp),
) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text("bulubulu", color = TvText, fontWeight = FontWeight.Bold, fontSize = 28.sp, letterSpacing = (-1).sp)
Spacer(Modifier.width(26.dp))
Row(horizontalArrangement = Arrangement.spacedBy(9.dp), modifier = Modifier.focusGroup()) {
ContentTab.entries.forEach { tab ->
TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab)).onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab)
}
}
Spacer(Modifier.weight(1f))
if (state.authBusy) {
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
} else if (state.account != null) {
TvAction(state.account.name.take(10) + " · 退出", { logoutConfirmation = true }, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
} else {
TvAction("扫码登录", onLogin, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
}
}
Spacer(Modifier.height(21.dp))
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text(
when (state.selectedTab) {
ContentTab.RECOMMEND -> if (state.account == null) "发现好视频" else "为你推荐"
ContentTab.MOVIE -> "电影"
ContentTab.BANGUMI -> "番剧"
},
color = TvText, fontSize = 21.sp, fontWeight = FontWeight.SemiBold,
)
Text(if (state.account == null) "登录后可观看账号有权访问的内容" else "${state.items.size} 部内容", color = TvMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 3.dp))
}
TvAction("刷新", onRefresh, Modifier.focusRequester(refreshFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "refresh" }, enabled = !state.loading)
}
Spacer(Modifier.height(10.dp))
when {
state.loading && state.items.isEmpty() -> {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp)
Text("正在加载…", color = TvMuted, fontSize = 15.sp)
}
}
}
state.items.isEmpty() -> {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(state.error ?: "暂时没有内容", color = TvText, fontSize = 18.sp)
TvAction("重新加载", onRefresh)
}
}
}
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 ->
val focusToken = "item:${state.selectedTab.name}:${item.id}"
VideoCard(
item = item,
portrait = state.selectedTab != ContentTab.RECOMMEND,
focusRequester = cardFocus.getOrPut(focusToken) { FocusRequester() },
onFocused = { lastFocusToken = focusToken },
onClick = { onItemSelected(item) },
)
}
item(span = { GridItemSpan(columns) }, key = "load-more") {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
state.error?.let { Text(it, color = Color(0xFFFFB0A6), fontSize = 14.sp) }
when {
state.loadingMore -> CircularProgressIndicator(Modifier.size(26.dp), color = TvAccent, strokeWidth = 2.dp)
state.hasMore -> TvAction(if (state.error == null) "加载更多" else "重试", onLoadMore)
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))
}
}
if (logoutConfirmation && active) {
ConfirmationDialog(
title = "退出登录?",
message = "这台设备上保存的登录信息会被清除。",
confirmLabel = "退出登录",
onConfirm = { logoutConfirmation = false; onLogout() },
onDismiss = { logoutConfirmation = false },
)
}
}
@Composable
private fun VideoCard(item: VideoItem, portrait: Boolean, focusRequester: FocusRequester, onFocused: () -> Unit, onClick: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val focusEnabled = LocalTvFocusEnabled.current
val scale by animateFloatAsState(if (focused) 1.025f else 1f, label = "posterFocus")
val shape = RoundedCornerShape(12.dp)
Column(
Modifier.fillMaxWidth()
.graphicsLayer { scaleX = scale; scaleY = scale }
.focusRequester(focusRequester)
.focusProperties { canFocus = focusEnabled }
.onFocusChanged { focused = it.isFocused; if (it.isFocused) onFocused() }
.border(if (focused) 3.dp else 1.dp, if (focused) TvAccent else Color.White.copy(alpha = 0.05f), shape)
.clip(shape)
.background(if (focused) Color(0xFF30232C) else TvPanel)
.clickable(enabled = focusEnabled, role = Role.Button, onClick = onClick)
.padding(3.dp),
) {
Box(Modifier.fillMaxWidth().aspectRatio(if (portrait) 0.72f else (16f / 9f)).clip(RoundedCornerShape(9.dp)).background(Color(0xFF202E3A)), contentAlignment = Alignment.Center) {
Text(item.title.take(1), color = TvMuted.copy(alpha = 0.3f), fontSize = 32.sp)
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(item.coverUrl.let { if (it.startsWith("http://")) "https://" + it.removePrefix("http://") else it })
.addHeader("Referer", "https://www.bilibili.com/")
.crossfade(true).build(),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
)
}
Text(item.title, color = if (focused) TvAccent else TvText, fontSize = 15.sp, fontWeight = FontWeight.Medium, minLines = 2, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 9.dp, end = 9.dp, top = 10.dp))
Text(item.subtitle.ifBlank { " " }, color = TvMuted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(start = 9.dp, end = 9.dp, top = 4.dp, bottom = 10.dp))
}
}
@@ -0,0 +1,28 @@
package dev.bulubulu.tv.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
internal val TvBackground = Color(0xFF0C1017)
internal val TvPanel = Color(0xFF181F29)
internal val TvAccent = Color(0xFFFFA5B9)
internal val TvText = Color(0xFFF5F1ED)
internal val TvMuted = Color(0xFF9DAAB9)
@Composable
fun BulubuluTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = darkColorScheme(
primary = TvAccent,
onPrimary = TvBackground,
background = TvBackground,
surface = TvPanel,
onSurface = TvText,
onSurfaceVariant = TvMuted,
error = Color(0xFFFFADA7),
),
content = content,
)
}
@@ -0,0 +1,215 @@
package dev.bulubulu.tv.ui
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
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.graphics.asImageBitmap
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
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 com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import dev.bulubulu.tv.core.QrLoginCode
import dev.bulubulu.tv.core.QrLoginStatus
import dev.bulubulu.tv.core.VideoDetails
import dev.bulubulu.tv.core.VideoEpisode
import kotlinx.coroutines.delay
@Composable
private fun DialogPanel(onDismiss: () -> Unit, content: @Composable () -> Unit) {
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(
color = TvPanel,
contentColor = TvText,
shape = RoundedCornerShape(22.dp),
modifier = Modifier.widthIn(max = 790.dp).fillMaxWidth(0.9f)
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)),
) { content() }
}
}
@Composable
fun LoginDialog(
code: QrLoginCode?,
status: QrLoginStatus?,
loading: Boolean,
error: String?,
onRetry: () -> Unit,
onDismiss: () -> Unit,
) {
val closeFocus = remember { FocusRequester() }
val qrBitmap = remember(code?.url) {
code?.let { runCatching { createQrCode(it.url) }.getOrNull() }
}
LaunchedEffect(Unit) { delay(100); closeFocus.requestFocus() }
DialogPanel(onDismiss) {
Column(Modifier.padding(30.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(
Modifier.size(228.dp).background(Color.White, RoundedCornerShape(14.dp)).padding(14.dp),
contentAlignment = Alignment.Center,
) {
if (qrBitmap != null && status != QrLoginStatus.Expired) {
Image(qrBitmap.asImageBitmap(), contentDescription = "登录二维码", modifier = Modifier.size(200.dp))
} else if (loading) {
CircularProgressIndicator(Modifier.size(30.dp), color = TvBackground, strokeWidth = 2.dp)
} else {
Text(if (status == QrLoginStatus.Expired) "二维码已过期" else "二维码暂不可用", color = TvBackground, fontSize = 15.sp)
}
}
Spacer(Modifier.width(30.dp))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(15.dp)) {
Text("扫码登录", fontSize = 27.sp, fontWeight = FontWeight.SemiBold)
Text("用哔哩哔哩手机客户端扫码,\n然后在手机上确认登录。", color = TvMuted, fontSize = 16.sp, lineHeight = 25.sp)
Text(
when {
error != null -> error
loading -> "正在生成二维码…"
status == QrLoginStatus.WaitingForConfirmation -> "已扫码,请在手机上确认"
status == QrLoginStatus.Expired -> "已过期,请刷新二维码"
status is QrLoginStatus.Success -> "登录成功"
else -> "等待扫码"
},
color = if (error == null) TvAccent else Color(0xFFFFADA7),
fontSize = 15.sp,
)
Text("登录信息仅加密保存在这台设备。", color = TvMuted.copy(alpha = 0.75f), fontSize = 12.sp)
}
}
Spacer(Modifier.height(25.dp))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
TvAction("刷新二维码", onRetry, enabled = !loading)
Spacer(Modifier.width(12.dp))
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus))
}
}
}
}
private fun createQrCode(value: String): Bitmap {
val pixels = MultiFormatWriter().encode(
value, BarcodeFormat.QR_CODE, 360, 360,
mapOf(EncodeHintType.CHARACTER_SET to "UTF-8", EncodeHintType.MARGIN to 2),
)
val colors = IntArray(pixels.width * pixels.height) { i ->
if (pixels[i % pixels.width, i / pixels.width]) android.graphics.Color.BLACK else android.graphics.Color.WHITE
}
return Bitmap.createBitmap(colors, pixels.width, pixels.height, Bitmap.Config.ARGB_8888)
}
@Composable
fun DetailsDialog(
details: VideoDetails?,
loading: Boolean,
error: String?,
onPlay: (VideoEpisode) -> Unit,
onRetry: () -> Unit,
onDismiss: () -> Unit,
) {
val closeFocus = remember { FocusRequester() }
val firstEpisodeFocus = remember { FocusRequester() }
LaunchedEffect(loading, details, error) {
delay(100)
if (!loading && error == null && !details?.episodes.isNullOrEmpty()) {
firstEpisodeFocus.requestFocus()
} else {
closeFocus.requestFocus()
}
}
DialogPanel(onDismiss) {
Column(Modifier.padding(28.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(details?.title ?: "视频详情", fontSize = 23.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
when {
loading -> Box(Modifier.fillMaxWidth().height(135.dp), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp)
}
error != null -> {
Text(error, color = Color(0xFFFFADA7), fontSize = 15.sp)
TvAction("重试", onRetry)
}
details != null -> {
if (details.description.isNotBlank()) {
Text(details.description, color = TvMuted, fontSize = 14.sp, maxLines = 3, lineHeight = 22.sp, overflow = TextOverflow.Ellipsis)
}
Text(if (details.episodes.size > 1) "选集" else "播放", color = TvAccent, fontSize = 14.sp, fontWeight = FontWeight.Medium)
if (details.episodes.isEmpty()) {
Text("暂时没有可播放的内容", color = TvMuted, fontSize = 15.sp)
} else {
LazyVerticalGrid(
columns = GridCells.Fixed(if (details.episodes.size == 1) 1 else 4),
modifier = Modifier.fillMaxWidth().heightIn(max = 180.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
itemsIndexed(details.episodes, key = { _, ep -> ep.id }) { index, episode ->
TvAction(
if (details.episodes.size == 1) "开始播放" else episode.label.ifBlank { "第 ${index + 1} 集" },
{ onPlay(episode) },
modifier = if (index == 0) Modifier.focusRequester(firstEpisodeFocus) else Modifier,
)
}
}
}
}
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus))
}
}
}
}
@Composable
internal fun ConfirmationDialog(
title: String,
message: String,
confirmLabel: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
val dismissFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { delay(100); dismissFocus.requestFocus() }
DialogPanel(onDismiss) {
Column(Modifier.padding(30.dp), verticalArrangement = Arrangement.spacedBy(20.dp)) {
Text(title, fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
Text(message, color = TvMuted, fontSize = 15.sp)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
TvAction(confirmLabel, onConfirm)
Spacer(Modifier.width(12.dp))
TvAction("取消", onDismiss, Modifier.focusRequester(dismissFocus))
}
}
}
}
@@ -0,0 +1,16 @@
package dev.bulubulu.tv.ui
import dev.bulubulu.tv.core.Account
import dev.bulubulu.tv.core.ContentTab
import dev.bulubulu.tv.core.VideoItem
data class HomeUiState(
val selectedTab: ContentTab = ContentTab.RECOMMEND,
val account: Account? = null,
val items: List<VideoItem> = emptyList(),
val loading: Boolean = true,
val loadingMore: Boolean = false,
val error: String? = null,
val hasMore: Boolean = true,
val authBusy: Boolean = false,
)
@@ -0,0 +1,70 @@
package dev.bulubulu.tv.ui
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
internal val LocalTvFocusEnabled = staticCompositionLocalOf { true }
@Composable
internal fun TvAction(
label: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
selected: Boolean = false,
enabled: Boolean = true,
) {
var focused by remember { mutableStateOf(false) }
val focusEnabled = LocalTvFocusEnabled.current
val background by animateColorAsState(
when {
focused -> TvAccent
selected -> Color(0xFF392A33)
else -> TvPanel
}, label = "buttonBackground",
)
val foreground = when {
!enabled -> TvMuted.copy(alpha = 0.5f)
focused -> TvBackground
selected -> TvAccent
else -> TvText
}
Box(
modifier = modifier
.defaultMinSize(minWidth = 74.dp, minHeight = 44.dp)
.focusProperties { canFocus = enabled && focusEnabled }
.onFocusChanged { focused = it.isFocused }
.background(background, RoundedCornerShape(12.dp))
.border(if (focused) 2.dp else 1.dp, if (focused) TvAccent else Color.White.copy(alpha = 0.06f), RoundedCornerShape(12.dp))
.semantics { this.selected = selected }
.clickable(enabled = enabled && focusEnabled, role = Role.Button, onClick = onClick)
.padding(horizontal = 18.dp, vertical = 11.dp),
contentAlignment = Alignment.Center,
) {
Text(label, color = foreground, fontSize = 15.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Normal)
}
}
+5
View File
@@ -0,0 +1,5 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="320dp" android:height="180dp" android:viewportWidth="320" android:viewportHeight="180">
<path android:fillColor="#101116" android:pathData="M0,0h320v180h-320z" />
<path android:fillColor="#F28F9E" android:pathData="M112,50h96v80h-96z" />
<path android:fillColor="#101116" android:pathData="M143,68L143,112L181,90z" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#101116" android:pathData="M0,0h108v108h-108z" />
<path android:fillColor="#F28F9E" android:pathData="M24,29h60v50h-60z" />
<path android:fillColor="#101116" android:pathData="M44,40L44,68L68,54z" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">bulubulu</string>
</resources>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Bulubulu" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:statusBarColor">#0C1017</item>
<item name="android:navigationBarColor">#0C1017</item>
<item name="android:windowBackground">#0C1017</item>
<item name="android:colorAccent">#FFA5B9</item>
</style>
</resources>
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
</cloud-backup>
<device-transfer>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,123 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.data.BiliCookieJar
import dev.bulubulu.tv.data.SessionCookieStore
import okhttp3.Cookie
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class BiliCookieJarTest {
private class MemoryStore : SessionCookieStore {
var cookies: List<Cookie> = emptyList()
override fun allCookies() = cookies.toList()
override fun replaceCookies(cookies: List<Cookie>) { this.cookies = cookies.toList() }
override fun clear() { cookies = emptyList() }
}
private fun sessionCookie(
domain: String = "bilibili.com", path: String = "/", value: String = "test-session",
expiresAt: Long = System.currentTimeMillis() + 60_000,
) =
Cookie.Builder().name("SESSDATA").value(value)
.domain(domain).path(path).secure().httpOnly()
.expiresAt(expiresAt).build()
@Test
fun `session is available on official HTTPS APIs only`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
jar.saveFromResponse("https://passport.bilibili.com/".toHttpUrl(), listOf(sessionCookie()))
assertEquals(1, jar.loadForRequest("https://api.bilibili.com/x/web-interface/nav".toHttpUrl()).size)
for (url in listOf(
"http://api.bilibili.com/", "https://example.com/", "https://i0.hdslb.com/",
"https://bilibili.com.evil.example/", "https://notbilibili.com/",
)) assertTrue("Cookie leaked to $url", jar.loadForRequest(url.toHttpUrl()).isEmpty())
}
@Test
fun `third party responses cannot set or replace session cookies`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
jar.saveFromResponse("https://evil.example/".toHttpUrl(), listOf(sessionCookie()))
jar.saveFromResponse("http://passport.bilibili.com/".toHttpUrl(), listOf(sessionCookie()))
jar.saveFromResponse("https://api.bilibili.com/".toHttpUrl(), listOf(sessionCookie("passport.bilibili.com")))
assertTrue(store.cookies.isEmpty())
}
@Test
fun `host-only and path scoping are preserved`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
val hostOnly = Cookie.Builder().name("host_cookie").value("test")
.hostOnlyDomain("passport.bilibili.com").path("/login").secure().build()
jar.saveFromResponse("https://passport.bilibili.com/login".toHttpUrl(), listOf(hostOnly))
assertEquals(1, jar.loadForRequest("https://passport.bilibili.com/login/confirm".toHttpUrl()).size)
assertTrue(jar.loadForRequest("https://api.bilibili.com/login".toHttpUrl()).isEmpty())
assertTrue(jar.loadForRequest("https://passport.bilibili.com/logout".toHttpUrl()).isEmpty())
}
@Test
fun `expired cookies delete an existing cookie with the same scope`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
val url = "https://passport.bilibili.com/".toHttpUrl()
jar.saveFromResponse(url, listOf(sessionCookie()))
val expired = sessionCookie(expiresAt = 1)
jar.saveFromResponse(url, listOf(expired))
assertTrue(jar.loadForRequest(url).isEmpty())
assertTrue(store.cookies.isEmpty())
}
@Test
fun `logout prevents a late QR response from restoring credentials`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
val epochBeforeLogout = jar.currentEpoch()
jar.clear()
jar.saveFromResponseIfCurrent(
"https://passport.bilibili.com/".toHttpUrl(), listOf(sessionCookie()), epochBeforeLogout,
)
assertTrue(store.cookies.isEmpty())
jar.saveFromResponseIfCurrent(
"https://passport.bilibili.com/".toHttpUrl(), listOf(sessionCookie()), jar.currentEpoch(),
)
assertEquals(1, store.cookies.size)
}
@Test
fun `replacing cookie does not keep an older value`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
val url = "https://passport.bilibili.com/".toHttpUrl()
jar.saveFromResponse(url, listOf(sessionCookie()))
jar.saveFromResponse(url, listOf(sessionCookie(value = "new-test-session")))
assertEquals(1, store.cookies.size)
assertEquals("new-test-session", store.cookies.single().value)
}
@Test
fun `verified adoption discards old account and late network cookies`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
val url = "https://passport.bilibili.com/".toHttpUrl()
jar.saveFromResponse(url, listOf(sessionCookie(value = "old-session")))
val beforeLogin = jar.currentEpoch()
jar.replaceSession(listOf(sessionCookie(value = "verified-session")))
jar.saveFromResponseIfCurrent(url, listOf(sessionCookie(value = "late-old-response")), beforeLogin)
assertEquals("verified-session", store.cookies.single().value)
}
@Test
fun `verified adoption filters untrusted and expired cookies`() {
val store = MemoryStore()
val jar = BiliCookieJar(store)
jar.replaceSession(listOf(
sessionCookie(), sessionCookie(domain = "evil.example"), sessionCookie(expiresAt = 1),
))
assertEquals(1, store.cookies.size)
assertEquals("bilibili.com", store.cookies.single().domain)
}
}
@@ -0,0 +1,28 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.data.BiliHttpClient
import dev.bulubulu.tv.data.SessionCookieStore
import kotlinx.coroutines.runBlocking
import okhttp3.Cookie
import org.junit.Assert.assertTrue
import org.junit.Test
class BiliHttpClientPolicyTest {
private val client = BiliHttpClient(object : SessionCookieStore {
override fun allCookies() = emptyList<Cookie>()
override fun replaceCookies(cookies: List<Cookie>) = Unit
override fun clear() = Unit
})
@Test
fun `API requests reject cleartext and third parties before making a connection`() = runBlocking {
for (url in listOf(
"http://api.bilibili.com/x/web-interface/nav",
"https://bilibili.com.evil.example/api", "https://example.com/api",
"https://api.bilibili.com:8443/api", "https://user:secret@api.bilibili.com/api",
)) {
val failure = runCatching { client.getJson(url) }.exceptionOrNull()
assertTrue("Unsafe URL accepted: $url", failure is IllegalArgumentException)
}
}
}
@@ -0,0 +1,170 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.core.BiliApiException
import dev.bulubulu.tv.core.VideoEpisode
import dev.bulubulu.tv.data.ContentJson
import java.io.IOException
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 ContentJsonTest {
private val episode = VideoEpisode("cid12", "P1", "示例视频", bvid = "BV1test12345", cid = 12)
@Test
fun recommendationSkipsAdsAndPreservesLargeVideoIds() {
val items = ContentJson.recommendationItems(
JSONArray(
"""[
{"goto":"av","id":117546711844747,"bvid":"BV1test12345","title":"视频","pic":"http://i0.hdslb.com/cover.jpg","duration":65,"owner":{"name":"UP主"}},
{"goto":"ad","id":99,"title":"广告"},
{"goto":"av","id":98,"title":"广告投稿","business_info":{"is_ad":true}},
{"goto":"live","id":100,"title":"直播"},
{"goto":"av","title":"损坏的卡片"}
]""",
),
)
assertEquals(1, items.size)
assertEquals(117546711844747L, items.single().aid)
assertEquals("https://i0.hdslb.com/cover.jpg", items.single().coverUrl)
assertEquals("UP主 · 1:05", items.single().subtitle)
}
@Test
fun seasonCardsRetainRightsBadgeAndEpisodeReference() {
val item = ContentJson.seasonItems(
JSONArray("""[{"season_id":12548,"title":"电影","cover":"//i0.hdslb.com/poster.jpg","badge":"大会员","index_show":"已完结","first_ep":{"ep_id":199612}}]"""),
).single()
assertEquals("ss12548", item.id)
assertEquals(199612L, item.epId)
assertEquals("大会员 · 已完结", item.subtitle)
}
@Test
fun ordinaryVideoHasAllPagesInsteadOfOnlyFirstPage() {
val details = ContentJson.videoDetails(
JSONObject("""{"title":"投稿","bvid":"BV1test12345","aid":117546711844747,"pages":[{"cid":43283448191,"page":1,"part":"上篇"},{"cid":43270800926,"page":2,"part":"下篇"}]}"""),
)
assertEquals(listOf("上篇", "下篇"), details.episodes.map { it.title })
assertEquals(43270800926L, details.episodes[1].cid)
assertNull(details.episodes[1].epId)
}
@Test
fun seasonDetailsSkipHiddenEpisodesButKeepEntitlementChecksForPlayback() {
val details = ContentJson.seasonDetails(
JSONObject("""{"title":"番剧","evaluate":"简介","episodes":[{"id":11,"title":"1","long_title":"开始","status":13},{"id":12,"title":"2","is_view_hide":true}]}"""),
)
assertEquals(1, details.episodes.size)
assertEquals(11L, details.episodes.single().epId)
assertEquals("开始", details.episodes.single().title)
}
@Test
fun selectsH264AndAacTracksAndReportsActualQuality() {
val source = ContentJson.playback(
JSONObject(
"""{
"quality":80,"timelength":120000,"accept_quality":[80,64],"accept_description":["1080P 高清","720P 高清"],
"dash":{"video":[
{"id":80,"height":1080,"codecs":"hvc1.1.6","baseUrl":"https://cdn.example/hevc.m4s","bandwidth":5000},
{"id":64,"height":720,"codecs":"avc1.64001F","base_url":"http://cdn.example/avc.m4s","backup_url":["https://backup.example/avc.m4s"],"bandwidth":2000},
{"id":80,"height":1080,"codecs":"av01.0.08M","baseUrl":"https://cdn.example/av1.m4s","bandwidth":3000}
],"audio":[
{"codecs":"mp4a.40.2","baseUrl":"https://cdn.example/audio.m4s","bandwidth":64000},
{"codecs":"ec-3","baseUrl":"https://cdn.example/dolby.m4s","bandwidth":256000}
]}}
""",
),
episode,
)
assertEquals("https://cdn.example/avc.m4s", source.video.url)
assertEquals(listOf("https://backup.example/avc.m4s"), source.video.backupUrls)
assertEquals("https://cdn.example/audio.m4s", source.audio?.url)
assertEquals("720P 高清", source.qualityLabel)
assertEquals(120000L, source.durationMs)
assertTrue(source.referer.endsWith("BV1test12345"))
}
@Test
fun refusesMembershipPreviewInsteadOfPresentingItAsWholeFilm() {
val error = assertThrows<BiliApiException> {
ContentJson.playback(JSONObject("""{"is_preview":1,"durl":[{"url":"https://cdn.example/preview.mp4"}]}"""), episode)
}
assertEquals(-10001, error.apiCode)
assertTrue(error.message.orEmpty().contains("试看"))
}
@Test
fun refusesDrmRatherThanTryingToBypassIt() {
val error = assertThrows<BiliApiException> {
ContentJson.playback(JSONObject("""{"is_drm":true,"durl":[{"url":"https://cdn.example/protected.mp4"}]}"""), episode)
}
assertEquals(-10003, error.apiCode)
}
@Test
fun acceptsBooleanAndNumericVariantsOfPermissionFlags() {
assertEquals(-10003, assertThrows<BiliApiException> {
ContentJson.playback(JSONObject("""{"is_drm":1}"""), episode)
}.apiCode)
assertEquals(-10001, assertThrows<BiliApiException> {
ContentJson.playback(JSONObject("""{"is_preview":true}"""), episode)
}.apiCode)
assertEquals(-101, assertThrows<BiliApiException> {
ContentJson.playback(JSONObject("""{"need_login":"1"}"""), episode)
}.apiCode)
}
@Test
fun refusesMultiPartProgressiveStreamRatherThanDroppingSegments() {
assertThrows<IOException> {
ContentJson.playback(
JSONObject("""{"durl":[{"url":"https://cdn.example/part1.mp4"},{"url":"https://cdn.example/part2.mp4"}]}"""),
episode,
)
}
}
@Test
fun singleProgressiveFileCanPlayWithoutSeparateAudio() {
val source = ContentJson.playback(
JSONObject("""{"quality":32,"timelength":60000,"durl":[{"url":"https://cdn.example/movie.mp4","backup_url":[]}]}"""),
episode,
)
assertNull(source.audio)
assertEquals("480P", source.qualityLabel)
assertEquals(60000L, source.durationMs)
}
@Test
fun doesNotAcceptNonHttpsOrCredentialBearingMediaUrls() {
assertEquals("", ContentJson.secureUrl("file:///sdcard/token"))
assertEquals("", ContentJson.secureUrl("https://user:secret@cdn.example/video.mp4"))
assertEquals("https://cdn.example/video.mp4", ContentJson.secureUrl("//cdn.example/video.mp4"))
}
@Test
fun handlesPgcResultEnvelopeAndRetainsServerPermissionErrors() {
assertEquals("ok", ContentJson.payload(JSONObject("""{"code":0,"result":{"title":"ok"}}""")).getString("title"))
val error = assertThrows<BiliApiException> {
ContentJson.payload(JSONObject("""{"code":0,"result":{"code":-10403,"message":"抱歉您所在地区不可观看!"}}"""))
}
assertEquals(-10403, error.apiCode)
assertFalse(error.message.orEmpty().isBlank())
}
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,20 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.core.ClientException
import java.io.IOException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
class UserMessageTest {
@Test fun transportErrorsNeverExposeSignedUrlsOrCredentials() {
val message = userMessage(IOException("https://cdn.example/video?token=private-signed-value"))
assertFalse(message.contains("private-signed-value"))
assertFalse(message.contains("cdn.example"))
}
@Test fun deliberatePlaybackErrorsKeepTheirUsefulExplanation() {
val reason = "B 站未提供兼容这台电视的 H.264 视频流"
assertEquals(reason, userMessage(ClientException(reason)))
}
}
@@ -0,0 +1,49 @@
package dev.bulubulu.tv
import dev.bulubulu.tv.data.WbiSigner
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
class WbiSignerTest {
private val imageKey = "7cd084941338484aae1ad9425b84077c"
private val subKey = "4932caff0ff746eab6f01bf08b70ac45"
@Test
fun signsFixedVectorWithSortedParameters() {
val signed = WbiSigner.signParameters(
linkedMapOf("foo" to "114", "bar" to "514", "baz" to "1919810"),
imageKey,
subKey,
1_702_204_169,
)
assertEquals("6149fdadf571698ca7e6a567265cd0ee", signed["w_rid"])
assertEquals("1702204169", signed["wts"])
}
@Test
fun usesRfc3986ForUnicodeSpacesAndReservedCharacters() {
val input = linkedMapOf("title" to "番 剧!'()*", "x" to "a+b/~")
val signed = WbiSigner.signParameters(input, imageKey, subKey, 1_702_204_169)
assertEquals("047238b7514bc6c1e3bfb29b62b68670", signed["w_rid"])
assertEquals("番 剧", signed["title"])
assertEquals("番 剧!'()*", input["title"])
assertFalse(input.containsKey("wts"))
}
@Test
fun replacesCallerSuppliedTimestampAndSignature() {
val signed = WbiSigner.signParameters(
mapOf("foo" to "114", "bar" to "514", "baz" to "1919810", "wts" to "1", "w_rid" to "stale"),
imageKey,
subKey,
1_702_204_169,
)
assertEquals("6149fdadf571698ca7e6a567265cd0ee", signed["w_rid"])
}
@Test(expected = IllegalArgumentException::class)
fun rejectsTruncatedKeys() {
WbiSigner.signParameters(emptyMap(), "short", subKey, 1_702_204_169)
}
}
@@ -0,0 +1,22 @@
package dev.bulubulu.tv.player
import org.junit.Assert.assertEquals
import org.junit.Test
class PlayerControlsTest {
@Test fun seekingNeverCrossesKnownTimelineBounds() {
assertEquals(0L, seekPosition(5_000, 30_000, -10_000))
assertEquals(30_000L, seekPosition(25_000, 30_000, 10_000))
assertEquals(16_000L, seekPosition(6_000, 30_000, 10_000))
}
@Test fun unknownDurationDoesNotBlockForwardSeeking() {
assertEquals(16_000L, seekPosition(6_000, -1, 10_000))
}
@Test fun timeLabelsHandleLongVideosAndMissingDuration() {
assertEquals("00:00", formatPlaybackTime(-1))
assertEquals("02:03", formatPlaybackTime(123_000))
assertEquals("1:02:03", formatPlaybackTime(3_723_000))
}
}