diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventions.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventions.kt index 6471db52..216d2596 100644 --- a/core/model/src/main/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventions.kt +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventions.kt @@ -280,7 +280,7 @@ fun settingsProxyPanelTitleLabel(): UiText = fun settingsProxyPanelDescription(): UiText = uiText( "settings_proxy_panel_desc", - "Bangumi API、Bangumi Archive 下载和 RSS 请求会共用这个 HTTP 代理。", + "Bangumi API、Bangumi Archive 下载、RSS 请求和 Bangumi 登录页会共用这个 HTTP 代理。", ) fun settingsProxyToggleLabel(enabled: Boolean): UiText = diff --git a/docs/agents/pre-pr-checklist.md b/docs/agents/pre-pr-checklist.md index 4dc7257d..88551d9e 100644 --- a/docs/agents/pre-pr-checklist.md +++ b/docs/agents/pre-pr-checklist.md @@ -130,6 +130,7 @@ Re-verify when: Room schema, DAOs, repositories, Bangumi/TMDB clients, NFO. - ✦ **Room migrations**: schema change ⇒ new migration + test; never bump version without one - ✦ **Repository contracts**: interface + `*Impl` pairs in sync; no DB access outside `data` - ✦ **Bangumi**: metadata fetch, episode comments, bangumi-archive sync routes +- ✦ **Bangumi OAuth 登录页代理**(TV 设置 → 元数据 → Bangumi 登录):配置「出站代理」后对话框显示「授权页通过代理 … 加载」且授权页能打开(真机 / System WebView 109 实测:配置可达的 HTTP 代理后完整加载 Bangumi 登录页;应用代理关且系统代理为空时为 `net::ERR_CONNECTION_CLOSED`、代理侧零流量);未配置时直连、无代理提示条;回环回调 `127.0.0.1`/`localhost` 不被代理;关闭对话框后进程内 WebView 代理已还原(再开别的 WebView 页面不受影响)。**A/B 前必须先清空系统全局代理并重启设备**,否则系统代理会掩盖应用代理缺失(见 §8 同题 failure class) - ✦ NFO read/write round-trip ### 5.7 Cloud sync & RSS (`sync-engine`, `cloud-drive*`) @@ -144,7 +145,7 @@ Re-verify when: any route, DTO, server, or WebUI change. **Follow `docs/agents/s - ✦ **Server boots** on 9978, `/api/info` responds; no route silently renamed/removed - ✦ **WebUI (Vue)**: forms, playback control, library work against the real device - ✦ **Settings parity** TV ↔ WebAPI ↔ WebUI, both directions -- ✦ `/api/proxy` still proxies media for WebUI playback +- ✦ `/api/proxy` 出站代理配置面不变(`GET/PUT` + `NetworkProxyDto` ↔ `rssProxy*`,TV/WebUI 共用);它是配置端点,不是媒体中继 ### 5.9 App maintenance (`app`, CI) Re-verify when: app-update flow, logging, CI workflows. @@ -264,10 +265,51 @@ Not device-verified (to be covered by follow-ups, reason recorded): New findings (section 1 candidates / product constraints): -- **WebView 不走应用代理,只认系统全局代理**:墙内网络下没有系统代理的盒子连授权页都打不开(ERR_CONNECTION_TIMED_OUT),OAuth 登录页加载完全不受 App 代理配置保护;只有 token 交换(OkHttp)走应用代理。面向墙内用户的登录方案必须把系统代理写进前置条件,或做二维码等不依赖 TV 出站的替代路径 +- **【v2.18 当时结论 · 2026-11 已修】WebView 不走应用代理,只认系统全局代理**:墙内网络下没有系统代理的盒子连授权页都打不开(ERR_CONNECTION_TIMED_OUT),OAuth 登录页加载完全不受 App 代理配置保护;当时只有 token 交换(OkHttp)走应用代理。当时的结论是「面向墙内用户的登录方案必须把系统代理写进前置条件,或做二维码等不依赖 TV 出站的替代路径」。**2026-11 已修**:登录对话框改用 androidx.webkit `ProxyController.setProxyOverride` 给进程内 WebView 装上同一份「出站代理」(回环回调 bypass 直连),见下文「Bangumi OAuth WebView 走应用出站代理(patch)」小节;原文保留,用于追溯当时为何不敢在 WebView 内登录 - **bgm 验证码是自动化天敌**:可疑 IP(代理出口)下几乎必弹验证码,自动化连错 4 次后停手(锁号风险);TV 端遥控器输验证码同样痛苦。验证码环节建议只做人走查,不进自动化 - **Composed-path divergence(沿用 v2.16 条目)**:本次同样先 unit-test 后真机,设备行为与单测一致,未复现发散 +### Bangumi OAuth WebView 走应用出站代理(patch) + +背景:v2.18 的 New findings 记过「WebView 不走应用代理,只认系统全局代理」——墙内盒子没有系统代理时连授权页都打不开。本次让 OAuth 登录对话框的内置 WebView 复用 App 自己的「出站代理」,登录页与 token 交换现在走同一条代理链路。 + +实现要点(`ui-tv/.../settings/BangumiOAuthWebViewProxy.kt`、`AddSourceScreen.kt` 的 `BangumiOAuthDialog`): + +- `androidx.webkit` 的 `ProxyController.setProxyOverride` 做进程级 WebView 代理 override;只有当 `WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)` 为 true 才安装,否则直连 + 对话框黄色提示(建议改用外部浏览器或升级 Android System WebView) +- 代理规则由 `BangumiHttpProxyConfig.toBangumiOAuthWebViewProxyRule()` 映射成 `http://host:port`,并 bypass `localhost` / `127.0.0.1`,保证回环回调 `http://127.0.0.1:13712/callback` 不被代理;代理关闭、host 空白、端口越界(1..65535 之外)→ 不产生规则 = 走直连(与旧版行为一致) +- 配置来源与 token 交换 / Bangumi 抓取 / Archive 下载 / RSS 完全同源:`CloudDriveAutomationConfig.toBangumiHttpProxyConfig()`(即设置里的 `rssProxy*` 字段);OAuth coordinator 在 `exchangeCode`/`refresh` 前也会 `oauthClient.configureProxy(proxyConfig())` +- 对话框销毁时 `clearProxyOverride` 还原直连;`apply` 生效回调里若对话框已释放(`released` 已置位)则执行 `clear` 而不是 `loadUrl`,覆盖「override 异步生效前对话框已关闭」的竞态(否则进程级 override 会残留到后续 WebView) +- 新增依赖 `androidx.webkit:webkit:1.14.0`(`gradle/libs.versions.toml` 的 `webkit` + `androidx-webkit` alias,`ui-tv` 实现依赖):该 AAR 元数据要求 `minCompileSdk=34`、`minAndroidGradlePluginVersion=8.1.1`;本仓库 `ui-tv` 是 compileSdk 35 / AGP 8.6.0,满足要求,不需要动 SDK 或插件版本(compileSdk 低于 34 或 AGP 低于 8.1.1 的模块会在依赖解析阶段直接失败) +- 新增 i18n:`settings_metadata_bangumi_oauth_proxy_active`(`%1$s` = `host:port`)/ `settings_metadata_bangumi_oauth_proxy_unsupported`,values / values-en / values-zh-rTW / values-zh-rHK 四地对齐 + +Own checks: + +- 单测 `BangumiOAuthWebViewProxyTest` 代理 rule 映射 7 例:代理关闭 → 无规则;host 空白(空串 / 纯空格)→ 无规则;端口 0 / 65536 → 无规则;启用 → `http://host:port` + `displayAddress` + bypass = `localhost`,`127.0.0.1`;host 首尾空白被 trim;边界端口 1 / 65535 接受 +- 代理关闭/未配置时零行为变化:`proxyRule == null` 时对话框直接 `loadUrl(authorizeUrl)`,不调 `setProxyOverride` / `clearProxyOverride`,也不显示代理提示条(推荐的对照基线:先关代理走一遍登录,再开代理走一遍;前提是系统全局代理已清空并重启设备,否则系统代理会掩盖应用代理缺失——见 New failure class) +- 不支持分支:`PROXY_OVERRIDE` 不支持的设备直连加载 + 黄色「当前系统 WebView 不支持应用内代理…」提示;`setProxyOverride` 抛 `UnsupportedOperationException` / `IllegalStateException` 时 `apply` 返回 false 但回调仍被调用一次(同步),不卡住页面加载 +- 销毁竞态:代理 override 生效回调晚于对话框销毁时,回调执行 `clear(mainExecutor)` 而不是 `loadUrl`;重开对话框应重新安装代理、关闭后进程内不残留(真机侧按「开代理登录 → 取消 → 再打开任意 WebView 页面」观察) +- [真机] Android 13 / SDK 33,System WebView 109.0.5414.123(被测 APK = 本次改动的本地 debug 构建,versionName 2.18.0 / versionCode 1,OAuth client id/secret 为本地占位值、真值只在 CI)——已验证: + - 干净基线(应用代理关):先 `settings delete global global_http_proxy_host global_http_proxy_port` 清掉系统代理并**重启设备**,再清空 WebView 数据 → 打开 Bangumi 登录对话框,WebView 显示「网页无法打开 / net::ERR_CONNECTION_CLOSED」,本地自建日志代理(18899)**零设备 CONNECT 记录** → 确为直连 + - 开应用代理(实验组):系统代理仍为空,应用出站代理设为一个局域网内可达的 HTTP 代理(`192.168.x.x:7890`)→ 对话框顶部出现绿色状态行「授权页通过代理 192.168.x.x:7890 加载。」,WebView 完整加载 Bangumi 登录页(「登录至 Bangumi / Email / 密码 / 立即注册」),截图存证;状态行出现即证明走的是 `apply` 分支(`PROXY_OVERRIDE` 受支持),而不是不支持分支 + - 路由证据:应用出站代理改设本地自建日志代理(`192.168.x.x:18899`),其日志记录到设备 IP 发起的 `CONNECT bgm.tv:443 HTTP/1.1` → override 确实作用于 WebView 进程流量,而不是系统代理的副作用 + - 验证入口:设置 → 元数据 → 使用 Bangumi 登录;验证脚本与截图仅本地留存(不入库) +- [真机] 未验证(不要当成已验证):真实 client id/secret 的完整 OAuth 授权回调(回环 `http://127.0.0.1:13712/callback`)+ code 换 token 闭环 —— 本地 debug 构建是占位 client id/secret,换 token 必然失败;该链路 v2.18 真机已验证且本次未改动,建议用 CI / 发版构建(真值)再走查一次 +- full `./gradlew assembleDebug test lint`(构建与测试全绿) + +Cross-checks(同一配置源被多处消费,改代理语义时都要过一遍): + +- 代理配置同源:TV「出站代理」保存(`SettingsViewModel.saveProxyConfig` → `CloudDriveAutomationConfig.rssProxy*`)后,WebView(本次)、token 交换(`BangumiOAuthCoordinator` → `oauthClient.configureProxy`)、Bangumi 抓取(`BangumiScraper.configureProxy`)、Archive 下载/调度(`bangumiArchiveStore.configureProxy`)、RSS 都读同一份配置——不同端不应出现两套代理状态 +- 手动贴 Token 链路原样保留:不经过 WebView / proxy override,coordinator 只读写同一套 SecurePreferences 键,语义不变 +- 既有 OAuth / 设置单测仍需绿:`BangumiOAuthClientTest`、`BangumiOAuthCoordinatorTest`、`SettingsViewModelTokenTest`(若构造器新增依赖需补 mock stub) +- WebAPI / WebUI 配置面不变:`GET/PUT /api/proxy`(`NetworkProxyDto` ↔ `rssProxy*`,WebUI 出站代理卡片)仍读写同一配置;OAuth 流程本身仍是 TV-only(surface-specific,见 parity 表),本次只同步「代理说明里包含 Bangumi 登录页」这层文案 +- 新增两个 string key 的 lint `MissingTranslation` 通过(四地 values 对齐);WebUI 说明文案改动只影响 WebUI + +New failure class (section 1 candidate): + +- **进程级全局副作用** —— `ProxyController.setProxyOverride` 影响整个进程的 WebView,而不是某个实例:忘记 clear、或 clear 与异步 apply 的先后顺序错了,会让之后所有 WebView 静默走代理(页面能打开但行为与用户预期不符,且没有日志)。检查:任何安装进程级设置的代码必须有唯一还原路径 + 「异步生效晚于释放」的竞态守卫;验证按「开 → 关 → 再开别的 WebView 页面」的顺序走,不能只看一次成功加载 + +- **系统全局代理掩盖应用代理缺失** —— 设备上只要有 `global_http_proxy_host/port`(真机实测原本配置了指向局域网内的 HTTP 代理),WebView 即使没装应用代理也能经系统代理加载授权页,「应用代理关闭」的对照组因此被误判成「直连可用 / 功能没坏」;更坑的是删掉 settings 后**已启动的应用进程可能仍沿用旧代理**,必须重启设备才拿到干净基线。检查:真机 A/B 前先 `settings get global global_http_proxy_host` / `global_http_proxy_port` 确认为 `null`(非空则 `settings delete global` 后重启),并在「系统代理为空 + 应用代理关」下同时确认对照组失败现象(如 `net::ERR_CONNECTION_CLOSED`)**与代理侧零流量**,基线才算成立 + ### RSS 扫描卡死修复:离线 archive 按查询全量解析 + URL 噪音系列名(patch) Own checks(HK1 真机证据 + 单测): diff --git a/docs/agents/settings-web-control-parity-checklist.md b/docs/agents/settings-web-control-parity-checklist.md index 899e9164..73f71bcc 100644 --- a/docs/agents/settings-web-control-parity-checklist.md +++ b/docs/agents/settings-web-control-parity-checklist.md @@ -63,6 +63,7 @@ Verify at least the smallest round-trip that proves parity: - If TV settings are affected, one app-side settings path too Prefer nearby existing tests when they exist. For UI-only copy/layout changes, a targeted manual verification is enough. +- 代理相关文案(TV 面板 / WebUI 卡片)属 copy-only:TV 视检 + WebUI 打开「代理配置」对照即可;OAuth 登录页的 WebView 代理是 TV 运行时能力,按 `pre-pr-checklist.md` 的「Bangumi OAuth WebView 走应用出站代理(patch)」小节真机验证 ### 6. Subagent follow-through After the main settings/menu change is done, a focused subagent may be used to audit parity gaps: @@ -80,7 +81,8 @@ 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 展示 | +| 出站代理(Bangumi API / Archive / RSS / OAuth 登录页) | ✅ 设置 →「出站代理」面板(`settings_proxy_panel_desc` 已含「Bangumi 登录页」,字段 `rssProxy*`);OAuth 对话框运行时把同一配置装到内置 WebView(`BangumiOAuthWebViewProxy`,进程级 override) | ✅ `GET/PUT /api/proxy`(`NetworkProxyDto` ↔ `CloudDriveAutomationConfig.rssProxy*`) | ✅「代理配置」视图的出站代理卡片(说明文案已含「Bangumi 登录页」) | 配置面三端同源;WebView 代理是设备进程级能力,Web 端只读写配置、不参与 apply | +| Bangumi OAuth 直连登录(回环回调 + WebView 代理) | ✅ 元数据区登录按钮 + WebView 对话框(配了出站代理则走应用代理,未配则直连)+ 外部浏览器入口 | ➖ 刻意不同步(回环回调/鉴权全在设备本地;token 管理沿用已有 bangumi-token 端点) | ➖ 同左(手动贴 token 链路不变;代理说明文案已同步「Bangumi 登录页」) | surface-specific:Web 侧无法完成 127.0.0.1 回调,也无法安装 WebView 代理;有效期/状态/代理提示仅 TV 展示 | ## Fast File Pointers - TV settings UI: `ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/` diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a6df1aeb..46e5f3d5 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -21,6 +21,7 @@ coroutines = "1.7.3" lifecycle = "2.7.0" activity-compose = "1.8.2" androidx-core = "1.12.0" +webkit = "1.14.0" navigation-compose = "2.7.7" work = "2.11.2" grpc = "1.81.0" @@ -99,6 +100,9 @@ androidx-core = { group = "androidx.core", name = "core", version.ref = "android # === Navigation Compose === androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigation-compose" } +# === WebView === +androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" } + # === Testing === junit = { group = "junit", name = "junit", version = "4.13.2" } androidx-test-core = { group = "androidx.test", name = "core", version = "1.5.0" } diff --git a/ui-tv/build.gradle.kts b/ui-tv/build.gradle.kts index cdb52eaa..b9762be3 100644 --- a/ui-tv/build.gradle.kts +++ b/ui-tv/build.gradle.kts @@ -55,6 +55,7 @@ dependencies { implementation(libs.androidx.activity.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.navigation.compose) + implementation(libs.androidx.webkit) implementation(libs.zxing.core) implementation(libs.dagger.hilt.android) diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/AddSourceScreen.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/AddSourceScreen.kt index 9780e9b7..fb54ff15 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/AddSourceScreen.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/AddSourceScreen.kt @@ -113,7 +113,9 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.viewinterop.AndroidView +import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig import com.miruplay.tv.scraper.core.BangumiOAuthConstants +import com.miruplay.tv.scraper.core.toBangumiHttpProxyConfig import com.miruplay.tv.sync.BangumiOAuthState import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -386,6 +388,7 @@ import kotlinx.coroutines.delay import java.text.SimpleDateFormat import java.util.Date import java.util.Locale +import java.util.concurrent.atomic.AtomicBoolean private const val DEFAULT_LOCAL_PATH = "/storage/emulated/0/Download" private const val QR_CODE_MATRIX_SIZE = 96 @@ -468,6 +471,7 @@ fun AddSourceScreen( val webControlEnabled by viewModel.webControlEnabled.collectAsStateWithLifecycle() val webControlAccessToken by viewModel.webControlAccessToken.collectAsStateWithLifecycle() val cloudDriveConfig by viewModel.cloudDriveConfig.collectAsStateWithLifecycle() + val bangumiOAuthProxy = remember(cloudDriveConfig) { cloudDriveConfig.toBangumiHttpProxyConfig() } val rssSubscriptions by viewModel.rssSubscriptions.collectAsStateWithLifecycle() val cloudDriveTokenConfigured by viewModel.cloudDriveTokenConfigured.collectAsStateWithLifecycle() val cloudDrivePasswordConfigured by viewModel.cloudDrivePasswordConfigured.collectAsStateWithLifecycle() @@ -828,6 +832,7 @@ fun AddSourceScreen( }, oauthState = bangumiOAuthState, tokenExpiryMs = bangumiTokenExpiryMs, + bangumiOAuthProxy = bangumiOAuthProxy, onStartOAuth = viewModel::startBangumiOAuth, onCancelOAuth = viewModel::cancelBangumiOAuth, onOAuthCallback = viewModel::submitBangumiOAuthCallback, @@ -1330,6 +1335,7 @@ private fun SettingsContent( onClearToken: () -> Unit, oauthState: BangumiOAuthState, tokenExpiryMs: Long, + bangumiOAuthProxy: BangumiHttpProxyConfig, onStartOAuth: () -> String?, onCancelOAuth: () -> Unit, onOAuthCallback: (String) -> Unit, @@ -1667,6 +1673,7 @@ private fun SettingsContent( onClearToken = onClearToken, oauthState = oauthState, tokenExpiryMs = tokenExpiryMs, + bangumiOAuthProxy = bangumiOAuthProxy, onStartOAuth = onStartOAuth, onCancelOAuth = onCancelOAuth, onOAuthCallback = onOAuthCallback, @@ -4651,6 +4658,7 @@ private fun BangumiOAuthSection( hasToken: Boolean, tokenExpiryMs: Long, oauthState: BangumiOAuthState, + proxyConfig: BangumiHttpProxyConfig, onStartOAuth: () -> String?, onCancelOAuth: () -> Unit, onOAuthCallback: (String) -> Unit, @@ -4707,6 +4715,7 @@ private fun BangumiOAuthSection( if (url != null) { BangumiOAuthDialog( authorizeUrl = url, + proxyConfig = proxyConfig, onExternalBrowser = { runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) @@ -4724,10 +4733,23 @@ private fun BangumiOAuthSection( @Composable private fun BangumiOAuthDialog( authorizeUrl: String, + proxyConfig: BangumiHttpProxyConfig, onExternalBrowser: () -> Unit, onCallback: (String) -> Unit, onDismiss: () -> Unit, ) { + val context = LocalContext.current + val mainExecutor = remember(context) { ContextCompat.getMainExecutor(context) } + val proxyRule = remember(proxyConfig) { proxyConfig.toBangumiOAuthWebViewProxyRule() } + val proxySupported = remember { BangumiOAuthWebViewProxy.isSupported() } + val released = remember { AtomicBoolean(false) } + DisposableEffect(Unit) { + onDispose { + if (proxyRule != null && proxySupported) { + BangumiOAuthWebViewProxy.clear(mainExecutor) + } + } + } var webViewRef by remember { mutableStateOf(null) } BackHandler { val webView = webViewRef @@ -4752,6 +4774,24 @@ private fun BangumiOAuthDialog( style = TvTypography.subtitle, color = TextPrimary, ) + if (proxyRule != null) { + if (proxySupported) { + StatusMessage( + icon = Icons.Filled.CheckCircle, + text = stringResource( + R.string.settings_metadata_bangumi_oauth_proxy_active, + proxyRule.displayAddress, + ), + color = ProgressGreen, + ) + } else { + StatusMessage( + icon = Icons.Filled.Warning, + text = stringResource(R.string.settings_metadata_bangumi_oauth_proxy_unsupported), + color = WarningYellow, + ) + } + } AndroidView( factory = { context -> WebView(context).apply { @@ -4770,7 +4810,18 @@ private fun BangumiOAuthDialog( } } } - loadUrl(authorizeUrl) + val rule = proxyRule + if (rule == null || !proxySupported) { + loadUrl(authorizeUrl) + } else { + BangumiOAuthWebViewProxy.apply(rule, mainExecutor) { + if (released.get()) { + BangumiOAuthWebViewProxy.clear(mainExecutor) + } else { + runCatching { loadUrl(authorizeUrl) } + } + } + } } }, update = { webViewRef = it }, @@ -4779,6 +4830,7 @@ private fun BangumiOAuthDialog( .height(520.dp) .clip(RoundedCornerShape(8.dp)), onRelease = { webView -> + released.set(true) webView.stopLoading() webView.destroy() }, @@ -4809,6 +4861,7 @@ private fun MetadataPanel( onClearToken: () -> Unit, oauthState: BangumiOAuthState, tokenExpiryMs: Long, + bangumiOAuthProxy: BangumiHttpProxyConfig, onStartOAuth: () -> String?, onCancelOAuth: () -> Unit, onOAuthCallback: (String) -> Unit, @@ -4880,6 +4933,7 @@ private fun MetadataPanel( hasToken = hasToken, tokenExpiryMs = tokenExpiryMs, oauthState = oauthState, + proxyConfig = bangumiOAuthProxy, onStartOAuth = onStartOAuth, onCancelOAuth = onCancelOAuth, onOAuthCallback = onOAuthCallback, diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxy.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxy.kt new file mode 100644 index 00000000..0d8a4670 --- /dev/null +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxy.kt @@ -0,0 +1,83 @@ +package com.miruplay.tv.ui.settings + +import androidx.webkit.ProxyConfig +import androidx.webkit.ProxyController +import androidx.webkit.WebViewFeature +import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig +import java.util.concurrent.Executor + +/** + * Proxy rule that can be applied to the Bangumi OAuth login WebView. + * + * [proxyRule] is the value accepted by [ProxyConfig.Builder.addProxyRule], while [displayAddress] is + * the human readable `host:port` form used in status text and logs. + */ +internal data class BangumiOAuthWebViewProxyRule( + val proxyRule: String, + val bypassRules: List, + val displayAddress: String, +) + +/** + * Maps the app wide outbound proxy configuration onto a WebView proxy rule. + * + * Returns null when the proxy is disabled, the host is blank, or the port is out of range: the OAuth + * login WebView then keeps using the direct connection. + */ +internal fun BangumiHttpProxyConfig.toBangumiOAuthWebViewProxyRule(): BangumiOAuthWebViewProxyRule? { + if (!enabled) return null + val normalizedHost = host.trim() + if (normalizedHost.isEmpty()) return null + if (port !in 1..65_535) return null + return BangumiOAuthWebViewProxyRule( + proxyRule = "http://$normalizedHost:$port", + bypassRules = WEBVIEW_PROXY_BYPASS_RULES, + displayAddress = "$normalizedHost:$port", + ) +} + +// Keep the OAuth loopback callback on the direct connection so the redirect is never proxied. +private val WEBVIEW_PROXY_BYPASS_RULES: List = listOf("localhost", "127.0.0.1") + +/** + * Thin wrapper around the androidx.webkit proxy override APIs used by the Bangumi OAuth WebView. + * + * Every platform call is defensive: WebView provider behavior varies across Android TV devices and + * the OAuth dialog must still load (over the direct connection) when the proxy cannot be applied. + */ +internal object BangumiOAuthWebViewProxy { + fun isSupported(): Boolean = + runCatching { WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE) } + .getOrDefault(false) + + /** + * Applies [rule] to the WebViews of this process. + * + * [onApplied] is invoked exactly once: asynchronously by the WebView when the override took + * effect, or synchronously from here when the platform rejected it. Callers use it to continue + * loading the authorization URL. Returns true when the override request was accepted. + */ + fun apply(rule: BangumiOAuthWebViewProxyRule, executor: Executor, onApplied: () -> Unit): Boolean { + return try { + val builder = ProxyConfig.Builder().addProxyRule(rule.proxyRule) + rule.bypassRules.forEach { bypassRule -> builder.addBypassRule(bypassRule) } + ProxyController.getInstance().setProxyOverride( + builder.build(), + executor, + Runnable { onApplied() }, + ) + true + } catch (exception: Exception) { + // Unsupported WebView providers throw UnsupportedOperationException / IllegalStateException. + onApplied() + false + } + } + + /** Clears any proxy override installed by [apply] and restores the direct connection. */ + fun clear(executor: Executor) { + runCatching { + ProxyController.getInstance().clearProxyOverride(executor, Runnable {}) + } + } +} diff --git a/ui-tv/src/main/res/values-en/strings.xml b/ui-tv/src/main/res/values-en/strings.xml index 7ee8205e..9aef00db 100644 --- a/ui-tv/src/main/res/values-en/strings.xml +++ b/ui-tv/src/main/res/values-en/strings.xml @@ -156,7 +156,7 @@ Save settings Upload now Outbound proxy - Bangumi API, Bangumi Archive downloads and RSS requests share this HTTP proxy. + Bangumi API, Bangumi Archive downloads, RSS requests and the Bangumi sign-in page share this HTTP proxy. Proxy enabled Proxy off Proxy host @@ -240,6 +240,8 @@ Cancel Sign out Valid until %1$s + The authorization page loads through proxy %1$s. + The current system WebView does not support in-app proxies, so the authorization page will load directly. If it fails to open, use an external browser or update Android System WebView. Bangumi token saved. Bangumi access token is empty; not saved. Bangumi access token cleared. diff --git a/ui-tv/src/main/res/values-zh-rHK/strings.xml b/ui-tv/src/main/res/values-zh-rHK/strings.xml index f145724a..de8daaee 100644 --- a/ui-tv/src/main/res/values-zh-rHK/strings.xml +++ b/ui-tv/src/main/res/values-zh-rHK/strings.xml @@ -701,6 +701,8 @@ 取消 登出 有效期限至 %1$s + 授權頁透過代理 %1$s 載入。 + 目前系統 WebView 不支援應用內代理,授權頁將直連載入;如無法開啟請改用外部瀏覽器或更新 Android System WebView。 批量匹配會跳過已有衝突後設資料。 支援單條應用、批量預覽、應用和撤銷。 Bangumi 搜尋、批量預覽、應用和撤銷保留在詳情頁。 @@ -723,7 +725,7 @@ 目前未啟用代理。 代理已啟用,請填寫代理位址。 代理位址 - Bangumi API、Bangumi Archive 下載和 RSS 請求會共用這個 HTTP 代理。 + Bangumi API、Bangumi Archive 下載、RSS 請求和 Bangumi 登入頁會共用這個 HTTP 代理。 出站代理 代理埠 儲存代理 diff --git a/ui-tv/src/main/res/values-zh-rTW/strings.xml b/ui-tv/src/main/res/values-zh-rTW/strings.xml index 54c6e1c8..c55f09a3 100644 --- a/ui-tv/src/main/res/values-zh-rTW/strings.xml +++ b/ui-tv/src/main/res/values-zh-rTW/strings.xml @@ -156,7 +156,7 @@ 儲存設定 立即上報 出站代理 - Bangumi API、Bangumi Archive 下載和 RSS 請求會共用這個 HTTP 代理。 + Bangumi API、Bangumi Archive 下載、RSS 請求和 Bangumi 登入頁會共用這個 HTTP 代理。 代理已啟用 代理關閉 代理位址 @@ -240,6 +240,8 @@ 取消 登出 有效期限至 %1$s + 授權頁透過代理 %1$s 載入。 + 目前系統 WebView 不支援應用內代理,授權頁將直連載入;如無法開啟請改用外部瀏覽器或更新 Android System WebView。 Bangumi Token 已儲存。 Bangumi Access Token 為空,未儲存。 Bangumi Access Token 已清除。 diff --git a/ui-tv/src/main/res/values/strings.xml b/ui-tv/src/main/res/values/strings.xml index 44c892ce..23afadd9 100644 --- a/ui-tv/src/main/res/values/strings.xml +++ b/ui-tv/src/main/res/values/strings.xml @@ -650,6 +650,8 @@ 取消 退出登录 有效期至 %1$s + 授权页通过代理 %1$s 加载。 + 当前系统 WebView 不支持应用内代理,授权页将直连加载;如打不开请改用外部浏览器或升级 Android System WebView。 批量匹配会跳过已有冲突元数据。 支持单条应用、批量预览、应用和撤销。 Bangumi 搜索、批量预览、应用和撤销保留在详情页。 @@ -672,7 +674,7 @@ 当前未启用代理。 代理已启用,请填写代理地址。 代理地址 - Bangumi API、Bangumi Archive 下载和 RSS 请求会共用这个 HTTP 代理。 + Bangumi API、Bangumi Archive 下载、RSS 请求和 Bangumi 登录页会共用这个 HTTP 代理。 出站代理 代理端口 保存代理 diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxyTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxyTest.kt new file mode 100644 index 00000000..03d44a1e --- /dev/null +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/BangumiOAuthWebViewProxyTest.kt @@ -0,0 +1,71 @@ +package com.miruplay.tv.ui.settings + +import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test + +class BangumiOAuthWebViewProxyTest { + @Test + fun `disabled config maps to no webview proxy rule`() { + val config = BangumiHttpProxyConfig(enabled = false, host = "10.0.0.2", port = 7890) + + assertNull(config.toBangumiOAuthWebViewProxyRule()) + } + + @Test + fun `blank host maps to no webview proxy rule`() { + val emptyHost = BangumiHttpProxyConfig(enabled = true, host = "", port = 7890) + val whitespaceHost = BangumiHttpProxyConfig(enabled = true, host = " ", port = 7890) + + assertNull(emptyHost.toBangumiOAuthWebViewProxyRule()) + assertNull(whitespaceHost.toBangumiOAuthWebViewProxyRule()) + } + + @Test + fun `port below valid range maps to no webview proxy rule`() { + val config = BangumiHttpProxyConfig(enabled = true, host = "10.0.0.2", port = 0) + + assertNull(config.toBangumiOAuthWebViewProxyRule()) + } + + @Test + fun `port above valid range maps to no webview proxy rule`() { + val config = BangumiHttpProxyConfig(enabled = true, host = "10.0.0.2", port = 65_536) + + assertNull(config.toBangumiOAuthWebViewProxyRule()) + } + + @Test + fun `enabled config maps to http proxy rule with loopback bypass`() { + val config = BangumiHttpProxyConfig(enabled = true, host = "10.0.0.2", port = 7890) + + val rule = config.toBangumiOAuthWebViewProxyRule() + + assertNotNull(rule) + assertEquals("http://10.0.0.2:7890", rule?.proxyRule) + assertEquals("10.0.0.2:7890", rule?.displayAddress) + assertEquals(listOf("localhost", "127.0.0.1"), rule?.bypassRules) + } + + @Test + fun `host surrounding whitespace is trimmed`() { + val config = BangumiHttpProxyConfig(enabled = true, host = " 192.168.1.10 ", port = 8080) + + val rule = config.toBangumiOAuthWebViewProxyRule() + + assertNotNull(rule) + assertEquals("http://192.168.1.10:8080", rule?.proxyRule) + assertEquals("192.168.1.10:8080", rule?.displayAddress) + } + + @Test + fun `boundary ports are accepted`() { + val minPort = BangumiHttpProxyConfig(enabled = true, host = "10.0.0.2", port = 1) + val maxPort = BangumiHttpProxyConfig(enabled = true, host = "10.0.0.2", port = 65_535) + + assertEquals("http://10.0.0.2:1", minPort.toBangumiOAuthWebViewProxyRule()?.proxyRule) + assertEquals("http://10.0.0.2:65535", maxPort.toBangumiOAuthWebViewProxyRule()?.proxyRule) + } +} diff --git a/web-control/frontend/src/App.vue b/web-control/frontend/src/App.vue index a957838d..a7b0e494 100644 --- a/web-control/frontend/src/App.vue +++ b/web-control/frontend/src/App.vue @@ -497,7 +497,7 @@ active-text="代理已启用" inactive-text="代理关闭" /> - Bangumi API、Archive 下载和 RSS 请求共用此 HTTP 代理。 + Bangumi API、Archive 下载、RSS 请求和 Bangumi 登录页共用此 HTTP 代理。
@@ -2330,7 +2330,7 @@ const viewMeta = computed(() => ({ library: ['片库', '浏览番剧、选择剧集并投到电视端播放。'], sources: ['媒体源', '用电脑或手机键盘添加、编辑和扫描媒体源。'], automation: ['自动化', '管理 RSS 订阅、CloudDrive2 离线下载和整理入库。'], - proxy: ['代理配置', '设置 Bangumi、Archive 下载和 RSS 请求共用的出站 HTTP 代理。'], + proxy: ['代理配置', '设置 Bangumi、Archive 下载、RSS 请求和 Bangumi 登录页共用的出站 HTTP 代理。'], metadata: ['元数据', '配置 Bangumi/TMDB Token,让收藏和观看进度同步不必在电视上输入。'], scan: ['扫描设置', '自动扫描、入库归并、海报墙排列与应用内容模式。'], playback: ['播放设置', '默认播放结束动作与色调映射后端。'],