commit 52c840661b3b0882582fe95e3626fda062a9249f Author: loveuer Date: Tue Nov 3 22:57:04 2026 +0800 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. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cbcee71 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +* text=auto +*.kt text eol=lf +*.kts text eol=lf +*.md text eol=lf +*.sh text eol=lf +gradlew text eol=lf +*.bat text eol=crlf +*.png binary +*.jar binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9942dae --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.gradle/ +.kotlin/ +.idea/ +local.properties +**/build/ +*.iml +*.jks +*.keystore +.DS_Store +captures/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..9f929bf --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +## v0.1.0-alpha — 2026-11-03 + +第一个可以构建并在模拟器运行的个人使用版本。 + +- 官方扫码登录与账号验证,支持退出和清除本机凭据。 +- 推荐 / 电影 / 番剧,真实接口、刷新、分页、详情与选集。 +- Media3 H.264 + AAC DASH 播放实现,遥控器播放控制和备用 CDN。 +- 深色极简电视界面,焦点反馈、弹窗和播放器返回后的焦点恢复。 +- Keystore 加密会话、取消扫码隔离、退出竞态保护、备份禁用。 +- 30 项 JVM 测试和 5 项 Android 设备测试通过。 + +Alpha 范围:未验证真实账号扫码确认、登录后会员资源、目标电视解码与真实遥控器;目前没有完整的端到端播放验证。DRM 和旧式多段视频明确不支持。详细验证记录见 [VALIDATION.md](docs/VALIDATION.md)。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..298f12d --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# bulubulu + +一个自己用的 Android TV 哔哩哔哩客户端。Kotlin + Jetpack Compose + Media3,保留扫码登录、推荐、电影、番剧和播放,把交互留给遥控器。 + +当前版本:**v0.1.0-alpha**。 + +![推荐页面](docs/screenshots/recommendation.png) + +## 第一版已有 + +- 使用哔哩哔哩手机客户端扫码并确认登录,不输入账号密码。 +- 推荐视频、电影和番剧三个页签,接入真实官方接口,支持刷新和分页。 +- 视频详情、投稿分 P、番剧选集。 +- 优先获取 H.264 + AAC,合并 DASH 音视频播放;支持暂停、继续、快进和快退。 +- 深色界面、明确的焦点边框与轻微缩放,关闭弹窗或播放器后恢复焦点。 +- 只有联网权限。没有统计 SDK、广告 SDK、自动更新、安装其他应用或存储读取权限。 + +这是非官方的个人客户端。登录不会扩大账号权限,会员、购买、地区限制依然由 B 站服务端决定;目前不支持 DRM 保护播放和旧式多段视频。推荐接口异常时会尝试公共热门列表。第一版没有搜索、弹幕、历史同步、追番管理和播放清晰度菜单。 + +## 遥控器 + +| 场景 | 操作 | +| --- | --- | +| 首页 / 选集 | 方向键移动,确认键选择 | +| 首页内容区 | 返回键把焦点移回当前页签 | +| 弹窗 | 返回键关闭 | +| 播放中 | 确认键暂停 / 继续,左右快退 / 快进 10 秒 | +| 播放中 | 上下显示控制栏,返回退出播放器 | + +在模拟器中可用键盘方向键和 Enter。长按左右每 250ms 最多跳转一次,避免遥控器重复事件导致跳过太多内容。 + +## 构建 + +需要 JDK 17、Android SDK Platform 35、Build Tools 35.0.0。最低系统 Android 6.0,电视的 Android 11 符合基础要求。包含 ARM32 和 ARM64 支持。 + +在本机的 `local.properties` 指定 SDK,文件不会提交到 Git: + +```properties +sdk.dir=/你的/Android/sdk +``` + +```sh +./gradlew assembleDebug testDebugUnitTest lintDebug +``` + +开发版 APK:`app/build/outputs/apk/debug/app-debug.apk`。开发签名使用本机 Android 开发密钥,私钥不在项目中;正式分发前应配置自己的 release 签名并妥善备份。 + +Android Keystore 与遥控器的设备测试需要模拟器。显式指定模拟器序列号,避免误操作其他设备: + +```sh +ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest +``` + +当前这台 Mac 已配置开发环境和 `bulubulu-preview` 模拟器,可运行下面的脚本重新打开窗口、构建并安装到该模拟器。脚本固定操作 `emulator-5580`,不会选择电视: + +```sh +./scripts/preview.sh +``` + +## 隐私与会话 + +Cookie 通过 Android Keystore 的 AES-GCM 密钥加密,保存到禁止备份目录;云备份和设备迁移均禁用。Cookie 只在符合域名、路径、有效期的 B 站 HTTPS 请求中使用,不传给图片或视频 CDN。二维码在本地绘制。 + +扫码使用独立内存会话,确认并验证账号后才保存;取消扫码会作废该尝试。退出先清除本地凭据,再尝试注销旧的官方会话。过期或迟到的网络响应不能把旧会话恢复回来。错误提示不会展示带签名的播放地址或原始网络异常。 + +这不代表第三方客户端可以保证永久兼容:官方网页接口、风控和账号协议可能变化,目标电视的解码和遥控器还需实机检查。当前没有在用户电视上安装。 + +## 项目结构 + +- `core/Models.kt`:共享数据模型与可展示的错误。 +- `data/`:官方接口、WBI 签名、扫码会话与加密存储。 +- `ui/`:首页、登录与选集弹窗、电视焦点组件。 +- `player/`:Media3 播放、备选 CDN 和遥控器控制。 +- `AppViewModel.kt`:分页缓存、登录生命周期、播放与页面状态。 +- `docs/`:接口说明、设计说明和真实运行截图。 + +接口与权限限制见 [CONTENT_API.md](docs/CONTENT_API.md),登录实现见 [AUTH.md](docs/AUTH.md),界面说明见 [UI.md](docs/UI.md)。验证结果记录在 [VALIDATION.md](docs/VALIDATION.md)。 diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000..3a177f2 --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,17 @@ +# Dependencies and references + +No third-party client APK, decompiled application, platform test signing key, analytics SDK or externally supplied native player is included in this project. + +Runtime libraries are resolved from Google's Maven repository and Maven Central: + +| Dependency | Purpose | License / project | +| --- | --- | --- | +| Kotlin / kotlinx.coroutines | Language and asynchronous work | [Apache-2.0](https://github.com/JetBrains/kotlin) | +| AndroidX Activity / Lifecycle / Compose / Media3 | TV interface, lifecycle, playback | [Apache-2.0](https://source.android.com/docs/setup/about/licenses) | +| OkHttp | HTTPS requests and cookie handling | [Apache-2.0](https://github.com/square/okhttp) | +| Coil | Cover image loading | [Apache-2.0](https://github.com/coil-kt/coil) | +| ZXing | Local QR image generation | [Apache-2.0](https://github.com/zxing/zxing) | + +JUnit, MockWebServer, AndroidX Test and the JVM org.json implementation are test dependencies and are not used as analytics or bundled application services. + +Public API reference: [bilibili-API-collect](https://github.com/SocialSisterYi/bilibili-API-collect). The application uses official Bilibili HTTPS endpoints and preserves their account/region/DRM restrictions. No Bilibili client code or credentials are bundled. Screenshots contain remotely fetched catalogue metadata and covers, whose rights remain with their respective owners; they are documentation, not built-in application assets. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..9902ae5 --- /dev/null +++ b/app/build.gradle.kts @@ -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") +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..41d3058 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,2 @@ +# Models and network payloads are parsed explicitly; no reflection-based JSON mapper. +-keepattributes Signature,InnerClasses,EnclosingMethod diff --git a/app/src/androidTest/java/dev/bulubulu/tv/SessionStoreInstrumentedTest.kt b/app/src/androidTest/java/dev/bulubulu/tv/SessionStoreInstrumentedTest.kt new file mode 100644 index 0000000..34e1d12 --- /dev/null +++ b/app/src/androidTest/java/dev/bulubulu/tv/SessionStoreInstrumentedTest.kt @@ -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()) + } +} diff --git a/app/src/androidTest/java/dev/bulubulu/tv/ui/TvRemoteNavigationTest.kt b/app/src/androidTest/java/dev/bulubulu/tv/ui/TvRemoteNavigationTest.kt new file mode 100644 index 0000000..3140fc8 --- /dev/null +++ b/app/src/androidTest/java/dev/bulubulu/tv/ui/TvRemoteNavigationTest.kt @@ -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) } + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9b8c130 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/java/dev/bulubulu/tv/AppViewModel.kt b/app/src/main/java/dev/bulubulu/tv/AppViewModel.kt new file mode 100644 index 0000000..24ed691 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/AppViewModel.kt @@ -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(null) + val playback = _playback.asStateFlow() + private val _notice = MutableStateFlow(null) + val notice = _notice.asStateFlow() + + private data class CachedFeed(val items: List, val nextPage: Int?) + private val feeds = mutableMapOf() + 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 +} diff --git a/app/src/main/java/dev/bulubulu/tv/BulubuluApplication.kt b/app/src/main/java/dev/bulubulu/tv/BulubuluApplication.kt new file mode 100644 index 0000000..3572013 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/BulubuluApplication.kt @@ -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) } +} diff --git a/app/src/main/java/dev/bulubulu/tv/MainActivity.kt b/app/src/main/java/dev/bulubulu/tv/MainActivity.kt new file mode 100644 index 0000000..403de79 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/MainActivity.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/core/Models.kt b/app/src/main/java/dev/bulubulu/tv/core/Models.kt new file mode 100644 index 0000000..6ddf50a --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/core/Models.kt @@ -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, 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) +data class PlaybackStream(val url: String, val backupUrls: List = 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) diff --git a/app/src/main/java/dev/bulubulu/tv/data/AuthRepository.kt b/app/src/main/java/dev/bulubulu/tv/data/AuthRepository.kt new file mode 100644 index 0000000..b4d4bf8 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/data/AuthRepository.kt @@ -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" + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/data/BiliHttpClient.kt b/app/src/main/java/dev/bulubulu/tv/data/BiliHttpClient.kt new file mode 100644 index 0000000..63323b0 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/data/BiliHttpClient.kt @@ -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) { + // 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 { + 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) { + saveFromResponseIfCurrent(url, cookies, currentEpoch()) + } + + @Synchronized + fun saveFromResponseIfCurrent(url: HttpUrl, cookies: List, 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 = emptyMap(), + allowedApiCodes: Set = 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): 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) = 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): 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)" } + } + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/data/ContentRepository.kt b/app/src/main/java/dev/bulubulu/tv/data/ContentRepository.kt new file mode 100644 index 0000000..218039d --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/data/ContentRepository.kt @@ -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): 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 = 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 = 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 = 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 { 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 = + if (this == null) emptyList() else (0 until length()).mapNotNull(::optJSONObject) + + private fun JSONArray?.strings(): List = + if (this == null) emptyList() else (0 until length()).mapNotNull { index -> + optString(index).takeIf { it.isNotBlank() && it != "null" } + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/data/SessionStore.kt b/app/src/main/java/dev/bulubulu/tv/data/SessionStore.kt new file mode 100644 index 0000000..2b1003c --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/data/SessionStore.kt @@ -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 + fun replaceCookies(cookies: List) + 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 = readEncryptedCookies() + + @Synchronized + override fun allCookies(): List = cookies.toList() + + @Synchronized + override fun replaceCookies(cookies: List) { + 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 { + 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 = emptyList()) : SessionCookieStore { + private var cookies = initial.toList() + + @Synchronized + override fun allCookies(): List = cookies.toList() + + @Synchronized + override fun replaceCookies(cookies: List) { this.cookies = cookies.toList() } + + @Synchronized + override fun clear() { cookies = emptyList() } +} diff --git a/app/src/main/java/dev/bulubulu/tv/data/WbiSigner.kt b/app/src/main/java/dev/bulubulu/tv/data/WbiSigner.kt new file mode 100644 index 0000000..8f134a2 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/data/WbiSigner.kt @@ -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): Map { + 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, + imageKey: String, + subKey: String, + timestampSeconds: Long, + ): Map { + 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", "~") + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/player/BackupDataSource.kt b/app/src/main/java/dev/bulubulu/tv/player/BackupDataSource.kt new file mode 100644 index 0000000..2ac51cb --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/player/BackupDataSource.kt @@ -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>, +) : DataSource { + private var active: DataSource? = null + private val listeners = mutableListOf() + + 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> = active?.responseHeaders.orEmpty() + + override fun close() { + val current = active + active = null + current?.close() + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/player/PlayerControls.kt b/app/src/main/java/dev/bulubulu/tv/player/PlayerControls.kt new file mode 100644 index 0000000..ebe7b5c --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/player/PlayerControls.kt @@ -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 +} diff --git a/app/src/main/java/dev/bulubulu/tv/player/PlayerScreen.kt b/app/src/main/java/dev/bulubulu/tv/player/PlayerScreen.kt new file mode 100644 index 0000000..b1cb6cb --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/player/PlayerScreen.kt @@ -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(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) + } + } + } + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/ui/BulubuluHome.kt b/app/src/main/java/dev/bulubulu/tv/ui/BulubuluHome.kt new file mode 100644 index 0000000..8d53d4f --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/ui/BulubuluHome.kt @@ -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() } + 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)) + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/ui/BulubuluTheme.kt b/app/src/main/java/dev/bulubulu/tv/ui/BulubuluTheme.kt new file mode 100644 index 0000000..fb4a9e0 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/ui/BulubuluTheme.kt @@ -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, + ) +} diff --git a/app/src/main/java/dev/bulubulu/tv/ui/Dialogs.kt b/app/src/main/java/dev/bulubulu/tv/ui/Dialogs.kt new file mode 100644 index 0000000..23dd5b1 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/ui/Dialogs.kt @@ -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)) + } + } + } +} diff --git a/app/src/main/java/dev/bulubulu/tv/ui/HomeUiState.kt b/app/src/main/java/dev/bulubulu/tv/ui/HomeUiState.kt new file mode 100644 index 0000000..c9894b8 --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/ui/HomeUiState.kt @@ -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 = emptyList(), + val loading: Boolean = true, + val loadingMore: Boolean = false, + val error: String? = null, + val hasMore: Boolean = true, + val authBusy: Boolean = false, +) diff --git a/app/src/main/java/dev/bulubulu/tv/ui/TvAction.kt b/app/src/main/java/dev/bulubulu/tv/ui/TvAction.kt new file mode 100644 index 0000000..94eb37c --- /dev/null +++ b/app/src/main/java/dev/bulubulu/tv/ui/TvAction.kt @@ -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) + } +} diff --git a/app/src/main/res/drawable/app_banner.xml b/app/src/main/res/drawable/app_banner.xml new file mode 100644 index 0000000..77babf7 --- /dev/null +++ b/app/src/main/res/drawable/app_banner.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/drawable/app_icon.xml b/app/src/main/res/drawable/app_icon.xml new file mode 100644 index 0000000..034ec36 --- /dev/null +++ b/app/src/main/res/drawable/app_icon.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..2142a27 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + bulubulu + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..53b6bb3 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,11 @@ + + + + diff --git a/app/src/main/res/xml/data_extraction_rules.xml b/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 0000000..224515d --- /dev/null +++ b/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/app/src/test/java/dev/bulubulu/tv/BiliCookieJarTest.kt b/app/src/test/java/dev/bulubulu/tv/BiliCookieJarTest.kt new file mode 100644 index 0000000..38ef371 --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/BiliCookieJarTest.kt @@ -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 = emptyList() + override fun allCookies() = cookies.toList() + override fun replaceCookies(cookies: List) { 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) + } + +} diff --git a/app/src/test/java/dev/bulubulu/tv/BiliHttpClientPolicyTest.kt b/app/src/test/java/dev/bulubulu/tv/BiliHttpClientPolicyTest.kt new file mode 100644 index 0000000..6493e84 --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/BiliHttpClientPolicyTest.kt @@ -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() + override fun replaceCookies(cookies: List) = 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) + } + } +} diff --git a/app/src/test/java/dev/bulubulu/tv/ContentJsonTest.kt b/app/src/test/java/dev/bulubulu/tv/ContentJsonTest.kt new file mode 100644 index 0000000..cec5eea --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/ContentJsonTest.kt @@ -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 { + 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 { + ContentJson.playback(JSONObject("""{"is_drm":true,"durl":[{"url":"https://cdn.example/protected.mp4"}]}"""), episode) + } + assertEquals(-10003, error.apiCode) + } + + @Test + fun acceptsBooleanAndNumericVariantsOfPermissionFlags() { + assertEquals(-10003, assertThrows { + ContentJson.playback(JSONObject("""{"is_drm":1}"""), episode) + }.apiCode) + assertEquals(-10001, assertThrows { + ContentJson.playback(JSONObject("""{"is_preview":true}"""), episode) + }.apiCode) + assertEquals(-101, assertThrows { + ContentJson.playback(JSONObject("""{"need_login":"1"}"""), episode) + }.apiCode) + } + + @Test + fun refusesMultiPartProgressiveStreamRatherThanDroppingSegments() { + assertThrows { + 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 { + ContentJson.payload(JSONObject("""{"code":0,"result":{"code":-10403,"message":"抱歉您所在地区不可观看!"}}""")) + } + assertEquals(-10403, error.apiCode) + assertFalse(error.message.orEmpty().isBlank()) + } + + private inline fun 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}") + } +} diff --git a/app/src/test/java/dev/bulubulu/tv/UserMessageTest.kt b/app/src/test/java/dev/bulubulu/tv/UserMessageTest.kt new file mode 100644 index 0000000..3999d0e --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/UserMessageTest.kt @@ -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))) + } +} diff --git a/app/src/test/java/dev/bulubulu/tv/WbiSignerTest.kt b/app/src/test/java/dev/bulubulu/tv/WbiSignerTest.kt new file mode 100644 index 0000000..cb8bea3 --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/WbiSignerTest.kt @@ -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) + } +} diff --git a/app/src/test/java/dev/bulubulu/tv/player/PlayerControlsTest.kt b/app/src/test/java/dev/bulubulu/tv/player/PlayerControlsTest.kt new file mode 100644 index 0000000..5797c82 --- /dev/null +++ b/app/src/test/java/dev/bulubulu/tv/player/PlayerControlsTest.kt @@ -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)) + } +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..1b4481a --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "2.0.21" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..f01b21e --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,14 @@ +# Architecture + +The application has one Android app module and no backend service. + +- `MainActivity` renders Compose, collects lifecycle-aware state and coordinates overlay focus restoration. +- `AppViewModel` owns feed pagination/cache, cancellable detail/playback requests, visible-screen QR polling and serialized account transitions. +- `AuthRepository` uses the official web QR flow with an isolated in-memory attempt. Only a verified active attempt can atomically replace the durable account session. +- `BiliHttpClient` validates official HTTPS API destinations, scopes cookies per network hop, bounds response sizes and propagates coroutine cancellation to OkHttp calls. +- `SessionStore` encrypts cookies with an Android Keystore AES-GCM key and writes an atomic file in `noBackupFilesDir`. +- `ContentRepository` retrieves official catalogue/details/playback responses; `WbiSigner` caches official signing material; pure `ContentJson` parsing separates format and entitlement checks from transport. +- `BulubuluHome`, dialogs and `TvAction` own TV layout/focus. Home stays composed beneath overlays, with focus/clicks disabled while inactive. +- `PlayerScreen` creates and releases Media3 with the composable lifecycle, merges separate AVC/AAC tracks and handles D-pad/media keys. CDN requests never receive account cookies. + +There is no analytics, self-update service, local media scanning or private server. Login credentials and signed playback URLs must never appear in application logs or raw error messages. Account entitlements and region/DRM restrictions remain server-controlled. Tests use fake sessions in isolated storage and do not require a real account. diff --git a/docs/AUTH.md b/docs/AUTH.md new file mode 100644 index 0000000..e9cdb82 --- /dev/null +++ b/docs/AUTH.md @@ -0,0 +1,12 @@ +# 登录与会话实现说明 + +- 二维码由官方 `passport.bilibili.com/x/passport-login/web/qrcode/generate` 获取,在电视本地用 ZXing 绘制;不通过第三方生成图片。 +- 手机哔哩哔哩扫码后由官方接口轮询确认:86101 等待扫码、86090 等待手机确认、86038 过期、0 成功。 +- 成功响应中的官方 `Set-Cookie` 只进入该次扫码独立的内存会话,通过官方 `/x/web-interface/nav` 验证用户后,仅在扫码仍有效且前台协程未取消时原子提交到持久会话。关闭/暂停二维码会丢弃待确认的会话,避免迟到响应在后台悄悄登录。不会访问 poll JSON 返回的跨站同步 URL,不收集密码,也不向第三方传递 Cookie。 +- 会话 Cookie 经 Android Keystore 内 AES-GCM 密钥加密,写入 `noBackupFilesDir/session.enc`,原子替换;密钥不可导出。损坏的存储或丢失的 Keystore 密钥导致退出登录,不降级为明文。 +- HTTP 层每一跳重新计算 Cookie,严格遵守域名、路径、有效期,并且仅向 HTTPS 的 `bilibili.com` 及其子域发送。图片/CDN、第三方和 HTTP 不会收到会话 Cookie。 +- 退出登录先立即删除本地会话,再用隔离的旧会话尽力调用官方注销接口。该请求迟到也不会删除之后的新登录。Cookie 代次保护还可避免旧网络响应覆盖已验证的新账号。 +- 只有官方明确返回未登录时清理失效凭据。网络失败、HTTP 412 风控和服务器错误不会触发删除登录状态。 +- 没有统计 SDK、崩溃上传、口令输入、刷新令牌上传或自动升级器。没有实现 Cookie 自动续期;失效后重新扫码。 + +验证范围:官方匿名 nav 和 QR 生成接口已成功做只读探测。未使用用户账号完成扫码,也未在电视上安装。单元测试覆盖 Cookie 域名/路径/HTTPS/过期/替换、退出登录竞态,以及 JSON API URL 限制。Keystore 加密需要真机或 Android 模拟器验证,普通 JVM 单元测试不能代替。 diff --git a/docs/CONTENT_API.md b/docs/CONTENT_API.md new file mode 100644 index 0000000..d5bd4e6 --- /dev/null +++ b/docs/CONTENT_API.md @@ -0,0 +1,33 @@ +# 内容接口与播放范围 + +本客户端的内容请求仅使用 B 站官方 HTTPS Web API,沿用扫码登录获得的 Cookie,不访问作者自建解析服务,不添加统计或自动更新服务。 + +## 当前路径 + +- 推荐:`/x/web-interface/wbi/index/top/feed/rcmd`。WBI 公共签名信息来自 `/x/web-interface/nav`,缓存最多六小时,签名失效时刷新一次。登录后由服务端决定推荐内容;未登录时仍可浏览。推荐接口返回特定风控错误时,降级到官方 `/x/web-interface/popular`,并不改变内容权限。 +- 电影和番剧:`/pgc/season/index/result`,分别使用 `season_type=2` 和 `season_type=1`,按播放量排序并支持分页。卡片保留会员等权益标签。 +- 投稿详情/分 P:`/x/web-interface/view`。 +- 电影/番剧详情与选集:`/pgc/view/web/season`,只展示正片集数,不把额外花絮自动加入播放列表。 +- 投稿播放:`/x/player/wbi/playurl`。 +- 电影/番剧播放:`/pgc/player/web/playurl`。 + +播放请求按普通 Web 客户端获取服务端允许的视频流,优先选择不高于常规 1080P 的 H.264 与 AAC,适合已知的 32 位 ARM Android 11 电视。清晰度由实际返回的轨道决定,登录和会员权益仍以 B 站接口结果为准。HTTP 图片/CDN链接升级到 HTTPS。 + +## 明确处理的限制 + +- 不绕过登录、会员、购买、区域、付费或 DRM 检查。 +- `is_preview=1` 的会员试看不会被当作完整电影播放,会提示确认登录和账号权限。 +- DRM 流暂不支持,并返回明确说明。 +- 支持 DASH 的分离视频/音轨,以及单个 progressive 文件;老式多段 progressive 流会明确提示不支持,不会只播第一段。 +- 当前没有弹幕、离线下载、评论、投币或自建视频代理。 +- 没有可复用的用户登录会话,因此“登录后推荐”和付费内容完整播放尚需用户以后在设备上验证。代码和公开接口正常响应不能替代电视遥控器及解码实测。 + +## 2026-11-03 电脑侧只读探测 + +使用浏览器 User-Agent 和 `Referer: https://www.bilibili.com/`,实际获得了匿名推荐、电影、番剧、投稿分 P、剧集选集的正常响应,UGC 播放接口返回 H.264 + AAC DASH;会员电影接口返回带 `is_preview=1` 的试看,因此客户端正确拒绝把它作为完整片源。 + +公开接口随 B 站更新可能变化。风控、账号权限、地域或网络错误会向界面返回,不能承诺所有内容都能播放。 + +## 单元测试 + +WBI 测试覆盖固定签名向量、Unicode/空格/保留字符编码、输入不变性和旧签名替换。解析测试覆盖大整数 ID、广告/非视频卡片过滤、分 P、剧集、H.264/AAC 选择、实际清晰度、会员试看/DRM拒绝、旧多段流拒绝和 PGC 的权限错误。 diff --git a/docs/UI.md b/docs/UI.md new file mode 100644 index 0000000..e3fea21 --- /dev/null +++ b/docs/UI.md @@ -0,0 +1,19 @@ +# TV interface and controls + +The first build uses an ink / warm-white / soft-pink palette: background `#0C1017`, panel `#181F29`, text `#F5F1ED`, secondary text `#9DAAB9`, accent `#FFA5B9`. Pink marks selection and focus; normal cards use dark surfaces. All shapes are authored in Compose and no marketing artwork is bundled. + +At a typical 960 × 540 dp TV viewport, the home screen has 38 dp horizontal and 24 dp vertical safe insets, a 44 dp tab/action row, a 21 sp section heading, and a four-column recommendation grid and five-column portrait grid with 18 dp gaps. Recommendation thumbnails are 16:9; movie/bangumi covers use a 0.72 portrait ratio. Focused cards gain a 3 dp border and a 1.025 scale. Buttons and episode items have at least 44 dp height. Account status stays in a top-right capsule. Loading, empty, error and pagination states use the same layout and do not insert a fake catalogue. + +## Remote + +- Home: direction keys move among tabs, cards, refresh, account and load more. Confirm selects a tab or opens video details. Back from the grid returns focus to the selected tab. Android's normal back handling applies from the header. +- Details: first episode receives focus after loading. Confirm starts playback. Multi-part videos and series have an episode grid. Back closes the dialog. +- Login: QR code is generated locally with ZXing, not uploaded to a QR service. Refresh and close are D-pad targets. Closing cancels the parent-owned poll task. No password input is present. +- Player: confirm or play/pause toggles playback; left/right seek ten seconds, with long press throttled to one step per 250 ms. Up/down display controls. Back exits playback directly. Both key-down and key-up are consumed so Android PlayerView cannot apply the same event twice. Controls remain visible when paused/end/error and hide after four seconds during playback. +- App backgrounding pauses the player; foregrounding resumes only if it was previously playing. Leaving the player releases Media3 and screen-on state. + +The player requests signed CDN URLs with a Bilibili Referer and browser User-Agent, without account cookies. It merges separate AVC/AAC fMP4 tracks through Media3, can use official backup CDN URLs after connection failure, and hides raw decoder/network exceptions that might include signed URLs. Actual decoder/remote behavior still needs testing on the target TV. + +## Visual review + +Prefer an emulator screenshot of the real Compose UI. If an HTML preview is used before an emulator is available, label it as a layout preview, use the dimensions/palette above and real fetched API data, and do not treat it as runtime verification. Community screenshots from unrelated clients are not assets for this app. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000..dcc83df --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,32 @@ +# v0.1.0-alpha 验证记录 + +日期:2026-11-03。 + +## 已验证 + +- 使用 Gradle 8.9、JDK 17、Android SDK 35 构建开发版 APK。 +- JVM 单元测试:30 项通过,0 失败。覆盖 Cookie 域名/路径/HTTPS/有效期隔离、账号切换与退出后的迟到响应、WBI 签名、内容解析、播放格式与权限判断、遥控器跳转边界、错误提示不泄露原始网络地址。 +- Android 11 ARM64 模拟器:5 项设备测试通过,0 失败。其中 2 项测试验证实际 Android Keystore 加密存储的重建读取与密文篡改后拒绝恢复;3 项测试验证方向键切换页签、选集和覆盖层焦点隔离。 +- Android Lint:无错误;保留依赖升级建议、固定横屏、targetSdk 等警告。依赖版本已固定,未宣称完成所有第三方依赖的漏洞审计。 +- 匿名官方接口:推荐、电影目录、番剧目录、投稿详情、剧集选集、H.264/AAC DASH 地址、二维码生成和等待扫码状态均曾返回有效数据。 +- 真实 Compose 应用已在电脑模拟器运行,已显示远程获取的推荐、电影封面和文本。`screenshots/recommendation.png` 是运行截图,不是网页效果图或预置目录。 +- 用户已在电脑上查看模拟器界面并认可作为首个 alpha 版本。 + +## 仍待验证 + +- 用户手机扫码确认后,真实账号登录、重启恢复、失效与退出的端到端行为。 +- 登录后的个性化推荐与账号实际有权观看的电影/番剧。 +- 持续播放、音画同步、暂停/跳转、后台恢复等完整端到端播放表现。已验证解析和控制逻辑,不等于已验证完整播放。 +- ARM32 雷鸟/TCL 电视的真实解码器、遥控器、焦点和分辨率适配。 +- 网络变化、官方接口或风控策略变化下的长期稳定性。 + +本次没有连接或安装到用户电视;设备测试固定使用 `emulator-5580`。 + +## 复现 + +```sh +./gradlew assembleDebug testDebugUnitTest lintDebug +ANDROID_SERIAL=emulator-5580 ./gradlew connectedDebugAndroidTest +``` + +设备测试需要已启动的模拟器。测试使用独立存储目录和假测试会话,不需要用户账号;Gradle 的 connected 测试任务可能在结束后移除测试安装的 APK。如需继续查看,运行 `./scripts/preview.sh` 重新部署到预览模拟器。 diff --git a/docs/screenshots/recommendation.png b/docs/screenshots/recommendation.png new file mode 100644 index 0000000..fd1da78 Binary files /dev/null and b/docs/screenshots/recommendation.png differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ce96a98 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +android.useAndroidX=true +kotlin.code.style=official +android.nonTransitiveRClass=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..2c35211 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7179de4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/scripts/preview.sh b/scripts/preview.sh new file mode 100755 index 0000000..499cfb6 --- /dev/null +++ b/scripts/preview.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_dir="$(cd "$(dirname "$0")/.." && pwd)" +sdk_dir="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}" +adb_bin="$sdk_dir/platform-tools/adb" +emulator_bin="$sdk_dir/emulator/emulator" +serial="emulator-5580" +avd_name="bulubulu-preview" + +if [[ ! -x "$adb_bin" || ! -x "$emulator_bin" ]]; then + echo "找不到 Android SDK,请先配置 ANDROID_HOME。" >&2 + exit 1 +fi + +cd "$project_dir" +./gradlew assembleDebug +mkdir -p .gradle + +if ! "$adb_bin" -s "$serial" get-state >/dev/null 2>&1; then + "$emulator_bin" -avd "$avd_name" -ports 5580,5581 -no-snapshot -gpu swiftshader \ + >.gradle/preview-emulator.log 2>&1 & +fi + +ready=0 +for ((attempt=0; attempt<120; attempt++)); do + if [[ "$("$adb_bin" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == "1" ]]; then + ready=1 + break + fi + sleep 1 +done +if [[ "$ready" != "1" ]]; then + echo "模拟器未能启动,请检查 .gradle/preview-emulator.log。" >&2 + exit 1 +fi + +running_avd="$("$adb_bin" -s "$serial" emu avd name | head -n 1 | tr -d '\r')" +if [[ "$running_avd" != "$avd_name" ]]; then + echo "5580 端口运行的是其他模拟器,已停止部署。" >&2 + exit 1 +fi + +"$adb_bin" -s "$serial" install -r app/build/outputs/apk/debug/app-debug.apk +"$adb_bin" -s "$serial" shell am start -n dev.bulubulu.tv/.MainActivity +echo "已打开 bulubulu。用方向键移动,Enter 确认。" diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..17e8ba0 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "bulubulu" +include(":app")