Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ plugins {

// 支持通过 -PVERSION_NAME / -PVERSION_CODE 显式传入版本信息。
// 未显式传入 VERSION_NAME 时,默认把最后一段 patch 替换为 BUILD_NUMBER。
val baseAppVersionName = "2.17.0"
val baseAppVersionName = "2.18.0"

fun String?.nonBlankOrNull(): String? =
this?.trim()?.takeIf { it.isNotBlank() }
Expand Down
31 changes: 31 additions & 0 deletions app/src/main/kotlin/com/miruplay/tv/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,23 @@ package com.miruplay.tv.di
import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import com.miruplay.tv.BuildConfig
import com.miruplay.tv.audiomeasure.AudioMeasureController
import com.miruplay.tv.data.db.MiruPlayDatabase
import com.miruplay.tv.repository.AppCredentialStore
import com.miruplay.tv.repository.CloudDriveAutomationRepository
import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig
import com.miruplay.tv.scraper.core.BangumiOAuthClient
import com.miruplay.tv.scraper.core.toBangumiHttpProxyConfig
import com.miruplay.tv.sync.BangumiOAuthCoordinator
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit
Expand Down Expand Up @@ -56,6 +66,27 @@ object AppModule {
fun provideToppingController(@ApplicationContext context: Context): com.miruplay.tv.topping.ToppingController {
return com.miruplay.tv.topping.ToppingController(com.miruplay.tv.topping.ToppingUsb(context))
}

@Provides
@Singleton
fun provideBangumiOAuthCoordinator(
credentials: AppCredentialStore,
cloudDriveRepository: CloudDriveAutomationRepository,
): BangumiOAuthCoordinator {
val client = BangumiOAuthClient(
clientId = BuildConfig.BANGUMI_CLIENT_ID,
clientSecret = BuildConfig.BANGUMI_CLIENT_SECRET,
)
return BangumiOAuthCoordinator(
credentials = credentials,
client = client.takeIf { it.isConfigured },
scope = CoroutineScope(SupervisorJob() + Dispatchers.Default),
proxyConfig = {
cloudDriveRepository.getConfig().getOrNull()?.toBangumiHttpProxyConfig()
?: BangumiHttpProxyConfig.Disabled
},
)
}
}

internal fun miruPlayDatabaseMigrations(): Array<Migration> =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,47 @@ fun metadataBangumiTokenEmptyMessage(): UiText =
fun metadataBangumiTokenClearedMessage(): UiText =
uiText("settings_metadata_bangumi_cleared_msg", "Bangumi Access Token 已清除。")

fun metadataBangumiOAuthNotConfiguredMessage(): UiText =
uiText("settings_metadata_bangumi_oauth_unconfigured", "未配置 Bangumi OAuth 应用信息,无法登录。")

fun metadataBangumiOAuthFailedMessage(detail: String = ""): UiText =
if (detail.isBlank()) {
uiText("settings_metadata_bangumi_oauth_failed", "Bangumi 登录失败。")
} else {
UiText("settings_metadata_bangumi_oauth_failed_detail", listOf(detail), "Bangumi 登录失败:$detail")
}

fun metadataBangumiOAuthSuccessMessage(): UiText =
uiText("settings_metadata_bangumi_oauth_success", "Bangumi 登录成功。")

fun metadataBangumiOAuthExchangingMessage(): UiText =
uiText("settings_metadata_bangumi_oauth_exchanging", "正在与 Bangumi 交换令牌…")

fun metadataBangumiOAuthLoginActionLabel(): UiText =
uiText("settings_metadata_bangumi_oauth_login", "使用 Bangumi 登录")

fun metadataBangumiOAuthDialogTitle(): UiText =
uiText("settings_metadata_bangumi_oauth_title", "Bangumi 登录")

fun metadataBangumiOAuthExternalBrowserActionLabel(): UiText =
uiText("settings_metadata_bangumi_oauth_external", "用外部浏览器打开")

fun metadataBangumiOAuthCancelActionLabel(): UiText =
uiText("settings_metadata_bangumi_oauth_cancel", "取消")

fun metadataBangumiOAuthLogoutActionLabel(): UiText =
uiText("settings_metadata_bangumi_oauth_logout", "退出登录")

fun metadataBangumiOAuthValidUntilMessage(expiresAtMillis: Long): UiText {
val text = if (expiresAtMillis > 0L) {
java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())
.format(java.util.Date(expiresAtMillis))
} else {
""
}
return UiText("settings_metadata_bangumi_oauth_valid_until", listOf(text), "有效期至 $text")
}

fun metadataTmdbTokenSavedMessage(): UiText =
uiText("settings_metadata_tmdb_saved_msg", "TMDB Token 已保存。")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,18 @@ class SecurePreferencesManager @Inject constructor(
securePrefs.edit().putString(KEY_BANGUMI_TOKEN, value).apply()
}

override var bangumiRefreshToken: String?
get() = securePrefs.getString(KEY_BANGUMI_REFRESH_TOKEN, null)
set(value) {
securePrefs.edit().putString(KEY_BANGUMI_REFRESH_TOKEN, value).apply()
}

override var bangumiTokenExpiresAtMillis: Long
get() = securePrefs.getLong(KEY_BANGUMI_TOKEN_EXPIRES_AT, 0L)
set(value) {
securePrefs.edit().putLong(KEY_BANGUMI_TOKEN_EXPIRES_AT, value).apply()
}

override var tmdbAccessToken: String?
get() = securePrefs.getString(KEY_TMDB_TOKEN, null)
set(value) {
Expand Down Expand Up @@ -128,7 +140,11 @@ class SecurePreferencesManager @Inject constructor(
}

override fun clearBangumiToken() {
securePrefs.edit().remove(KEY_BANGUMI_TOKEN).apply()
securePrefs.edit()
.remove(KEY_BANGUMI_TOKEN)
.remove(KEY_BANGUMI_REFRESH_TOKEN)
.remove(KEY_BANGUMI_TOKEN_EXPIRES_AT)
.apply()
}

override fun clearTmdbToken() {
Expand Down Expand Up @@ -157,6 +173,8 @@ class SecurePreferencesManager @Inject constructor(
private const val SECURE_PREFERENCES_NAME = "miruplay_secure_prefs"
private const val COMPATIBILITY_PREFERENCES_NAME = "miruplay_secure_prefs_compat"
private const val KEY_BANGUMI_TOKEN = "bangumi_access_token"
private const val KEY_BANGUMI_REFRESH_TOKEN = "bangumi_refresh_token"
private const val KEY_BANGUMI_TOKEN_EXPIRES_AT = "bangumi_token_expires_at"
private const val KEY_TMDB_TOKEN = "tmdb_access_token"
private const val KEY_TMDB_API_BASE_URL_OVERRIDE = "tmdb_api_base_url_override"
private const val KEY_CLOUD_DRIVE_TOKEN = "cloud_drive_token"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ class LogUploadRepositoryImplTest {

private class FakeCredentialStore : AppCredentialStore {
override var bangumiAccessToken: String? = null
override var bangumiRefreshToken: String? = null
override var bangumiTokenExpiresAtMillis: Long = 0L
override var tmdbAccessToken: String? = null
override var tmdbApiBaseUrlOverride: String? = null
override var otlpAccessToken: String? = null
Expand Down
33 changes: 33 additions & 0 deletions docs/agents/pre-pr-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,36 @@ Cross-checks:
New failure class (section 1 candidate):

- **Probe-gates-playback on unreachable networks** — a pre-playback metadata probe using a non-proxy transport (platform MediaExtractor, raw HttpURLConnection) hangs instead of failing fast, blocking the player start behind it with zero log signal. Check: every pre-playback network access must either share the playback transport/proxy config or have a hard timeout + skip path; verify on device with the origin blocked (direct connection must fail fast, proxy path must play).

### Bangumi OAuth 直连登录(回环回调 + 7 天轮换)(v2.18)

Own checks (unit-tested + 真机闭环已验证,HK1 @ 2026-10-20):

- 未配置 client id/secret 时构建照常通过,设置页显示"未配置"状态而非崩溃(BuildConfig 空字符串兜底;CI 同仓库 PR 带 secret,fork PR 为空)
- 回调 `state` 对不上直接拒绝,不触发换 token;换 token 失败停留在 Failed 状态,可重试/取消
- 刷新逻辑:有效期内直接返回现有 token;临期(24h)自动 refresh 并持久化新 pair;refresh 失败但旧 token 未过期则继续用旧 token,不把用户踢下线
- `submitCallbackUrl` 的换 token 跑在新协程里,不占回环监听线程(izuko 踩过的坑:监听线程自取消会导致换 token 请求夭折)
- full `./gradlew assembleDebug test lint` green;新单测:OAuthClient 授权 URL/换 token/刷新/错误映射/MockWebServer、coordinator 状态机/去重/刷新边际/登出、SettingsViewModel 接线
- [真机] WebView 授权页加载 → 账号登录并授权 → 自动跳回:显示"Token 已保存在加密存储中。"+"有效期至 2026-10-27 20:57"(7 天 TTL 与 bgm access_token 一致,证明换 token 解析与落库正确)+ 退出登录按钮 + 左侧"元数据 已设置 1 项"
- [真机] 到达成功态本身即证明全链:授权 URL 三件正确 → 回环接住 code → token 端点 200 → 加密持久化 → UI 状态刷新
- [真机] force-stop 冷启动后登录态仍在,无崩溃;操作全程 logcat 无 AndroidRuntime:E

Cross-checks:

- 手动贴 Token 链路原样保留(coordinator 只读写同一套 SecurePreferences 键,互不覆盖语义外行为);现有 Bangumi 搜索/收藏/同步走 `tokenProvider` 读到的仍是同一份 access token
- WebAPI/WebUI 刻意不同步 OAuth 流程:回环回调 + WebView + 外部浏览器都是设备本地能力,Web 端已有手动 token 读写端点覆盖管理面;TV 设置页为唯一入口(surface-specific,见 parity 表)
- 新增 i18n key 四地对齐 + UiTextResolver 映射(lint MissingTranslation 通过)
- [真机] 同步全部 Bangumi 进度在空媒体库下点按无可见变化——符合设计(`animeCount > 0` 才显示结果行,`syncAllBangumi()` 空库直接返回零统计且不联网),不是 bug

Not device-verified (to be covered by follow-ups, reason recorded):

- 外部浏览器路径(回环监听在外部浏览器回调下的存活)——当时设备无可用系统浏览器做对照,且 WebView 路径已证明回环有效
- 退出登录清理 —— 会登出用户刚登录的真实账号,需用户授权后再测
- 临期自动刷新 —— 需改系统时间或等 6 天窗口,单测已覆盖分支
- 无网络/代理未配失败态 —— 墙内直连 bgm.tv 本就超时,失败重试分支走单测

New findings (section 1 candidates / product constraints):

- **WebView 不走应用代理,只认系统全局代理**:墙内网络下没有系统代理的盒子连授权页都打不开(ERR_CONNECTION_TIMED_OUT),OAuth 登录页加载完全不受 App 代理配置保护;只有 token 交换(OkHttp)走应用代理。面向墙内用户的登录方案必须把系统代理写进前置条件,或做二维码等不依赖 TV 出站的替代路径
- **bgm 验证码是自动化天敌**:可疑 IP(代理出口)下几乎必弹验证码,自动化连错 4 次后停手(锁号风险);TV 端遥控器输验证码同样痛苦。验证码环节建议只做人走查,不进自动化
- **Composed-path divergence(沿用 v2.16 条目)**:本次同样先 unit-test 后真机,设备行为与单测一致,未复现发散
1 change: 1 addition & 0 deletions docs/agents/settings-web-control-parity-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Suggested scope for the subagent:
| Feature | TV settings | WebAPI | WebUI | Notes |
|---|---|---|---|---|
| Topping DAC 控制(toppingctl 协议) | ✅ AUDIO_DSP 区内 `ToppingDacControls` | ✅ `/api/topping/{status,volume,preset,flat,gain,power,preamp,usb-permission}` | ✅ 音频 DSP 视图 Topping DAC 卡片 | 音量仅 DX5 II(音量不在 HID 上的型号禁用输入);> −10 dB 需确认;未 confirmed 型号拒写 |
| Bangumi OAuth 直连登录(回环回调) | ✅ 元数据区登录按钮 + WebView 对话框 + 外部浏览器入口 | ➖ 刻意不同步(回环回调/鉴权全在设备本地;token 管理沿用已有 bangumi-token 端点) | ➖ 同左(手动贴 token 链路不变) | surface-specific:Web 侧无法完成 127.0.0.1 回调;有效期/状态仅 TV 展示 |

## Fast File Pointers
- TV settings UI: `ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ interface CloudDriveCredentialStore {

interface AppCredentialStore : CloudDriveCredentialStore {
var bangumiAccessToken: String?
var bangumiRefreshToken: String?
var bangumiTokenExpiresAtMillis: Long
var tmdbAccessToken: String?
var tmdbApiBaseUrlOverride: String?
var otlpAccessToken: String?
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package com.miruplay.tv.scraper.core

import com.miruplay.tv.core.common.AppError
import com.miruplay.tv.core.common.Result
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URLEncoder
import java.util.concurrent.TimeUnit

object BangumiOAuthConstants {
const val AUTHORIZE_URL = "https://bgm.tv/oauth/authorize"
const val TOKEN_URL = "https://bgm.tv/oauth/access_token"

const val CALLBACK_PORT = 13712
const val CALLBACK_PATH = "/callback"
const val CALLBACK_URL = "http://127.0.0.1:$CALLBACK_PORT$CALLBACK_PATH"

fun authorizeUrl(
clientId: String,
state: String,
callbackUrl: String = CALLBACK_URL,
): String =
"$AUTHORIZE_URL?client_id=${clientId.urlEncode()}" +
"&response_type=code" +
"&state=${state.urlEncode()}" +
"&redirect_uri=${callbackUrl.urlEncode()}"

private fun String.urlEncode(): String =
URLEncoder.encode(this, Charsets.UTF_8.name())
}

@Serializable
data class BangumiOAuthTokenResponse(
@SerialName("access_token") val accessToken: String = "",
@SerialName("expires_in") val expiresInSeconds: Long = 0L,
@SerialName("token_type") val tokenType: String = "",
@SerialName("refresh_token") val refreshToken: String = "",
@SerialName("user_id") val userId: Long = 0L,
)

data class BangumiOAuthTokens(
val accessToken: String,
val refreshToken: String,
/** Epoch millis at which the access token expires. */
val expiresAtMillis: Long,
val userId: Long = 0L,
)

interface BangumiOAuthClientApi {
val isConfigured: Boolean
val clientId: String
fun configureProxy(proxyConfig: BangumiHttpProxyConfig)
suspend fun exchangeCode(
code: String,
callbackUrl: String = BangumiOAuthConstants.CALLBACK_URL,
): Result<BangumiOAuthTokens>

suspend fun refresh(
refreshToken: String,
callbackUrl: String = BangumiOAuthConstants.CALLBACK_URL,
): Result<BangumiOAuthTokens>
}

/**
* Direct OAuth2 client for Bangumi (no third-party relay involved).
*
* Flow: open [BangumiOAuthConstants.authorizeUrl] in a browser/WebView, Bangumi
* redirects to the loopback [BangumiOAuthConstants.CALLBACK_URL] with
* `?code=..&state=..`, then [exchangeCode] swaps the code for tokens.
* Access tokens live 7 days (`expires_in` 604800); use [refresh] to rotate.
*/
class BangumiOAuthClient(
override val clientId: String,
private val clientSecret: String,
httpClient: OkHttpClient? = null,
private val tokenUrl: String = BangumiOAuthConstants.TOKEN_URL,
private val clockMillis: () -> Long = System::currentTimeMillis,
) : BangumiOAuthClientApi {
private val proxyClient = BangumiProxyAwareOkHttpClient(
httpClient ?: defaultClient(),
)
private val json = Json { ignoreUnknownKeys = true }

override val isConfigured: Boolean
get() = clientId.isNotBlank() && clientSecret.isNotBlank()

override fun configureProxy(proxyConfig: BangumiHttpProxyConfig) {
proxyClient.configureProxy(proxyConfig)
}

override suspend fun exchangeCode(
code: String,
callbackUrl: String,
): Result<BangumiOAuthTokens> = requestToken(
grantType = "authorization_code",
callbackUrl = callbackUrl,
) {
add("code", code)
}

override suspend fun refresh(
refreshToken: String,
callbackUrl: String,
): Result<BangumiOAuthTokens> = requestToken(
grantType = "refresh_token",
callbackUrl = callbackUrl,
) {
add("refresh_token", refreshToken)
}

private suspend fun requestToken(
grantType: String,
callbackUrl: String,
extra: FormBody.Builder.() -> Unit,
): Result<BangumiOAuthTokens> = withContext(Dispatchers.IO) {
try {
if (!isConfigured) {
return@withContext Result.failure(
AppError.ScrapingError.ApiError(SOURCE_NAME, "Bangumi OAuth 未配置 client_id/secret"),
)
}
val body = FormBody.Builder()
.add("grant_type", grantType)
.add("client_id", clientId)
.add("client_secret", clientSecret)
.add("redirect_uri", callbackUrl)
.apply(extra)
.build()
val request = Request.Builder()
.url(tokenUrl)
.post(body)
.addHeader("User-Agent", DEFAULT_USER_AGENT)
.addHeader("Accept", "application/json")
.build()
proxyClient.newCall(request).execute().use { response ->
val text = response.body?.string().orEmpty()
if (!response.isSuccessful) {
return@withContext Result.failure(
AppError.NetworkError.HttpError(response.code, text.ifBlank { response.message }),
)
}
val parsed = json.decodeFromString<BangumiOAuthTokenResponse>(text)
if (parsed.accessToken.isBlank()) {
return@withContext Result.failure(
AppError.ScrapingError.ApiError(SOURCE_NAME, "Bangumi 换 token 响应缺 access_token"),
)
}
Result.success(
BangumiOAuthTokens(
accessToken = parsed.accessToken,
refreshToken = parsed.refreshToken,
expiresAtMillis = clockMillis() + parsed.expiresInSeconds * 1000L,
userId = parsed.userId,
)
)
}
} catch (error: Exception) {
Result.failure(AppError.NetworkError.ServerUnreachable(tokenUrl))
}
}

companion object {
const val SOURCE_NAME = "Bangumi"
private const val DEFAULT_USER_AGENT = "ModerRAS/MiruPlay/0.1.0 (Android TV) (https://github.com/ModerRAS/MiruPlay)"

private fun defaultClient(): OkHttpClient =
OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
}
}
Loading
Loading