From 83567230dcd46ae061e05aeaf06b095a76b77a68 Mon Sep 17 00:00:00 2001 From: ModerRAS Date: Fri, 20 Nov 2026 02:23:53 +0800 Subject: [PATCH] =?UTF-8?q?feat(tv):=20=E6=8E=A5=E5=85=A5=E6=96=B0?= =?UTF-8?q?=E7=95=AA=E6=97=B6=E9=97=B4=E8=A1=A8=EF=BC=88=E5=8F=AF=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=95=B0=E6=8D=AE=E6=BA=90=20+=20=E5=91=A8=E8=A1=A8?= =?UTF-8?q?=20+=20=E8=AE=BE=E7=BD=AE=E4=B8=89=E7=AB=AF=E4=B8=80=E8=87=B4?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 时间表数据层:AirRadar 兼容客户端(10s 超时、内存/磁盘缓存 TTL 1h、失败回退旧缓存、404 空态),模型/URL 校验/时区换算放 core:model - 设置:新增「新番时间表」分组与数据源地址(本地 SharedPreferences、http/https 校验、旧数据兼容),媒体库顶栏新增「时间表」入口 - UI:新增 ScheduleScreen(周一..周日分组、组内本地时间升序、JST→设备时区跨日换算、匹配 Bangumi id 可进详情、loading/error/empty/未配置四态、TV 焦点/返回) - WebAPI/WebUI 三端一致:GET/PUT /api/settings/schedule + WebUI「新番时间表」视图 - 测试:JSON/时区/缓存/URL/匹配/设置/路由单测;版本 2.19.0(minor:用户可见新功能) --- app/build.gradle.kts | 2 +- .../kotlin/com/miruplay/tv/MainActivity.kt | 22 + .../com/miruplay/tv/navigation/NavRoutes.kt | 1 + .../tv/model/ScheduleDataSourceUrl.kt | 38 ++ .../com/miruplay/tv/model/ScheduleModels.kt | 158 +++++ .../tv/model/ScheduleTimeConversion.kt | 198 ++++++ .../tv/model/ScheduleUiConventions.kt | 238 +++++++ .../SettingsSectionDisplayConventions.kt | 7 + .../tv/model/ScheduleDataSourceUrlTest.kt | 57 ++ .../tv/model/ScheduleSnapshotParsingTest.kt | 139 +++++ .../tv/model/ScheduleTimeConversionTest.kt | 183 ++++++ .../SettingsSectionDisplayConventionsTest.kt | 6 +- .../data/schedule/AirRadarScheduleClient.kt | 85 +++ .../schedule/ScheduleDataSourcePreferences.kt | 46 ++ .../tv/data/schedule/ScheduleRepository.kt | 190 ++++++ .../schedule/AirRadarScheduleClientTest.kt | 114 ++++ .../ScheduleDataSourcePreferencesTest.kt | 65 ++ .../data/schedule/ScheduleRepositoryTest.kt | 212 +++++++ docs/agents/pre-pr-checklist.md | 30 + .../settings-web-control-parity-checklist.md | 1 + .../miruplay/tv/ui/common/UiTextResolver.kt | 61 ++ .../miruplay/tv/ui/library/LibraryScreen.kt | 16 +- .../miruplay/tv/ui/schedule/ScheduleScreen.kt | 586 ++++++++++++++++++ .../tv/ui/schedule/ScheduleViewModel.kt | 168 +++++ .../tv/ui/settings/AddSourceScreen.kt | 114 ++++ .../tv/ui/settings/SettingsViewModel.kt | 34 + ui-tv/src/main/res/values-en-rGB/strings.xml | 61 ++ ui-tv/src/main/res/values-en/strings.xml | 61 ++ ui-tv/src/main/res/values-zh-rHK/strings.xml | 61 ++ ui-tv/src/main/res/values-zh-rTW/strings.xml | 61 ++ ui-tv/src/main/res/values/strings.xml | 61 ++ .../ui/settings/SettingsViewModelTokenTest.kt | 5 + .../tv/webcontrol/NanoHttpWebControlServer.kt | 7 + .../webcontrol/WebControlEndpointService.kt | 2 + .../tv/webcontrol/WebControlModels.kt | 11 + .../WebControlScheduleSettingsRouteTest.kt | 184 ++++++ web-control/build.gradle.kts | 1 + web-control/frontend/src/App.vue | 130 +++- .../frontend/src/components/NavMenu.vue | 1 + .../tv/webcontrol/WebControlService.kt | 24 + 40 files changed, 3436 insertions(+), 5 deletions(-) create mode 100644 core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrl.kt create mode 100644 core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleModels.kt create mode 100644 core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleTimeConversion.kt create mode 100644 core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleUiConventions.kt create mode 100644 core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrlTest.kt create mode 100644 core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleSnapshotParsingTest.kt create mode 100644 core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleTimeConversionTest.kt create mode 100644 data/src/main/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClient.kt create mode 100644 data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferences.kt create mode 100644 data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleRepository.kt create mode 100644 data/src/test/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClientTest.kt create mode 100644 data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferencesTest.kt create mode 100644 data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleRepositoryTest.kt create mode 100644 ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleScreen.kt create mode 100644 ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleViewModel.kt create mode 100644 web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlScheduleSettingsRouteTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 0424db27..b548abde 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -9,7 +9,7 @@ plugins { // 支持通过 -PVERSION_NAME / -PVERSION_CODE 显式传入版本信息。 // 未显式传入 VERSION_NAME 时,默认把最后一段 patch 替换为 BUILD_NUMBER。 -val baseAppVersionName = "2.18.0" +val baseAppVersionName = "2.19.0" fun String?.nonBlankOrNull(): String? = this?.trim()?.takeIf { it.isNotBlank() } diff --git a/app/src/main/kotlin/com/miruplay/tv/MainActivity.kt b/app/src/main/kotlin/com/miruplay/tv/MainActivity.kt index e1761045..d4bfbe73 100644 --- a/app/src/main/kotlin/com/miruplay/tv/MainActivity.kt +++ b/app/src/main/kotlin/com/miruplay/tv/MainActivity.kt @@ -64,6 +64,7 @@ import com.miruplay.tv.ui.music.MusicPlayerPlaceholder import com.miruplay.tv.ui.music.MusicPlayerScreen import com.miruplay.tv.ui.mode.DramaLibraryScreen import com.miruplay.tv.ui.player.PlayerScreen +import com.miruplay.tv.ui.schedule.ScheduleScreen import com.miruplay.tv.ui.settings.AddSourceScreen import com.miruplay.tv.ui.theme.MiruPlayTheme import com.miruplay.tv.webcontrol.WebControlNavigator @@ -1187,6 +1188,7 @@ private fun MiruPlayNavigation( composable(NavRoutes.LIBRARY) { LibraryScreen( onNavigateToSettings = { navController.navigate(NavRoutes.SETTINGS) }, + onNavigateToSchedule = { navController.navigate(NavRoutes.SCHEDULE) }, onNavigateToDetail = { animeId -> runCatching { navController.navigate(NavRoutes.animeDetail(animeId)) @@ -1292,6 +1294,26 @@ private fun MiruPlayNavigation( onNavigateBack = { navController.popBackStack() }, onRestartApp = { (navController.context as? MainActivity)?.requestAppShutdown(restart = true) }, onExitApp = { (navController.context as? MainActivity)?.requestAppShutdown(restart = false) }, + onNavigateToSchedule = { navController.navigate(NavRoutes.SCHEDULE) }, + ) + } + + composable(NavRoutes.SCHEDULE) { + ScheduleScreen( + onNavigateBack = { navController.popBackStack() }, + onNavigateToDetail = { animeId -> + runCatching { + navController.navigate(NavRoutes.animeDetail(animeId)) + }.onFailure { error -> + MiruLog.e( + "MiruPlayNavigation", + "Failed to open anime detail from schedule", + error, + mapOf("anime_id" to animeId) + ) + } + }, + onNavigateToSettings = { navController.navigate(NavRoutes.SETTINGS) }, ) } diff --git a/app/src/main/kotlin/com/miruplay/tv/navigation/NavRoutes.kt b/app/src/main/kotlin/com/miruplay/tv/navigation/NavRoutes.kt index 5b0c264d..3f4ce339 100644 --- a/app/src/main/kotlin/com/miruplay/tv/navigation/NavRoutes.kt +++ b/app/src/main/kotlin/com/miruplay/tv/navigation/NavRoutes.kt @@ -17,6 +17,7 @@ object NavRoutes { const val MUSIC_DETAIL = "music/{albumId}" const val MUSIC_PLAYER = "music-player/{trackId}" const val SETTINGS = MiruPlayRouteSurface.SETTINGS_ROUTE + const val SCHEDULE = "schedule" const val ANIME_DETAIL = "${MiruPlayRouteSurface.ANIME_ROUTE_PREFIX}/{animeId}" const val PLAYER = "${MiruPlayRouteSurface.PLAYER_ROUTE_PREFIX}/{uri}" const val PLAYER_WITH_OPTIONS = "$PLAYER?mediaSourceId={mediaSourceId}&startPosition={startPosition}&episodeId={episodeId}&progressId={progressId}" diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrl.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrl.kt new file mode 100644 index 00000000..33771009 --- /dev/null +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrl.kt @@ -0,0 +1,38 @@ +package com.miruplay.tv.model + +import java.net.URI + +/** + * 时间表数据源地址的校验与归一化。 + * + * 该地址由用户在运行时填写,仓库里不保存任何默认值/真实域名。规则: + * - 只接受 http / https; + * - 必须有 host,不能带空白字符; + * - 不接受 query / fragment(它是 base URL,客户端再拼 `/api/schedule/latest`); + * - 去掉末尾的 `/`,避免拼出双斜杠。 + */ +object ScheduleDataSourceUrl { + + fun normalize(raw: String?): String? { + val trimmed = raw?.trim().orEmpty() + if (trimmed.isEmpty()) return null + if (trimmed.any { it.isWhitespace() }) return null + + val uri = runCatching { URI(trimmed) }.getOrNull() ?: return null + val scheme = uri.scheme?.lowercase() ?: return null + if (scheme != "http" && scheme != "https") return null + if (uri.host.isNullOrBlank()) return null + if (uri.rawUserInfo != null) return null + if (uri.port != -1 && uri.port !in 1..65_535) return null + if (uri.rawQuery != null || uri.rawFragment != null) return null + + val normalized = trimmed.trimEnd('/') + return normalized.takeIf { it.isNotEmpty() } + } + + fun isValid(raw: String?): Boolean = normalize(raw) != null + + /** 拼接最新的时间表接口地址;[baseUrl] 必须是已归一化的地址。 */ + fun latestScheduleEndpoint(baseUrl: String): String = + "${baseUrl.trimEnd('/')}/api/schedule/latest" +} diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleModels.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleModels.kt new file mode 100644 index 00000000..dfcf6f74 --- /dev/null +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleModels.kt @@ -0,0 +1,158 @@ +package com.miruplay.tv.model + +import kotlinx.serialization.Serializable + +/** + * 新番时间表(AirRadar)API 的线格式。 + * + * 数据源地址只存在于用户运行时配置里,仓库不保存任何默认地址;客户端在用户配置的 + * base URL 上拼接 `/api/schedule/latest`。所有字段都给默认值,服务端新增字段不会 + * 让旧客户端解析失败(客户端同时开启 ignoreUnknownKeys)。 + */ +@Serializable +data class ScheduleSnapshot( + val schemaVersion: Int = 1, + val generatedAt: String? = null, + val season: String? = null, + val seasonStart: String? = null, + val seasonEnd: String? = null, + val timezone: String? = null, + val itemCount: Int = 0, + val items: List = emptyList(), +) + +@Serializable +data class ScheduleItem( + val subjectId: Int = 0, + val name: String = "", + val nameCn: String? = null, + val airDate: String? = null, + val image: String? = null, + /** JST 周几:1=周一 … 7=周日。 */ + val weekday: Int = 0, + /** JST 时刻,HH:mm。 */ + val time: String = "", + val timezone: String? = null, + val confidence: String? = null, + val sources: List = emptyList(), + val updatedAt: String? = null, +) { + /** 优先中文名,缺失时回退日文原名。 */ + val displayName: String + get() = nameCn?.trim()?.takeIf { it.isNotEmpty() } ?: name.trim() +} + +@Serializable +data class ScheduleSource( + val url: String = "", + val domain: String = "", + val provider: String = "", +) + +/** 时间表请求失败原因;UI 按类型给可重试文案。 */ +sealed interface ScheduleFetchError { + data object InvalidUrl : ScheduleFetchError + data object Network : ScheduleFetchError + data object Timeout : ScheduleFetchError + data class Http(val code: Int) : ScheduleFetchError + data object InvalidData : ScheduleFetchError +} + +enum class ScheduleConfidence { + HIGH, + MEDIUM, + LOW, + UNKNOWN; + + companion object { + fun fromWire(raw: String?): ScheduleConfidence = + when (raw?.trim()?.lowercase()) { + "high" -> HIGH + "medium" -> MEDIUM + "low" -> LOW + else -> UNKNOWN + } + } +} + +/** + * 一行已换算到设备本地时区的播出信息。 + * + * [localWeekday] / [localMinutes] 是设备时区里的周几与分钟数;[crossDayOffset] 是本地 + * 日期相对 JST 播出日期的天数差(0 同日,+1 跨到次日,-1 跨到前一日),用于 UI 标注。 + */ +data class ScheduleAiring( + val subjectId: Int, + val displayName: String, + val originalName: String, + val imageUrl: String?, + val confidence: ScheduleConfidence, + val sourceCount: Int, + val airDate: String?, + val jstWeekday: Int, + val jstTimeLabel: String, + val localWeekday: Int, + val localMinutes: Int, + val localTimeLabel: String, + val crossDayOffset: Int, +) { + /** 本地时间升序排序键:周几 * 1440 + 分钟。 */ + val localSortKey: Int + get() = localWeekday.coerceIn(1, 7) * MINUTES_PER_DAY + localMinutes.coerceIn(0, MINUTES_PER_DAY - 1) + + companion object { + const val MINUTES_PER_DAY = 24 * 60 + } +} + +/** 按设备本地周几分组后的一天;[weekday] 使用 ISO 编号 1=周一 … 7=周日。 */ +data class ScheduleDay( + val weekday: Int, + val airings: List, +) { + val isEmpty: Boolean + get() = airings.isEmpty() + + companion object { + fun emptyDays(): List = (1..7).map { ScheduleDay(it, emptyList()) } + } +} + +/** 已按设备本地时区整理好的整周时间表。 */ +data class WeeklySchedule( + val season: String?, + val seasonStart: String?, + val seasonEnd: String?, + val generatedAt: String?, + /** 数据源声明的时区(通常为 Asia/Tokyo)。 */ + val sourceTimezone: String, + /** 设备当前时区 id。 */ + val localTimezone: String, + /** 固定 7 项,按周一 … 周日排列。 */ + val days: List, + /** 时间/周几不合法而被跳过的条目数。 */ + val skippedItemCount: Int = 0, +) { + val totalCount: Int + get() = days.sumOf { it.airings.size } + + fun day(weekday: Int): ScheduleDay? = days.firstOrNull { it.weekday == weekday } +} + +/** Bangumi subject id -> 本地媒体库里的作品(同 id 只保留第一条)。 */ +fun List.indexAnimeByBangumiId(): Map { + val index = LinkedHashMap() + for (anime in this) { + val bangumiId = anime.bangumiId?.takeIf { it > 0 } ?: continue + index.putIfAbsent(bangumiId, anime) + } + return index +} + +/** 时间表条目在本地媒体库里的匹配结果;null 表示「未在媒体库」。 */ +fun ScheduleAiring.matchedAnime(index: Map): Anime? = + subjectId.takeIf { it > 0 }?.let(index::get) + +/** 媒体库匹配统计(用于表头概览)。 */ +fun WeeklySchedule.matchedCount(index: Map): Int = + days.sumOf { day -> day.airings.count { it.matchedAnime(index) != null } } diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleTimeConversion.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleTimeConversion.kt new file mode 100644 index 00000000..2ed77469 --- /dev/null +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleTimeConversion.kt @@ -0,0 +1,198 @@ +package com.miruplay.tv.model + +import java.time.DayOfWeek +import java.time.Instant +import java.time.LocalDate +import java.time.LocalTime +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeParseException +import java.time.temporal.ChronoUnit + +/** 换算到设备本地时区后的一个时间段。 */ +data class ScheduleLocalSlot( + /** ISO 周几:1=周一 … 7=周日。 */ + val weekday: Int, + /** 当天 0 点起的分钟数。 */ + val minutes: Int, + /** "HH:mm"。 */ + val timeLabel: String, + /** 本地日期相对 JST 播出日期的天数差。 */ + val crossDayOffset: Int, +) { + val sortKey: Int + get() = weekday * ScheduleAiring.MINUTES_PER_DAY + minutes +} + +/** + * JST 周几 + 时刻 → 设备本地时区的周几 + 时刻。 + * + * 跨日必须正确:例如 JST 周日 01:30 在 UTC-4 是周六 12:30。 + * + * 契约以「JST 周几 + 时刻」(ScheduleItem.weekday / ScheduleItem.time)为权威播出时刻: + * 锚定到 [now] 之后最近一次满足该周几 + 时刻的 JST 日期,再做完整时区换算。 + * 不使用 airDate:线上数据实测存在 airDate 与 weekday 不一致的条目(例如 airDate 是 + * 周一但 weekday=5),按 airDate 换算会把周五的番显示成周一。 + * + * 纯函数、不依赖系统默认时区,测试可注入 [sourceZone] / [localZone] / [now]。 + */ +object ScheduleTimeConversion { + + val JAPAN_TV_ZONE: ZoneId = ZoneId.of("Asia/Tokyo") + + private val TIME_PATTERN = Regex("""^(\d{1,2}):(\d{2})(?::\d{2})?$""") + + /** 解析 "HH:mm" / "H:mm" / "HH:mm:ss";小时必须 0..23(AirRadar 已把深夜番归一化为真实时钟)。 */ + fun parseTimeOfDay(raw: String?): LocalTime? { + val text = raw?.trim().orEmpty() + if (text.isEmpty()) return null + val match = TIME_PATTERN.matchEntire(text) ?: return null + val hour = match.groupValues[1].toIntOrNull() ?: return null + val minute = match.groupValues[2].toIntOrNull() ?: return null + if (hour !in 0..23 || minute !in 0..59) return null + return LocalTime.of(hour, minute) + } + + /** 1..7(ISO)→ 周几;非法返回 null。 */ + fun normalizeWeekday(weekday: Int): Int? = weekday.takeIf { it in 1..7 } + + fun parseZoneOrNull(raw: String?): ZoneId? = + raw?.trim()?.takeIf { it.isNotEmpty() }?.let { runCatching { ZoneId.of(it) }.getOrNull() } + + /** 解析 JST 播出日期(ISO yyyy-MM-dd);缺失/非法返回 null。 */ + fun parseAirDate(raw: String?): LocalDate? = + raw?.trim()?.takeIf { it.isNotEmpty() }?.let { + try { + LocalDate.parse(it) + } catch (_: DateTimeParseException) { + null + } + } + + /** 把一条「JST 周几 + HH:mm」换算到 [localZone](airDate 不可信,按 weekday + time 锚定)。 */ + fun toLocalSlot( + weekday: Int, + time: String, + sourceZone: ZoneId = JAPAN_TV_ZONE, + localZone: ZoneId, + now: Instant = Instant.now(), + ): ScheduleLocalSlot? { + val normalizedWeekday = normalizeWeekday(weekday) ?: return null + val localTime = parseTimeOfDay(time) ?: return null + val jstDate = nextAiringDate( + weekday = normalizedWeekday, + time = localTime, + sourceZone = sourceZone, + now = now, + ) + return convert(jstDate, localTime, sourceZone, localZone) + } + + /** 锚定到 [now] 之后(含正在进行的当天时刻)最近一次满足周几 + 时刻的 JST 日期。 */ + private fun nextAiringDate( + weekday: Int, + time: LocalTime, + sourceZone: ZoneId, + now: Instant, + ): LocalDate { + val nowInSource = now.atZone(sourceZone) + val today = nowInSource.toLocalDate() + val delta = Math.floorMod(weekday - today.dayOfWeek.value, 7) + var candidate = today.plusDays(delta.toLong()) + val candidateDateTime = ZonedDateTime.of(candidate, time, sourceZone) + if (candidateDateTime.toInstant().isBefore(now)) { + candidate = candidate.plusDays(7L) + } + return candidate + } + + private fun convert( + jstDate: LocalDate, + time: LocalTime, + sourceZone: ZoneId, + localZone: ZoneId, + ): ScheduleLocalSlot { + val localDateTime = ZonedDateTime.of(jstDate, time, sourceZone) + .withZoneSameInstant(localZone) + .toLocalDateTime() + val weekday = localDateTime.dayOfWeek.value + val minutes = localDateTime.hour * 60 + localDateTime.minute + val crossDayOffset = ChronoUnit.DAYS.between(jstDate, localDateTime.toLocalDate()).toInt() + return ScheduleLocalSlot( + weekday = weekday, + minutes = minutes, + timeLabel = formatClock(localDateTime.hour, localDateTime.minute), + crossDayOffset = crossDayOffset, + ) + } + + /** + * 把一季的原始快照整理成「周一 … 周日」的分组周表: + * 条目按本地时间升序,7 天分组始终存在(没有条目的天是空分组)。 + */ + fun buildWeeklySchedule( + snapshot: ScheduleSnapshot, + localZone: ZoneId, + now: Instant = Instant.now(), + ): WeeklySchedule { + val snapshotZone = parseZoneOrNull(snapshot.timezone) ?: JAPAN_TV_ZONE + var skipped = 0 + val groups = (1..7).associateWith { mutableListOf() } + + for (item in snapshot.items) { + val itemZone = parseZoneOrNull(item.timezone) ?: snapshotZone + val slot = toLocalSlot( + weekday = item.weekday, + time = item.time, + sourceZone = itemZone, + localZone = localZone, + now = now, + ) + if (slot == null) { + skipped++ + continue + } + val jstTime = parseTimeOfDay(item.time) ?: continue + val airing = ScheduleAiring( + subjectId = item.subjectId, + displayName = item.displayName, + originalName = item.name.trim(), + imageUrl = item.image?.trim()?.takeIf { it.isNotEmpty() }, + confidence = ScheduleConfidence.fromWire(item.confidence), + sourceCount = item.sources.size, + airDate = item.airDate?.trim()?.takeIf { it.isNotEmpty() }, + jstWeekday = item.weekday, + jstTimeLabel = formatClock(jstTime.hour, jstTime.minute), + localWeekday = slot.weekday, + localMinutes = slot.minutes, + localTimeLabel = slot.timeLabel, + crossDayOffset = slot.crossDayOffset, + ) + groups.getValue(slot.weekday).add(airing) + } + + val days = (1..7).map { weekday -> + ScheduleDay( + weekday = weekday, + airings = groups.getValue(weekday) + .sortedWith(compareBy({ it.localMinutes }, { it.displayName })), + ) + } + return WeeklySchedule( + season = snapshot.season?.trim()?.takeIf { it.isNotEmpty() }, + seasonStart = snapshot.seasonStart?.trim()?.takeIf { it.isNotEmpty() }, + seasonEnd = snapshot.seasonEnd?.trim()?.takeIf { it.isNotEmpty() }, + generatedAt = snapshot.generatedAt?.trim()?.takeIf { it.isNotEmpty() }, + sourceTimezone = snapshotZone.id, + localTimezone = localZone.id, + days = days, + skippedItemCount = skipped, + ) + } + + private fun formatClock(hour: Int, minute: Int): String = + String.format(java.util.Locale.ROOT, "%02d:%02d", hour, minute) + + /** 本地周几的中文/英文标签由 UI 层用 UiText 处理;这里只提供 ISO 编号。 */ + fun isoWeekdayOf(dayOfWeek: DayOfWeek): Int = dayOfWeek.value +} diff --git a/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleUiConventions.kt b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleUiConventions.kt new file mode 100644 index 00000000..6686539b --- /dev/null +++ b/core/model/src/main/kotlin/com/miruplay/tv/model/ScheduleUiConventions.kt @@ -0,0 +1,238 @@ +package com.miruplay.tv.model + +import com.miruplay.tv.core.common.UiText +import com.miruplay.tv.core.common.joinUiText +import com.miruplay.tv.core.common.rawUiText +import com.miruplay.tv.core.common.uiText + +// ── 设置页:新番时间表分组 ──────────────────────────────────────────────── + +fun settingsScheduleMenuSummary(configured: Boolean): UiText = + if (configured) { + uiText("settings_menu_schedule_configured", "已配置") + } else { + uiText("settings_menu_schedule_unconfigured", "未配置") + } + +fun settingsSchedulePanelTitleLabel(): UiText = + uiText("settings_schedule_panel_title", "新番时间表") + +fun settingsSchedulePanelDescription(): UiText = + uiText( + "settings_schedule_panel_desc", + "填入时间表服务地址后,媒体库顶栏可打开每周新番表。地址只保存在本机。", + ) + +fun settingsScheduleUrlFieldLabel(): UiText = + uiText("settings_schedule_url_field", "时间表服务地址") + +fun settingsScheduleSaveActionLabel(): UiText = + uiText("settings_schedule_save", "保存地址") + +fun settingsScheduleClearActionLabel(): UiText = + uiText("settings_schedule_clear", "清除地址") + +fun settingsScheduleSavedStatus(): UiText = + uiText("settings_schedule_saved", "时间表地址已保存。") + +fun settingsScheduleClearedStatus(): UiText = + uiText("settings_schedule_cleared", "时间表地址已清除。") + +fun settingsScheduleInvalidUrlStatus(): UiText = + uiText("settings_schedule_invalid", "地址无效:需要以 http:// 或 https:// 开头的完整地址。") + +fun settingsScheduleCurrentUnsetStatus(): UiText = + uiText("settings_schedule_current_unset", "尚未配置时间表地址。") + +fun settingsScheduleCurrentStatus(url: String): UiText = + UiText("settings_schedule_current", listOf(url), "当前地址:$url") + +fun settingsScheduleOpenScheduleActionLabel(): UiText = + uiText("settings_schedule_open", "打开时间表") + +// ── 时间表页 ──────────────────────────────────────────────────────────── + +fun libraryScheduleActionLabel(): UiText = + uiText("library_schedule_action", "时间表") + +fun scheduleScreenTitleLabel(): UiText = + uiText("schedule_title", "新番时间表") + +fun scheduleScreenSubtitleLabel(): UiText = + uiText("schedule_subtitle", "每周播出时间 · 已换算到设备时区") + +fun scheduleLoadingMessage(): UiText = + uiText("schedule_loading", "正在获取时间表…") + +fun scheduleUnconfiguredTitle(): UiText = + uiText("schedule_unconfigured_title", "尚未配置时间表服务") + +fun scheduleUnconfiguredDescription(): UiText = + uiText( + "schedule_unconfigured_desc", + "到「设置 → 新番时间表」填入服务地址后,这里会显示每周播出时间。", + ) + +fun scheduleGoSettingsActionLabel(): UiText = + uiText("schedule_go_settings", "去设置") + +fun scheduleEmptyTitle(): UiText = + uiText("schedule_empty_title", "暂无播出数据") + +fun scheduleEmptyDescription(): UiText = + uiText("schedule_empty_desc", "服务端还没有发布本季时间表,稍后再试。") + +fun scheduleErrorTitle(): UiText = + uiText("schedule_error_title", "时间表获取失败") + +fun scheduleErrorMessage(error: ScheduleFetchError): UiText = + when (error) { + ScheduleFetchError.InvalidUrl -> uiText( + "schedule_error_invalid_url", + "数据源地址无效,请到设置里重新填写。", + ) + ScheduleFetchError.Network -> uiText( + "schedule_error_network", + "网络不可用,请检查网络后重试。", + ) + ScheduleFetchError.Timeout -> uiText( + "schedule_error_timeout", + "请求超时,请稍后重试。", + ) + is ScheduleFetchError.Http -> UiText( + "schedule_error_http", + listOf(error.code), + "服务返回错误(HTTP ${error.code})。", + ) + ScheduleFetchError.InvalidData -> uiText( + "schedule_error_invalid_data", + "时间表数据格式无法识别,请确认数据源地址。", + ) + } + +fun scheduleRetryActionLabel(): UiText = + uiText("schedule_retry", "重试") + +fun scheduleRefreshActionLabel(): UiText = + uiText("schedule_refresh", "刷新") + +fun scheduleBackActionLabel(): UiText = + uiText("schedule_back", "返回") + +fun scheduleSeasonLabel( + season: String?, + seasonStart: String?, + seasonEnd: String?, +): UiText? { + val safeSeason = season?.takeIf { it.isNotBlank() } + val start = seasonStart?.takeIf { it.isNotBlank() } + val end = seasonEnd?.takeIf { it.isNotBlank() } + return when { + safeSeason != null && start != null && end != null -> UiText( + "schedule_season_range", + listOf(safeSeason, start, end), + "$safeSeason · $start 至 $end", + ) + safeSeason != null -> rawUiText(safeSeason) + else -> null + } +} + +fun scheduleUpdatedAtLabel(localTimestamp: String): UiText = + UiText("schedule_updated_at", listOf(localTimestamp), "更新于 $localTimestamp") + +fun scheduleLocalZoneNote(zoneId: String): UiText = + UiText("schedule_local_zone", listOf(zoneId), "设备时区:$zoneId") + +fun scheduleTodayLabel(): UiText = + uiText("schedule_today", "今天") + +fun scheduleWeekdayLabel(weekday: Int): UiText = when (weekday) { + 1 -> uiText("schedule_weekday_mon", "周一") + 2 -> uiText("schedule_weekday_tue", "周二") + 3 -> uiText("schedule_weekday_wed", "周三") + 4 -> uiText("schedule_weekday_thu", "周四") + 5 -> uiText("schedule_weekday_fri", "周五") + 6 -> uiText("schedule_weekday_sat", "周六") + else -> uiText("schedule_weekday_sun", "周日") +} + +/** 「周一 22:00」——本地周几 + 本地时刻。 */ +fun scheduleLocalTimeLabel(weekday: Int, localTime: String): UiText { + val dayLabel = scheduleWeekdayLabel(weekday) + return UiText( + "schedule_local_time", + listOf(dayLabel, localTime), + "${dayLabel.fallback} $localTime", + ) +} + +/** 原始 JST 时刻,作为次要信息展示。 */ +fun scheduleJstTimeLabel(jstWeekday: Int, jstTime: String): UiText { + val dayLabel = scheduleWeekdayLabel(jstWeekday) + return UiText( + "schedule_jst_time", + listOf(dayLabel, jstTime), + "日本时间 ${dayLabel.fallback} $jstTime", + ) +} + +fun scheduleCrossDayNextDayLabel(): UiText = + uiText("schedule_cross_day_next", "次日") + +fun scheduleCrossDayPreviousDayLabel(): UiText = + uiText("schedule_cross_day_previous", "前日") + +fun scheduleConfidenceLabel(confidence: ScheduleConfidence): UiText = + when (confidence) { + ScheduleConfidence.HIGH -> uiText("schedule_confidence_high", "置信度高") + ScheduleConfidence.MEDIUM -> uiText("schedule_confidence_medium", "置信度中") + ScheduleConfidence.LOW -> uiText("schedule_confidence_low", "置信度低") + ScheduleConfidence.UNKNOWN -> uiText("schedule_confidence_unknown", "置信度未知") + } + +fun scheduleSourceCountLabel(count: Int): UiText { + val safe = count.coerceAtLeast(0) + return UiText("schedule_source_count", listOf(safe), "$safe 个来源") +} + +fun scheduleMatchedLabel(): UiText = + uiText("schedule_matched", "已匹配媒体库") + +fun scheduleUnmatchedLabel(): UiText = + uiText("schedule_unmatched", "未在媒体库") + +fun scheduleOpenDetailHint(): UiText = + uiText("schedule_open_detail_hint", "按确定打开详情") + +fun scheduleMatchedSummary(matchedCount: Int, totalCount: Int): UiText { + val matched = matchedCount.coerceAtLeast(0) + val total = totalCount.coerceAtLeast(0) + return UiText( + "schedule_matched_summary", + listOf(matched, total), + "媒体库匹配 $matched/$total", + ) +} + +fun scheduleCachedBadgeLabel(): UiText = + uiText("schedule_cached_badge", "缓存") + +fun scheduleStaleBannerLabel(): UiText = + uiText("schedule_stale_banner", "网络不可用,正在显示上次缓存的数据。") + +fun scheduleSkippedItemsLabel(count: Int): UiText { + val safe = count.coerceAtLeast(0) + return UiText("schedule_skipped_items", listOf(safe), "$safe 条数据时间无法解析,已跳过。") +} + +fun scheduleEmptyDayLabel(): UiText = + uiText("schedule_empty_day", "本日无新番") + +// 供时间表页头部拼接的多段文案(卷、更新时间、时区)。 +fun scheduleHeaderMeta( + seasonLabel: UiText?, + updatedAtLabel: UiText?, + localZoneLabel: UiText, +): UiText = + joinUiText(listOfNotNull(seasonLabel, updatedAtLabel, localZoneLabel)) 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 70fe7c5e..fd8a7c95 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 @@ -17,6 +17,10 @@ enum class MiruPlaySettingsSection( androidTvTitle = uiText("settings_section_sources_title", "媒体源"), androidTvDescription = uiText("settings_section_sources_desc", "本地、WebDAV、SMB"), ), + SCHEDULE( + androidTvTitle = uiText("settings_section_schedule_title", "新番时间表"), + androidTvDescription = uiText("settings_section_schedule_desc", "数据源与每周播出时间"), + ), PLAYBACK( androidTvTitle = uiText("settings_section_playback_title", "播放"), androidTvDescription = uiText("settings_section_playback_desc", "播完动作"), @@ -59,6 +63,7 @@ val androidTvSettingsSectionOrder: List = listOf( MiruPlaySettingsSection.WEB_UI, MiruPlaySettingsSection.SOURCES, + MiruPlaySettingsSection.SCHEDULE, MiruPlaySettingsSection.PLAYBACK, MiruPlaySettingsSection.AUDIO_DSP, MiruPlaySettingsSection.CLOUD_DRIVE, @@ -169,6 +174,7 @@ data class SettingsSectionMenuSummaryInput( val sourceCount: Int = 0, val playbackSummary: UiText = rawUiText(""), val audioDspEnabled: Boolean = false, + val scheduleConfigured: Boolean = false, val cloudDriveEnabled: Boolean = false, val rssCount: Int = 0, val proxyEnabled: Boolean = false, @@ -190,6 +196,7 @@ fun MiruPlaySettingsSection.settingsMenuSummary( when (this) { MiruPlaySettingsSection.WEB_UI -> settingsWebUiMenuSummary(input.webUiAddressCount) MiruPlaySettingsSection.SOURCES -> settingsSourcesMenuSummary(input.sourceCount) + MiruPlaySettingsSection.SCHEDULE -> settingsScheduleMenuSummary(input.scheduleConfigured) MiruPlaySettingsSection.PLAYBACK -> input.playbackSummary MiruPlaySettingsSection.AUDIO_DSP -> if (input.audioDspEnabled) { diff --git a/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrlTest.kt b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrlTest.kt new file mode 100644 index 00000000..27660876 --- /dev/null +++ b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleDataSourceUrlTest.kt @@ -0,0 +1,57 @@ +package com.miruplay.tv.model + +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 ScheduleDataSourceUrlTest { + + @Test + fun `accepts http and https base urls`() { + assertEquals("https://example.com", ScheduleDataSourceUrl.normalize("https://example.com")) + assertEquals("https://example.com", ScheduleDataSourceUrl.normalize(" https://example.com/ ")) + assertEquals("https://example.com:8443/api", ScheduleDataSourceUrl.normalize("https://example.com:8443/api/")) + assertEquals("http://192.168.1.10:8080", ScheduleDataSourceUrl.normalize("http://192.168.1.10:8080")) + } + + @Test + fun `rejects blank and non-http schemes`() { + assertNull(ScheduleDataSourceUrl.normalize(null)) + assertNull(ScheduleDataSourceUrl.normalize("")) + assertNull(ScheduleDataSourceUrl.normalize(" ")) + assertNull(ScheduleDataSourceUrl.normalize("example.com")) + assertNull(ScheduleDataSourceUrl.normalize("ftp://example.com")) + assertNull(ScheduleDataSourceUrl.normalize("file:///sdcard/schedule.json")) + assertNull(ScheduleDataSourceUrl.normalize("javascript:alert(1)")) + } + + @Test + fun `rejects url parts that break base-url joining`() { + assertNull(ScheduleDataSourceUrl.normalize("https://example.com/path?x=1")) + assertNull(ScheduleDataSourceUrl.normalize("https://example.com/path#frag")) + assertNull(ScheduleDataSourceUrl.normalize("https://user:pass@example.com")) + assertNull(ScheduleDataSourceUrl.normalize("https://exa mple.com")) + assertNull(ScheduleDataSourceUrl.normalize("https://")) + } + + @Test + fun `isValid mirrors normalize`() { + assertTrue(ScheduleDataSourceUrl.isValid("https://example.com")) + assertFalse(ScheduleDataSourceUrl.isValid("example.com")) + assertFalse(ScheduleDataSourceUrl.isValid(" ")) + } + + @Test + fun `latest endpoint joins without double slash`() { + assertEquals( + "https://example.com/api/schedule/latest", + ScheduleDataSourceUrl.latestScheduleEndpoint("https://example.com"), + ) + assertEquals( + "https://example.com:8443/base/api/schedule/latest", + ScheduleDataSourceUrl.latestScheduleEndpoint("https://example.com:8443/base/"), + ) + } +} diff --git a/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleSnapshotParsingTest.kt b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleSnapshotParsingTest.kt new file mode 100644 index 00000000..b91a4b45 --- /dev/null +++ b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleSnapshotParsingTest.kt @@ -0,0 +1,139 @@ +package com.miruplay.tv.model + +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant +import java.time.ZoneId + +class ScheduleSnapshotParsingTest { + + /** 与线上契约同构的 fixture;图片/来源域名均为示例占位,不含真实数据源地址。 */ + private val fixture = """ + { + "schemaVersion": 1, + "generatedAt": "2026-10-07T03:04:05Z", + "season": "2026-fall", + "seasonStart": "2026-10-01", + "seasonEnd": "2026-12-31", + "timezone": "Asia/Tokyo", + "itemCount": 3, + "items": [ + { + "subjectId": 393010, + "name": "サンプル・アニメ", + "nameCn": "示例动画", + "airDate": "2026-10-07", + "image": "https://example.com/pic/393010.jpg", + "weekday": 3, + "time": "23:00", + "timezone": "Asia/Tokyo", + "confidence": "high", + "sources": [ + {"url": "https://example.com/a", "domain": "example.com", "provider": "official_site"}, + {"url": "https://example.org/b", "domain": "example.org", "provider": "search"} + ], + "updatedAt": "2026-10-07T03:04:05Z" + }, + { + "subjectId": 393011, + "name": "夜中アニメ", + "nameCn": null, + "airDate": "2026-10-09", + "image": null, + "weekday": 5, + "time": "01:28", + "timezone": "Asia/Tokyo", + "confidence": "medium", + "sources": [], + "updatedAt": "2026-10-07T03:04:05Z" + }, + { + "subjectId": 393012, + "name": "Unknown Confidence Show", + "airDate": "2026-10-05", + "weekday": 1, + "time": "19:30", + "confidence": "some-future-value", + "sources": [] + } + ] + } + """.trimIndent() + + private val json = Json { ignoreUnknownKeys = true } + + @Test + fun `fixture decodes per api contract`() { + val snapshot = json.decodeFromString(fixture) + assertEquals(1, snapshot.schemaVersion) + assertEquals("2026-fall", snapshot.season) + assertEquals("Asia/Tokyo", snapshot.timezone) + assertEquals(3, snapshot.items.size) + + val first = snapshot.items[0] + assertEquals(393010, first.subjectId) + assertEquals("示例动画", first.displayName) + assertEquals("https://example.com/pic/393010.jpg", first.image) + assertEquals(3, first.weekday) + assertEquals("23:00", first.time) + assertEquals(2, first.sources.size) + assertEquals(ScheduleConfidence.HIGH, ScheduleConfidence.fromWire(first.confidence)) + + // nameCn 缺失时回退日文原名 + assertEquals("夜中アニメ", snapshot.items[1].displayName) + // 未知 confidence 值降级为 UNKNOWN 而不是解析失败 + assertEquals(ScheduleConfidence.UNKNOWN, ScheduleConfidence.fromWire(snapshot.items[2].confidence)) + } + + @Test + fun `future unknown top-level fields do not break parsing`() { + val tolerant = json.decodeFromString( + """{"schemaVersion":1,"items":[],"brandNewField":{"nested":true}}""", + ) + assertTrue(tolerant.items.isEmpty()) + assertNull(tolerant.season) + } + + @Test + fun `weekly schedule from fixture groups into local weekdays`() { + val snapshot = json.decodeFromString(fixture) + val weekly = ScheduleTimeConversion.buildWeeklySchedule( + snapshot = snapshot, + localZone = ZoneId.of("Asia/Shanghai"), + now = Instant.parse("2026-10-06T00:00:00Z"), + ) + assertEquals(3, weekly.totalCount) + // JST 周三 23:00 → 上海周三 22:00;JST 周五 01:28 → 上海周五 00:28;JST 周一 19:30 → 上海周一 18:30。 + assertEquals("22:00", weekly.day(3)!!.airings.single().localTimeLabel) + assertEquals("00:28", weekly.day(5)!!.airings.single().localTimeLabel) + assertEquals("18:30", weekly.day(1)!!.airings.single().localTimeLabel) + assertEquals("示例动画", weekly.day(3)!!.airings.single().displayName) + } + + @Test + fun `library matching uses bangumi subject id`() { + val snapshot = json.decodeFromString(fixture) + val weekly = ScheduleTimeConversion.buildWeeklySchedule( + snapshot = snapshot, + localZone = ZoneId.of("Asia/Shanghai"), + now = Instant.parse("2026-10-06T00:00:00Z"), + ) + val library = listOf( + Anime(id = "anime-1", title = "示例动画", bangumiId = 393010), + Anime(id = "anime-2", title = "没有 Bangumi id 的作品", bangumiId = null), + Anime(id = "anime-3", title = "重复 id 的后一条", bangumiId = 393010), + Anime(id = "anime-4", title = "其它作品", bangumiId = 999999), + ) + val index = library.indexAnimeByBangumiId() + assertEquals(2, index.size) // 393010 与 999999 + assertEquals("anime-1", index.getValue(393010).id) // 重复 id 保留第一条 + + val matched = weekly.day(3)!!.airings.single() + assertEquals("anime-1", matched.matchedAnime(index)?.id) + assertNull(weekly.day(5)!!.airings.single().matchedAnime(index)) // 393011 不在媒体库 + assertEquals(1, weekly.matchedCount(index)) + } +} diff --git a/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleTimeConversionTest.kt b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleTimeConversionTest.kt new file mode 100644 index 00000000..059330ab --- /dev/null +++ b/core/model/src/test/kotlin/com/miruplay/tv/model/ScheduleTimeConversionTest.kt @@ -0,0 +1,183 @@ +package com.miruplay.tv.model + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.Instant +import java.time.LocalTime +import java.time.ZoneId + +class ScheduleTimeConversionTest { + + private val shanghai = ZoneId.of("Asia/Shanghai") + private val utcPlus12 = ZoneId.of("UTC+12") + private val utcMinus4 = ZoneId.of("UTC-04:00") + + @Test + fun `parseTimeOfDay accepts hh-mm and h-mm`() { + assertEquals(LocalTime.of(23, 0), ScheduleTimeConversion.parseTimeOfDay("23:00")) + assertEquals(LocalTime.of(1, 5), ScheduleTimeConversion.parseTimeOfDay("1:05")) + assertEquals(LocalTime.of(1, 28), ScheduleTimeConversion.parseTimeOfDay("01:28:00")) + assertEquals(LocalTime.MIDNIGHT, ScheduleTimeConversion.parseTimeOfDay("00:00")) + } + + @Test + fun `parseTimeOfDay rejects malformed clock values`() { + assertNull(ScheduleTimeConversion.parseTimeOfDay(null)) + assertNull(ScheduleTimeConversion.parseTimeOfDay("")) + assertNull(ScheduleTimeConversion.parseTimeOfDay("24:00")) + assertNull(ScheduleTimeConversion.parseTimeOfDay("23:60")) + assertNull(ScheduleTimeConversion.parseTimeOfDay("abc")) + assertNull(ScheduleTimeConversion.parseTimeOfDay("2300")) + } + + @Test + fun `jst slot converts to shanghai same weekday minute minus one`() { + val slot = ScheduleTimeConversion.toLocalSlot( + weekday = 3, + time = "23:00", + localZone = shanghai, + now = Instant.parse("2026-10-06T00:00:00Z"), // JST 周二 09:00 + )!! + assertEquals(3, slot.weekday) + assertEquals(22 * 60, slot.minutes) + assertEquals("22:00", slot.timeLabel) + assertEquals(0, slot.crossDayOffset) + } + + @Test + fun `jst early-morning slot crosses back to previous day in western zone`() { + // JST 周日 01:30(锚到 2026-10-04)→ UTC-4 是周六 12:30(2026-10-03)。 + val slot = ScheduleTimeConversion.toLocalSlot( + weekday = 7, + time = "01:30", + localZone = utcMinus4, + now = Instant.parse("2026-10-01T00:00:00Z"), + )!! + assertEquals(6, slot.weekday) + assertEquals("12:30", slot.timeLabel) + assertEquals(-1, slot.crossDayOffset) + } + + @Test + fun `jst late-night slot crosses forward to next day in eastern zone`() { + // JST 周日 23:00(锚到 2026-10-04)→ UTC+12 是周一 02:00(2026-10-05)。 + val slot = ScheduleTimeConversion.toLocalSlot( + weekday = 7, + time = "23:00", + localZone = utcPlus12, + now = Instant.parse("2026-10-01T00:00:00Z"), + )!! + assertEquals(1, slot.weekday) + assertEquals("02:00", slot.timeLabel) + assertEquals(1, slot.crossDayOffset) + } + + @Test + fun `dst zone uses real zone rules around us fall-back`() { + // 2026-11-01 美国夏令时结束:JST 11-02 01:30 → 纽约 EST(-5) 11-01 11:30,跨回前一天。 + val slot = ScheduleTimeConversion.toLocalSlot( + weekday = 1, + time = "01:30", + localZone = ZoneId.of("America/New_York"), + now = Instant.parse("2026-10-30T00:00:00Z"), + )!! + assertEquals(7, slot.weekday) + assertEquals("11:30", slot.timeLabel) + assertEquals(-1, slot.crossDayOffset) + } + + @Test + fun `slot anchors to next occurrence when todays airing already passed`() { + // now = 2026-10-07 23:30 JST(周三晚上)→ 周三 23:00 已过,应锚到下周三(10-14)。 + val slot = ScheduleTimeConversion.toLocalSlot( + weekday = 3, + time = "23:00", + localZone = shanghai, + now = Instant.parse("2026-10-07T14:30:00Z"), + )!! + assertEquals(3, slot.weekday) + assertEquals("22:00", slot.timeLabel) + } + + @Test + fun `buildWeeklySchedule groups by local weekday and sorts by local time`() { + val snapshot = ScheduleSnapshot( + season = "2026-fall", + seasonStart = "2026-10-01", + seasonEnd = "2026-12-31", + timezone = "Asia/Tokyo", + items = listOf( + // airDate 故意与 weekday 不一致:契约以 weekday + time 为准。 + ScheduleItem(subjectId = 1, name = "A", airDate = "2026-10-05", weekday = 3, time = "23:00"), + ScheduleItem(subjectId = 2, name = "B", airDate = "2026-10-09", weekday = 4, time = "01:28"), + ScheduleItem(subjectId = 3, name = "C", weekday = 3, time = "19:00"), + ScheduleItem(subjectId = 4, name = "D", weekday = 3, time = "bad-clock", airDate = "2026-10-07"), + ScheduleItem(subjectId = 5, name = "E", weekday = 9, time = "10:00", airDate = "2026-10-07"), + ), + ) + val weekly = ScheduleTimeConversion.buildWeeklySchedule( + snapshot = snapshot, + localZone = shanghai, + now = Instant.parse("2026-10-01T00:00:00Z"), // JST 周四 09:00 + ) + assertEquals(7, weekly.days.size) + assertEquals(2, weekly.skippedItemCount) // 两条非法(4 的时钟、5 的周几) + assertEquals(3, weekly.totalCount) + val wednesday = weekly.day(3)!! + assertEquals(listOf(3, 1), wednesday.airings.map { it.subjectId }) // 18:00 早于 22:00 + assertEquals(listOf("18:00", "22:00"), wednesday.airings.map { it.localTimeLabel }) + // JST 周四 01:28 → 上海周四 00:28,仍在周四(当天 01:28 已过,锚到下周四语义相同)。 + assertEquals(4, weekly.day(4)!!.airings.single().localWeekday) + assertEquals("00:28", weekly.day(4)!!.airings.single().localTimeLabel) + assertEquals("2026-fall", weekly.season) + assertEquals("Asia/Shanghai", weekly.localTimezone) + assertEquals("Asia/Tokyo", weekly.sourceTimezone) + } + + @Test + fun `inconsistent airDate does not override the weekday`() { + // 线上 AirRadar 数据实测有 airDate 与 weekday 不一致的条目: + // airDate 2026-10-05 是周一,但 weekday=5、time=10:00 —— 必须显示为周五。 + val snapshot = ScheduleSnapshot( + timezone = "Asia/Tokyo", + items = listOf( + ScheduleItem( + subjectId = 7, + name = "Contradictory", + airDate = "2026-10-05", + weekday = 5, + time = "10:00", + ), + ), + ) + val weekly = ScheduleTimeConversion.buildWeeklySchedule( + snapshot = snapshot, + localZone = shanghai, + now = Instant.parse("2026-10-05T00:00:00Z"), + ) + assertTrue(weekly.day(1)!!.isEmpty) + val friday = weekly.day(5)!!.airings.single() + assertEquals("09:00", friday.localTimeLabel) + assertEquals(5, friday.localWeekday) + } + + @Test + fun `weekly grouping follows the converted local weekday`() { + val snapshot = ScheduleSnapshot( + timezone = "Asia/Tokyo", + items = listOf( + ScheduleItem(subjectId = 8, name = "Cross", weekday = 7, time = "01:30", airDate = "2026-10-01"), + ), + ) + val weekly = ScheduleTimeConversion.buildWeeklySchedule( + snapshot = snapshot, + localZone = utcMinus4, + now = Instant.parse("2026-10-01T00:00:00Z"), + ) + // JST 周日 01:30 → UTC-4 周六 12:30:分组要落在周六,且周日为空。 + assertEquals("12:30", weekly.day(6)!!.airings.single().localTimeLabel) + assertTrue(weekly.day(7)!!.isEmpty) + } +} diff --git a/core/model/src/test/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventionsTest.kt b/core/model/src/test/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventionsTest.kt index 1246b685..4796f779 100644 --- a/core/model/src/test/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventionsTest.kt +++ b/core/model/src/test/kotlin/com/miruplay/tv/model/SettingsSectionDisplayConventionsTest.kt @@ -10,13 +10,14 @@ class SettingsSectionDisplayConventionsTest { @Test fun `settings section copy is shared`() { assertEquals( - listOf("WebUI", "媒体源", "播放", "音频 DSP", "CloudDrive", "代理配置", "扫描", "日志上报", "更新", "元数据", "关于"), + listOf("WebUI", "媒体源", "新番时间表", "播放", "音频 DSP", "CloudDrive", "代理配置", "扫描", "日志上报", "更新", "元数据", "关于"), androidTvSettingsSectionOrder.map { it.androidTvTitle.fallback }, ) assertEquals( listOf( "访问地址与二维码", "本地、WebDAV、SMB", + "数据源与每周播出时间", "播完动作", "PEQ、扫频测量与校准", "RSS 离线下载与入库", @@ -42,6 +43,8 @@ class SettingsSectionDisplayConventionsTest { assertEquals("等待网络", settingsWebUiMenuSummary(addressCount = 0).fallback) assertEquals("2 个地址", settingsWebUiMenuSummary(addressCount = 2).fallback) assertEquals("3 个源", settingsSourcesMenuSummary(sourceCount = 3).fallback) + assertEquals("未配置", settingsScheduleMenuSummary(configured = false).fallback) + assertEquals("已配置", settingsScheduleMenuSummary(configured = true).fallback) assertEquals("未启用", settingsCloudDriveMenuSummary(enabled = false, rssCount = 4).fallback) assertEquals("4 个订阅", settingsCloudDriveMenuSummary(enabled = true, rssCount = 4).fallback) assertEquals("未启用", settingsProxyMenuSummary(enabled = false).fallback) @@ -102,6 +105,7 @@ class SettingsSectionDisplayConventionsTest { ) assertEquals("2 个地址", MiruPlaySettingsSection.WEB_UI.settingsMenuSummary(androidInput).fallback) assertEquals("3 个源", MiruPlaySettingsSection.SOURCES.settingsMenuSummary(androidInput).fallback) + assertEquals("未配置", MiruPlaySettingsSection.SCHEDULE.settingsMenuSummary(androidInput).fallback) assertEquals("播完动作", MiruPlaySettingsSection.PLAYBACK.settingsMenuSummary(androidInput).fallback) assertEquals("4 个订阅", MiruPlaySettingsSection.CLOUD_DRIVE.settingsMenuSummary(androidInput).fallback) assertEquals("203.0.113.20:7890", MiruPlaySettingsSection.PROXY.settingsMenuSummary(androidInput).fallback) diff --git a/data/src/main/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClient.kt b/data/src/main/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClient.kt new file mode 100644 index 00000000..922af985 --- /dev/null +++ b/data/src/main/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClient.kt @@ -0,0 +1,85 @@ +package com.miruplay.tv.data.schedule + +import com.miruplay.tv.model.ScheduleDataSourceUrl +import com.miruplay.tv.model.ScheduleFetchError +import com.miruplay.tv.model.ScheduleSnapshot +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.Json +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.IOException +import java.net.SocketTimeoutException +import java.util.concurrent.TimeUnit +import javax.inject.Inject + +sealed interface ScheduleFetchResult { + data class Success(val snapshot: ScheduleSnapshot) : ScheduleFetchResult + + /** 404 no_schedule_data:服务端尚未发布任何数据。 */ + data object NoData : ScheduleFetchResult + data class Failure(val error: ScheduleFetchError) : ScheduleFetchResult +} + +/** + * AirRadar 时间表 HTTP 客户端。 + * + * - 复用 App 的单例 OkHttp(练连接池),但使用更短的 10s 超时; + * - 只 GET `{baseUrl}/api/schedule/latest`,地址来自用户运行时配置; + * - 404 视为「尚无数据」,其它非 2xx 视为可重试错误。 + */ +class AirRadarScheduleClient @Inject constructor( + baseClient: OkHttpClient, +) { + private val client: OkHttpClient = baseClient.newBuilder() + .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) + .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) + .callTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) + .build() + + private val json = Json { + ignoreUnknownKeys = true + isLenient = true + } + + suspend fun fetchLatest(baseUrl: String): ScheduleFetchResult = withContext(Dispatchers.IO) { + val normalized = ScheduleDataSourceUrl.normalize(baseUrl) + ?: return@withContext ScheduleFetchResult.Failure(ScheduleFetchError.InvalidUrl) + val request = Request.Builder() + .url(ScheduleDataSourceUrl.latestScheduleEndpoint(normalized)) + .header("Accept", "application/json") + .get() + .build() + + try { + client.newCall(request).execute().use { response -> + when { + response.code == HTTP_NOT_FOUND -> ScheduleFetchResult.NoData + !response.isSuccessful -> ScheduleFetchResult.Failure( + ScheduleFetchError.Http(response.code), + ) + else -> { + val body = response.body?.string().orEmpty() + val snapshot = runCatching { + json.decodeFromString(body) + }.getOrNull() + if (snapshot == null) { + ScheduleFetchResult.Failure(ScheduleFetchError.InvalidData) + } else { + ScheduleFetchResult.Success(snapshot) + } + } + } + } + } catch (_: SocketTimeoutException) { + ScheduleFetchResult.Failure(ScheduleFetchError.Timeout) + } catch (_: IOException) { + ScheduleFetchResult.Failure(ScheduleFetchError.Network) + } + } + + companion object { + internal const val TIMEOUT_SECONDS = 10L + private const val HTTP_NOT_FOUND = 404 + } +} diff --git a/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferences.kt b/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferences.kt new file mode 100644 index 00000000..6af21f6e --- /dev/null +++ b/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferences.kt @@ -0,0 +1,46 @@ +package com.miruplay.tv.data.schedule + +import android.content.Context +import com.miruplay.tv.model.ScheduleDataSourceUrl +import dagger.hilt.android.qualifiers.ApplicationContext +import javax.inject.Inject +import javax.inject.Singleton + +/** + * 时间表数据源地址的本地持久化(沿用项目现有 SharedPreferences 设置体系)。 + * + * 默认空字符串表示未配置:老版本升级后没有这个 key,读到的就是空值,不需要迁移; + * 地址只保存在本机,不写入仓库/文档/日志。 + */ +@Singleton +class ScheduleDataSourcePreferences @Inject constructor( + @ApplicationContext context: Context, +) { + private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + + /** 运行时配置的原始地址;空表示未配置。 */ + var rawDataSourceUrl: String + get() = prefs.getString(KEY_DATA_SOURCE_URL, null).orEmpty() + set(value) { + prefs.edit().putString(KEY_DATA_SOURCE_URL, value.trim()).apply() + } + + /** 已归一化、可直接拼接口的地址;未配置或非法时为 null。 */ + fun configuredUrlOrNull(): String? = ScheduleDataSourceUrl.normalize(rawDataSourceUrl) + + /** 保存地址;非法地址返回 false 且不覆盖旧值(UI 会提示校验失败)。 */ + fun save(rawUrl: String?): Boolean { + val normalized = ScheduleDataSourceUrl.normalize(rawUrl) ?: return false + rawDataSourceUrl = normalized + return true + } + + fun clear() { + prefs.edit().remove(KEY_DATA_SOURCE_URL).apply() + } + + companion object { + internal const val PREFS_NAME = "miruplay_schedule_prefs" + internal const val KEY_DATA_SOURCE_URL = "schedule_data_source_url" + } +} diff --git a/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleRepository.kt b/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleRepository.kt new file mode 100644 index 00000000..42d1b9ea --- /dev/null +++ b/data/src/main/kotlin/com/miruplay/tv/data/schedule/ScheduleRepository.kt @@ -0,0 +1,190 @@ +package com.miruplay.tv.data.schedule + +import android.content.Context +import com.miruplay.tv.model.ScheduleDataSourceUrl +import com.miruplay.tv.model.ScheduleFetchError +import com.miruplay.tv.model.ScheduleSnapshot +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.io.File +import javax.inject.Inject +import javax.inject.Singleton + +/** 加载结果:UI 据此区分 未配置 / 加载中 / 无数据(404) / 失败 / 成功。 */ +sealed interface ScheduleLoadResult { + data class Success( + val snapshot: ScheduleSnapshot, + /** true 表示来自内存/磁盘缓存(未发网络请求)。 */ + val fromCache: Boolean, + /** true 表示缓存已过期、网络又失败,展示的是旧数据;[error] 是失败原因。 */ + val stale: Boolean, + val error: ScheduleFetchError? = null, + ) : ScheduleLoadResult + + data object NotConfigured : ScheduleLoadResult + data object Empty : ScheduleLoadResult + data class Failure(val error: ScheduleFetchError) : ScheduleLoadResult +} + +@Serializable +internal data class CachedSchedule( + val fetchedAtMillis: Long, + val snapshot: ScheduleSnapshot, +) + +/** + * 时间表仓库:内存 + 磁盘两级缓存(TTL 1 小时),网络失败时回退到旧缓存(stale)。 + * + * - 缓存文件在 app cacheDir 下,随 `clearCache` 或系统清理缓存消失; + * - 404 视为「服务端尚无数据」:清掉缓存并返回 [ScheduleLoadResult.Empty]; + * - 所有 load 调用串行化,避免并发刷新重复打网络。 + */ +@Singleton +class ScheduleRepository @Inject constructor( + @ApplicationContext private val context: Context, + private val client: AirRadarScheduleClient, + private val preferences: ScheduleDataSourcePreferences, +) { + private val json = Json { + ignoreUnknownKeys = true + isLenient = true + } + private val loadMutex = Mutex() + + @Volatile + private var memoryCache: CachedSchedule? = null + + private val cacheDirectory: File by lazy { File(context.cacheDir, CACHE_DIRECTORY_NAME) } + private val cacheFile: File by lazy { File(cacheDirectory, CACHE_FILE_NAME) } + + fun configuredUrlOrNull(): String? = preferences.configuredUrlOrNull() + + fun rawConfiguredUrl(): String = preferences.rawDataSourceUrl + + /** 保存数据源地址;非法地址返回 false(不覆盖旧值)。 */ + fun saveDataSourceUrl(rawUrl: String?): Boolean = preferences.save(rawUrl) + + fun clearDataSourceUrl() { + preferences.clear() + clearCache() + } + + /** 当前是否有可展示的缓存(用于设置页状态摘要,不触发网络)。 */ + fun hasCachedSnapshot(): Boolean = memoryCache != null || cacheFile.exists() + + suspend fun load( + forceRefresh: Boolean = false, + nowMillis: Long = System.currentTimeMillis(), + ): ScheduleLoadResult = loadMutex.withLock { + val baseUrl = configuredUrlOrNull() + ?: return@withLock ScheduleLoadResult.NotConfigured + + if (!forceRefresh) { + val cached = freshCacheOrNull(nowMillis) + if (cached != null) { + return@withLock ScheduleLoadResult.Success( + snapshot = cached.snapshot, + fromCache = true, + stale = false, + ) + } + } + + return@withLock when (val result = client.fetchLatest(baseUrl)) { + is ScheduleFetchResult.Success -> { + val cached = CachedSchedule(fetchedAtMillis = nowMillis, snapshot = result.snapshot) + memoryCache = cached + writeDiskCache(cached) + ScheduleLoadResult.Success( + snapshot = result.snapshot, + fromCache = false, + stale = false, + ) + } + + ScheduleFetchResult.NoData -> { + clearCache() + ScheduleLoadResult.Empty + } + + is ScheduleFetchResult.Failure -> { + // 网络/解析失败时尽量给用户看上次成功的数据,而不是空白页。 + val stale = memoryCache ?: readDiskCache() + if (stale != null) { + ScheduleLoadResult.Success( + snapshot = stale.snapshot, + fromCache = true, + stale = true, + error = result.error, + ) + } else { + ScheduleLoadResult.Failure(result.error) + } + } + } + } + + fun clearCache() { + memoryCache = null + runCatching { cacheFile.delete() } + } + + private suspend fun freshCacheOrNull(nowMillis: Long): CachedSchedule? { + memoryCache?.takeIf { it.isFresh(nowMillis) }?.let { return it } + val disk = readDiskCache() ?: return null + return if (disk.isFresh(nowMillis)) { + memoryCache = disk + disk + } else { + // 过期缓存留着给网络失败时兜底,但不算 fresh。 + memoryCache = disk + null + } + } + + private suspend fun readDiskCache(): CachedSchedule? = withContext(Dispatchers.IO) { + val file = cacheFile + if (!file.exists()) return@withContext null + val parsed = runCatching { + json.decodeFromString(file.readText()) + }.getOrNull() + if (parsed == null) { + runCatching { file.delete() } + } + parsed + } + + private suspend fun writeDiskCache(cached: CachedSchedule) { + runCatching { + withContext(Dispatchers.IO) { + if (!cacheDirectory.exists()) cacheDirectory.mkdirs() + val temp = File(cacheDirectory, "$CACHE_FILE_NAME.tmp") + temp.writeText(json.encodeToString(CachedSchedule.serializer(), cached)) + if (cacheFile.exists()) cacheFile.delete() + if (!temp.renameTo(cacheFile)) { + temp.copyTo(cacheFile, overwrite = true) + temp.delete() + } + } + } + } + + internal fun cacheFileForTest(): File = cacheFile + + companion object { + const val CACHE_TTL_MILLIS: Long = 60L * 60L * 1000L + private const val CACHE_DIRECTORY_NAME = "schedule" + private const val CACHE_FILE_NAME = "latest_schedule.json" + } +} + +internal fun CachedSchedule.isFresh(nowMillis: Long): Boolean = + nowMillis - fetchedAtMillis in 0 until ScheduleRepository.CACHE_TTL_MILLIS && fetchedAtMillis > 0L + +/** 供 UI 层判断配置地址是否可保存。 */ +internal fun isValidDataSourceInput(raw: String?): Boolean = ScheduleDataSourceUrl.isValid(raw) diff --git a/data/src/test/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClientTest.kt b/data/src/test/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClientTest.kt new file mode 100644 index 00000000..a8f1021b --- /dev/null +++ b/data/src/test/kotlin/com/miruplay/tv/data/schedule/AirRadarScheduleClientTest.kt @@ -0,0 +1,114 @@ +package com.miruplay.tv.data.schedule + +import com.miruplay.tv.model.ScheduleFetchError +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.util.concurrent.TimeUnit + +class AirRadarScheduleClientTest { + + private lateinit var server: MockWebServer + private lateinit var client: AirRadarScheduleClient + + @Before + fun setUp() { + server = MockWebServer() + server.start() + client = AirRadarScheduleClient( + OkHttpClient.Builder() + .connectTimeout(2, TimeUnit.SECONDS) + .readTimeout(2, TimeUnit.SECONDS) + .build(), + ) + } + + @After + fun tearDown() { + server.shutdown() + } + + private fun baseUrl(): String = server.url("/").toString().trimEnd('/') + + @Test + fun `success parses snapshot and requests latest endpoint`() = runBlocking { + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + + val result = client.fetchLatest(baseUrl()) + + assertTrue(result is ScheduleFetchResult.Success) + val snapshot = (result as ScheduleFetchResult.Success).snapshot + assertEquals("2026-fall", snapshot.season) + assertEquals(2, snapshot.items.size) + assertEquals("示例动画", snapshot.items[0].displayName) + + val recorded = server.takeRequest(2, TimeUnit.SECONDS)!! + assertEquals("/api/schedule/latest", recorded.path) + assertEquals("GET", recorded.method) + } + + @Test + fun `404 maps to no data`() = runBlocking { + server.enqueue(MockResponse().setResponseCode(404).setBody("""{"error":"no_schedule_data"}""")) + + val result = client.fetchLatest(baseUrl()) + + assertEquals(ScheduleFetchResult.NoData, result) + } + + @Test + fun `5xx maps to retryable http error`() = runBlocking { + server.enqueue(MockResponse().setResponseCode(503).setBody("busy")) + + val result = client.fetchLatest(baseUrl()) + + assertEquals(ScheduleFetchResult.Failure(ScheduleFetchError.Http(503)), result) + } + + @Test + fun `malformed json maps to invalid data`() = runBlocking { + server.enqueue(MockResponse().setResponseCode(200).setBody("not-json")) + + val result = client.fetchLatest(baseUrl()) + + assertEquals(ScheduleFetchResult.Failure(ScheduleFetchError.InvalidData), result) + } + + @Test + fun `unreachable host maps to network error`() = runBlocking { + val unusedUrl = server.url("/").toString().trimEnd('/') + server.shutdown() + + val result = client.fetchLatest(unusedUrl) + + assertTrue(result is ScheduleFetchResult.Failure) + } + + @Test + fun `invalid base url fails fast without network`() = runBlocking { + val result = client.fetchLatest("ftp://example.com") + assertEquals(ScheduleFetchResult.Failure(ScheduleFetchError.InvalidUrl), result) + } + + companion object { + val FIXTURE = """{ + "schemaVersion": 1, + "generatedAt": "2026-10-07T03:04:05Z", + "season": "2026-fall", + "seasonStart": "2026-10-01", + "seasonEnd": "2026-12-31", + "timezone": "Asia/Tokyo", + "itemCount": 2, + "items": [ + {"subjectId": 393010, "name": "サンプル", "nameCn": "示例动画", "airDate": "2026-10-07", "image": "https://example.com/a.jpg", "weekday": 3, "time": "23:00", "timezone": "Asia/Tokyo", "confidence": "high", "sources": [{"url": "https://example.com/s", "domain": "example.com", "provider": "official_site"}]}, + {"subjectId": 393011, "name": "夜中アニメ", "airDate": "2026-10-09", "weekday": 5, "time": "01:28", "timezone": "Asia/Tokyo", "confidence": "medium", "sources": []} + ] +}""" + } +} diff --git a/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferencesTest.kt b/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferencesTest.kt new file mode 100644 index 00000000..e50a7f6b --- /dev/null +++ b/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleDataSourcePreferencesTest.kt @@ -0,0 +1,65 @@ +package com.miruplay.tv.data.schedule + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class ScheduleDataSourcePreferencesTest { + + private lateinit var context: Context + private lateinit var preferences: ScheduleDataSourcePreferences + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences(ScheduleDataSourcePreferences.PREFS_NAME, Context.MODE_PRIVATE) + .edit() + .clear() + .commit() + preferences = ScheduleDataSourcePreferences(context) + } + + @Test + fun `old install without the key reads as not configured`() { + assertEquals("", preferences.rawDataSourceUrl) + assertNull(preferences.configuredUrlOrNull()) + } + + @Test + fun `save normalizes trailing slash and trims whitespace`() { + assertTrue(preferences.save(" https://example.com/ ")) + + assertEquals("https://example.com", preferences.rawDataSourceUrl) + assertEquals("https://example.com", preferences.configuredUrlOrNull()) + } + + @Test + fun `invalid save keeps the previous url`() { + assertTrue(preferences.save("https://example.com/base")) + + assertFalse(preferences.save("not-a-url")) + assertFalse(preferences.save("ftp://example.com")) + assertFalse(preferences.save(null)) + + assertEquals("https://example.com/base", preferences.configuredUrlOrNull()) + } + + @Test + fun `clear removes the configured url`() { + assertTrue(preferences.save("https://example.com")) + preferences.clear() + + assertEquals("", preferences.rawDataSourceUrl) + assertNull(preferences.configuredUrlOrNull()) + } +} diff --git a/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleRepositoryTest.kt b/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleRepositoryTest.kt new file mode 100644 index 00000000..d87ba4e7 --- /dev/null +++ b/data/src/test/kotlin/com/miruplay/tv/data/schedule/ScheduleRepositoryTest.kt @@ -0,0 +1,212 @@ +package com.miruplay.tv.data.schedule + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.util.concurrent.TimeUnit + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class ScheduleRepositoryTest { + + private lateinit var context: Context + private lateinit var server: MockWebServer + private lateinit var preferences: ScheduleDataSourcePreferences + private lateinit var repository: ScheduleRepository + + private fun baseUrl(): String = server.url("/").toString().trimEnd('/') + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences(ScheduleDataSourcePreferences.PREFS_NAME, Context.MODE_PRIVATE) + .edit() + .clear() + .commit() + File(context.cacheDir, "schedule").deleteRecursively() + server = MockWebServer() + server.start() + preferences = ScheduleDataSourcePreferences(context) + repository = newRepository() + } + + @After + fun tearDown() { + runCatching { server.shutdown() } + } + + private fun newRepository(): ScheduleRepository = ScheduleRepository( + context = context, + client = AirRadarScheduleClient( + OkHttpClient.Builder() + .connectTimeout(2, TimeUnit.SECONDS) + .readTimeout(2, TimeUnit.SECONDS) + .build(), + ), + preferences = preferences, + ) + + private fun configureUrl(url: String = baseUrl()): Boolean = repository.saveDataSourceUrl(url) + + @Test + fun `not configured returns NotConfigured without network`() = runBlocking { + val result = repository.load(nowMillis = 1_000L) + + assertEquals(ScheduleLoadResult.NotConfigured, result) + assertEquals(0, server.requestCount) + } + + @Test + fun `invalid configured url is treated as not configured`() = runBlocking { + preferences.rawDataSourceUrl = "ftp://example.com" + + assertEquals(ScheduleLoadResult.NotConfigured, repository.load(nowMillis = 1_000L)) + assertEquals(0, server.requestCount) + } + + @Test + fun `fresh load goes to network and caches in memory and on disk`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + + val result = repository.load(nowMillis = 1_000L) as ScheduleLoadResult.Success + + assertFalse(result.fromCache) + assertFalse(result.stale) + assertEquals("2026-fall", result.snapshot.season) + assertEquals(1, server.requestCount) + assertTrue(repository.cacheFileForTest().exists()) + + val cached = repository.load(nowMillis = 2_000L) as ScheduleLoadResult.Success + assertTrue(cached.fromCache) + assertFalse(cached.stale) + assertEquals(1, server.requestCount) // 未过期,不再发请求 + } + + @Test + fun `cache expires after one hour and refetches`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + repository.load(nowMillis = 1_000L) + + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + val expired = repository.load( + nowMillis = 1_000L + ScheduleRepository.CACHE_TTL_MILLIS, + ) as ScheduleLoadResult.Success + + assertFalse(expired.fromCache) + assertEquals(2, server.requestCount) + } + + @Test + fun `disk cache survives repository recreation`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + repository.load(nowMillis = 1_000L) + + val recreated = newRepository() + val result = recreated.load(nowMillis = 2_000L) as ScheduleLoadResult.Success + + assertTrue(result.fromCache) + assertFalse(result.stale) + assertEquals(1, server.requestCount) + } + + @Test + fun `network failure falls back to stale cache`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + repository.load(nowMillis = 1_000L) + server.shutdown() + + val recreated = newRepository() + val result = recreated.load( + forceRefresh = true, + nowMillis = 1_000L + ScheduleRepository.CACHE_TTL_MILLIS * 2, + ) as ScheduleLoadResult.Success + + assertTrue(result.fromCache) + assertTrue(result.stale) + assertNotNull(result.error) + } + + @Test + fun `network failure without cache returns retryable failure`() = runBlocking { + assertTrue(configureUrl()) + server.shutdown() + + val result = repository.load(nowMillis = 1_000L) + + assertTrue(result is ScheduleLoadResult.Failure) + assertFalse(repository.hasCachedSnapshot()) + } + + @Test + fun `404 means empty and clears old cache`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + repository.load(nowMillis = 1_000L) + assertTrue(repository.hasCachedSnapshot()) + + server.enqueue(MockResponse().setResponseCode(404).setBody("""{"error":"no_schedule_data"}""")) + val result = repository.load(forceRefresh = true, nowMillis = 2_000L) + + assertEquals(ScheduleLoadResult.Empty, result) + assertFalse(repository.hasCachedSnapshot()) + } + + @Test + fun `force refresh bypasses fresh cache`() = runBlocking { + assertTrue(configureUrl()) + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + repository.load(nowMillis = 1_000L) + + server.enqueue(MockResponse().setResponseCode(200).setBody(FIXTURE)) + val refreshed = repository.load(forceRefresh = true, nowMillis = 2_000L) as ScheduleLoadResult.Success + + assertFalse(refreshed.fromCache) + assertEquals(2, server.requestCount) + } + + @Test + fun `saving url validates and clears cache`() = runBlocking { + assertTrue(configureUrl()) + assertEquals(baseUrl(), preferences.configuredUrlOrNull()) + + assertFalse(repository.saveDataSourceUrl("ftp://example.com")) + assertEquals(baseUrl(), preferences.configuredUrlOrNull()) + + repository.clearDataSourceUrl() + assertNull(preferences.configuredUrlOrNull()) + } + + companion object { + val FIXTURE = """{ + "schemaVersion": 1, + "generatedAt": "2026-10-07T03:04:05Z", + "season": "2026-fall", + "seasonStart": "2026-10-01", + "seasonEnd": "2026-12-31", + "timezone": "Asia/Tokyo", + "itemCount": 1, + "items": [ + {"subjectId": 393010, "name": "サンプル", "nameCn": "示例动画", "airDate": "2026-10-07", "weekday": 3, "time": "23:00", "timezone": "Asia/Tokyo", "confidence": "high", "sources": []} + ] +}""" + } +} diff --git a/docs/agents/pre-pr-checklist.md b/docs/agents/pre-pr-checklist.md index 09ddcb76..19f90d6b 100644 --- a/docs/agents/pre-pr-checklist.md +++ b/docs/agents/pre-pr-checklist.md @@ -374,3 +374,33 @@ Cross-checks: Not device-verified: - HK1 上用真实 Bangumi 账号走完验证码并看到收藏同步。本环境没有盒子,也没有发版用的 client id/secret。单测用 MockWebServer 固定了 Bangumi 登录页和授权页的 HTML 结构;线上页面改版后要再对一次真实验证码 + +### 新番时间表(时间表服务接入 + 设置数据源)(2026-11-20) + +Own checks(HK1 真机,debug APK,2026-11-20): + +- [真机] 媒体库顶栏「时间表」→ 新番时间表页:loading → 内容(2026-fall · 2026-10-01 至 2026-12-31;更新于 11-20 01:23;设备时区 Asia/Shanghai;媒体库匹配 0/10) +- [真机] 周一 … 周日分组、组内按本地时间升序;JST→本地换算正确(日本时间 周一 19:00 → 周一 18:00;日本时间 周六 00:30 → 周五 23:30 且带「前日」标记);周五分组显示「今天」chip,空分组显示「本日无新番」 +- [真机] 刷新重拉网络(清缓存后首次进入无「缓存」角标;再次进入显示「缓存」角标,证明磁盘缓存 TTL 内直接复用) +- [真机] 设置 →「新番时间表」:菜单摘要「已配置」;面板显示服务地址、保存地址/打开时间表/清除地址;按保存显示「时间表地址已保存。」 +- [真机] 未配置态清空设置后显示「尚未配置时间表服务 / 去设置」;配置不可达地址且无缓存时显示「时间表获取失败 / 网络不可用,请检查网络后重试。/ 重试」 +- [真机] 设置页打开无崩溃(曾因 VerifyError 崩溃,修复后复测);全流程 logcat 无 AndroidRuntime:E / FATAL +- 单测:JSON fixture 解析 + 未知字段兼容、JST→本地(跨日前后、DST、weekday+time 优先于不可信 airDate)、7 天分组与本地时间排序、URL 校验/归一化/非法 scheme、内存+磁盘缓存 TTL/强制刷新/失败回退 stale/404 清缓存、设置保存校验、Bangumi subject id 匹配、Settings section 文案、WebAPI 路由 GET/PUT 正常/非法/清除 + +Cross-checks: + +- 设置三端一致:TV 设置「新番时间表」、WebAPI `GET/PUT /api/settings/schedule`、WebUI「新番时间表」视图读写同一个 SharedPreferences 键;API/WebUI 单测只使用 `https://example.com`,真实服务地址不入库 +- 既有设置面板(媒体源/播放/元数据/代理等)与设置页返回/焦点导航不受新增 section 影响 +- 媒体库顶栏既有搜索/扫描/设置按钮焦点顺序保持(时间表按钮在扫描左侧,UP→搜索→RIGHT 逐项可达) +- `./gradlew assembleDebug`、相关模块单测、`./gradlew lint` 全绿 + +Not device-verified: + +- 匹配本地媒体库 → 进详情:HK1 现有媒体库只有 AudioTest(无 Bangumi ID),时间表 10 条全部「未在媒体库」;匹配逻辑与 fixture 由单测覆盖,详情路由复用既有 ANIME_DETAIL 路径 +- 404「暂无播出数据」空态:线上服务当前有数据,真机无法复现;由 `ScheduleRepositoryTest` 的 404 用例覆盖 +- 跨日「次日」标记:设备时区 Asia/Shanghai 只会出现「前日」;「次日」由 UTC+12 单测覆盖 + +New findings(section 1 候选 failure class): + +- **超大 Composable 追加捕获值 → D8 VerifyError(构建/单测全绿,真机进页面即崩)**:往 5.6k 行的 `AddSourceScreen` 主组合 lambda 里再加几个 `collectAsStateWithLifecycle` State/草稿后,debug(debuggable + R8 不优化)DEX 校验在进入设置页时报 `java.lang.VerifyError: Verifier rejected class ...AddSourceScreenKt$AddSourceScreen$12$1`;把新状态收进独立子组合(`ScheduleSourcePanel` 自行 collect/持有草稿)后恢复。检查:改超大型 Compose 函数时数一下主 lambda 新增捕获值,状态与 UI 尽量下沉到子 composable,并真机实际打开该页面。 +- **上游 airDate 与 weekday 自相矛盾**:时间表服务实测返回的 `airDate` 与 `weekday` 不一致(如 airDate 是周一而 weekday=周五),按 airDate 做时区锚定会把周五的番显示成周一;契约以 weekday+time 为权威,客户端换算只信这两个字段,单测 `inconsistent airDate does not override the weekday` 固化。 diff --git a/docs/agents/settings-web-control-parity-checklist.md b/docs/agents/settings-web-control-parity-checklist.md index 64fd00f2..82dc16ad 100644 --- a/docs/agents/settings-web-control-parity-checklist.md +++ b/docs/agents/settings-web-control-parity-checklist.md @@ -81,6 +81,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 型号拒写 | +| 新番时间表数据源(AirRadar 兼容) | ✅ 设置 →「新番时间表」(服务地址输入、保存/清除、已配置/未配置状态) | ✅ `GET/PUT /api/settings/schedule`(`ScheduleSettingsDto` ↔ `ScheduleRepository`);空字符串=清除,非法地址返回 400 | ✅「新番时间表」视图(地址输入、保存/清除、已配置/未配置状态) | 服务地址由用户在运行时填写,只保存在设备本机 SharedPreferences;仓库、文档、日志都不写入真实域名(示例仅用 `https://example.com`) | | 出站代理(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 登录 | ✅ 元数据区 WebView / 外部浏览器,回环 `127.0.0.1:13712/callback` | ✅ `POST /api/metadata/bangumi-login/start|captcha|cancel` 与 `POST /api/metadata/bangumi-login`(邮箱、密码、验证码)。手动 token 仍走 `bangumi-token`。密码不入库、不回显 | ✅ 元数据页账号登录:验证码由电视代拉(走出站代理),通过后设备换 token | 网页不把浏览器重定向到 `127.0.0.1`。TV WebView 与网页登录共用 `BangumiOAuthCoordinator`。未配 client id/secret 时网页返回 `not_configured` | diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/common/UiTextResolver.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/common/UiTextResolver.kt index afce1534..46ffcff8 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/common/UiTextResolver.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/common/UiTextResolver.kt @@ -1185,5 +1185,66 @@ internal fun uiTextResId(key: String): Int = "translate_lang_ru" -> R.string.translate_lang_ru "translate_lang_pt" -> R.string.translate_lang_pt "settings_app_mode_music" -> R.string.settings_app_mode_music + "settings_section_schedule_title" -> R.string.settings_section_schedule_title + "settings_section_schedule_desc" -> R.string.settings_section_schedule_desc + "settings_menu_schedule_configured" -> R.string.settings_menu_schedule_configured + "settings_menu_schedule_unconfigured" -> R.string.settings_menu_schedule_unconfigured + "settings_schedule_panel_title" -> R.string.settings_schedule_panel_title + "settings_schedule_panel_desc" -> R.string.settings_schedule_panel_desc + "settings_schedule_url_field" -> R.string.settings_schedule_url_field + "settings_schedule_save" -> R.string.settings_schedule_save + "settings_schedule_clear" -> R.string.settings_schedule_clear + "settings_schedule_saved" -> R.string.settings_schedule_saved + "settings_schedule_cleared" -> R.string.settings_schedule_cleared + "settings_schedule_invalid" -> R.string.settings_schedule_invalid + "settings_schedule_current_unset" -> R.string.settings_schedule_current_unset + "settings_schedule_current" -> R.string.settings_schedule_current + "settings_schedule_open" -> R.string.settings_schedule_open + "library_schedule_action" -> R.string.library_schedule_action + "schedule_title" -> R.string.schedule_title + "schedule_subtitle" -> R.string.schedule_subtitle + "schedule_loading" -> R.string.schedule_loading + "schedule_unconfigured_title" -> R.string.schedule_unconfigured_title + "schedule_unconfigured_desc" -> R.string.schedule_unconfigured_desc + "schedule_go_settings" -> R.string.schedule_go_settings + "schedule_empty_title" -> R.string.schedule_empty_title + "schedule_empty_desc" -> R.string.schedule_empty_desc + "schedule_error_title" -> R.string.schedule_error_title + "schedule_error_invalid_url" -> R.string.schedule_error_invalid_url + "schedule_error_network" -> R.string.schedule_error_network + "schedule_error_timeout" -> R.string.schedule_error_timeout + "schedule_error_http" -> R.string.schedule_error_http + "schedule_error_invalid_data" -> R.string.schedule_error_invalid_data + "schedule_retry" -> R.string.schedule_retry + "schedule_refresh" -> R.string.schedule_refresh + "schedule_back" -> R.string.schedule_back + "schedule_season_range" -> R.string.schedule_season_range + "schedule_updated_at" -> R.string.schedule_updated_at + "schedule_local_zone" -> R.string.schedule_local_zone + "schedule_today" -> R.string.schedule_today + "schedule_weekday_mon" -> R.string.schedule_weekday_mon + "schedule_weekday_tue" -> R.string.schedule_weekday_tue + "schedule_weekday_wed" -> R.string.schedule_weekday_wed + "schedule_weekday_thu" -> R.string.schedule_weekday_thu + "schedule_weekday_fri" -> R.string.schedule_weekday_fri + "schedule_weekday_sat" -> R.string.schedule_weekday_sat + "schedule_weekday_sun" -> R.string.schedule_weekday_sun + "schedule_local_time" -> R.string.schedule_local_time + "schedule_jst_time" -> R.string.schedule_jst_time + "schedule_cross_day_next" -> R.string.schedule_cross_day_next + "schedule_cross_day_previous" -> R.string.schedule_cross_day_previous + "schedule_confidence_high" -> R.string.schedule_confidence_high + "schedule_confidence_medium" -> R.string.schedule_confidence_medium + "schedule_confidence_low" -> R.string.schedule_confidence_low + "schedule_confidence_unknown" -> R.string.schedule_confidence_unknown + "schedule_source_count" -> R.string.schedule_source_count + "schedule_matched" -> R.string.schedule_matched + "schedule_unmatched" -> R.string.schedule_unmatched + "schedule_open_detail_hint" -> R.string.schedule_open_detail_hint + "schedule_matched_summary" -> R.string.schedule_matched_summary + "schedule_cached_badge" -> R.string.schedule_cached_badge + "schedule_stale_banner" -> R.string.schedule_stale_banner + "schedule_skipped_items" -> R.string.schedule_skipped_items + "schedule_empty_day" -> R.string.schedule_empty_day else -> 0 } diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/library/LibraryScreen.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/library/LibraryScreen.kt index d2ecfab4..55cc97a3 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/library/LibraryScreen.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/library/LibraryScreen.kt @@ -27,6 +27,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Search import androidx.lifecycle.Lifecycle @@ -52,6 +53,7 @@ import com.miruplay.tv.model.libraryManualScanActionLabel import com.miruplay.tv.model.libraryNoSourcesMessage import com.miruplay.tv.model.libraryPosterWallSectionTitle import com.miruplay.tv.model.libraryRecentlyAddedSectionTitle +import com.miruplay.tv.model.libraryScheduleActionLabel import com.miruplay.tv.model.libraryScanActionLabel import com.miruplay.tv.model.libraryScanNowActionLabel import com.miruplay.tv.model.libraryScanningTitle @@ -69,6 +71,7 @@ import kotlinx.coroutines.delay @Composable fun LibraryScreen( onNavigateToSettings: () -> Unit, + onNavigateToSchedule: () -> Unit, onNavigateToDetail: (String) -> Unit, viewModel: LibraryViewModel = hiltViewModel() ) { @@ -138,7 +141,8 @@ fun LibraryScreen( }, onScan = { viewModel.scanNow() }, onCancelScan = { viewModel.cancelScan() }, - onNavigateToSettings = onNavigateToSettings + onNavigateToSettings = onNavigateToSettings, + onNavigateToSchedule = onNavigateToSchedule, ) when (val state = uiState) { @@ -198,7 +202,8 @@ private fun LibraryHeader( onSearchActiveChange: (Boolean) -> Unit, onScan: () -> Unit, onCancelScan: () -> Unit, - onNavigateToSettings: () -> Unit + onNavigateToSettings: () -> Unit, + onNavigateToSchedule: () -> Unit, ) { Row( modifier = Modifier.fillMaxWidth().padding(bottom = 24.dp), @@ -269,6 +274,13 @@ private fun LibraryHeader( } Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + TvButton( + text = libraryScheduleActionLabel().resolve(), + icon = Icons.Filled.DateRange, + onClick = onNavigateToSchedule, + modifier = Modifier.width(132.dp), + secondary = true, + ) if (activeScan == null) { TvButton( text = libraryScanActionLabel().resolve(), diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleScreen.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleScreen.kt new file mode 100644 index 00000000..c4c50366 --- /dev/null +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleScreen.kt @@ -0,0 +1,586 @@ +package com.miruplay.tv.ui.schedule + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +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.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Settings +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.tv.material3.ExperimentalTvMaterial3Api +import androidx.tv.material3.Text +import com.miruplay.tv.model.scheduleCachedBadgeLabel +import com.miruplay.tv.model.scheduleConfidenceLabel +import com.miruplay.tv.model.scheduleCrossDayNextDayLabel +import com.miruplay.tv.model.scheduleCrossDayPreviousDayLabel +import com.miruplay.tv.model.scheduleEmptyDayLabel +import com.miruplay.tv.model.scheduleEmptyDescription +import com.miruplay.tv.model.scheduleEmptyTitle +import com.miruplay.tv.model.scheduleErrorMessage +import com.miruplay.tv.model.scheduleErrorTitle +import com.miruplay.tv.model.scheduleGoSettingsActionLabel +import com.miruplay.tv.model.scheduleJstTimeLabel +import com.miruplay.tv.model.scheduleLoadingMessage +import com.miruplay.tv.model.scheduleLocalTimeLabel +import com.miruplay.tv.model.scheduleLocalZoneNote +import com.miruplay.tv.model.scheduleMatchedLabel +import com.miruplay.tv.model.scheduleMatchedSummary +import com.miruplay.tv.model.scheduleOpenDetailHint +import com.miruplay.tv.model.scheduleRefreshActionLabel +import com.miruplay.tv.model.scheduleRetryActionLabel +import com.miruplay.tv.model.scheduleBackActionLabel +import com.miruplay.tv.model.scheduleSeasonLabel +import com.miruplay.tv.model.scheduleSkippedItemsLabel +import com.miruplay.tv.model.scheduleSourceCountLabel +import com.miruplay.tv.model.scheduleScreenSubtitleLabel +import com.miruplay.tv.model.scheduleScreenTitleLabel +import com.miruplay.tv.model.scheduleStaleBannerLabel +import com.miruplay.tv.model.scheduleTodayLabel +import com.miruplay.tv.model.scheduleUnconfiguredDescription +import com.miruplay.tv.model.scheduleUnconfiguredTitle +import com.miruplay.tv.model.scheduleUnmatchedLabel +import com.miruplay.tv.model.scheduleUpdatedAtLabel +import com.miruplay.tv.model.scheduleWeekdayLabel +import com.miruplay.tv.ui.common.resolve +import com.miruplay.tv.ui.components.InitialFocusHandle +import com.miruplay.tv.ui.components.LoadingIndicator +import com.miruplay.tv.ui.components.OverscanContainer +import com.miruplay.tv.ui.components.RemoteImage +import com.miruplay.tv.ui.components.TvButton +import com.miruplay.tv.ui.components.rememberInitialFocusHandle +import com.miruplay.tv.ui.components.tvFocusableClickable +import com.miruplay.tv.ui.theme.AccentBlue +import com.miruplay.tv.ui.theme.AnimeRed +import com.miruplay.tv.ui.theme.DarkSurface +import com.miruplay.tv.ui.theme.FocusBorder +import com.miruplay.tv.ui.theme.ProgressGreen +import com.miruplay.tv.ui.theme.TextPrimary +import com.miruplay.tv.ui.theme.TextSecondary +import com.miruplay.tv.ui.theme.TvTypography +import com.miruplay.tv.ui.theme.WarningYellow + +/** + * 新番时间表:按设备本地时区的周一 … 周日分组、组内按本地时间升序。 + * + * - 未配置数据源 → 引导去设置; + * - 服务端 404 无数据 → 空态;请求失败且有缓存 → 旧数据 + 提示条; + * - 匹配到本地媒体库(Bangumi subject id)的行按确定键进详情,未匹配显示「未在媒体库」。 + */ +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +fun ScheduleScreen( + onNavigateBack: () -> Unit, + onNavigateToDetail: (String) -> Unit, + onNavigateToSettings: () -> Unit, + viewModel: ScheduleViewModel = hiltViewModel(), +) { + val state by viewModel.state.collectAsStateWithLifecycle() + + OverscanContainer { + Column(modifier = Modifier.fillMaxSize()) { + ScheduleHeader( + showRefresh = state !is ScheduleUiState.Loading, + onRefresh = viewModel::refresh, + onNavigateBack = onNavigateBack, + ) + + when (val current = state) { + ScheduleUiState.Loading -> LoadingState() + ScheduleUiState.Unconfigured -> UnconfiguredState( + onNavigateToSettings = onNavigateToSettings, + ) + ScheduleUiState.Empty -> EmptyState(onRetry = viewModel::retry) + is ScheduleUiState.Error -> ErrorState( + state = current, + onRetry = viewModel::retry, + onNavigateToSettings = onNavigateToSettings, + ) + is ScheduleUiState.Content -> ScheduleContent( + content = current, + onNavigateToDetail = onNavigateToDetail, + ) + } + } + } +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun ScheduleHeader( + showRefresh: Boolean, + onRefresh: () -> Unit, + onNavigateBack: () -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp), + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = scheduleScreenTitleLabel().resolve(), + style = TvTypography.title, + color = TextPrimary, + ) + Spacer(Modifier.height(4.dp)) + Text( + text = scheduleScreenSubtitleLabel().resolve(), + style = TvTypography.body, + color = TextSecondary, + ) + } + if (showRefresh) { + TvButton( + text = scheduleRefreshActionLabel().resolve(), + icon = Icons.Filled.Refresh, + onClick = onRefresh, + modifier = Modifier.width(150.dp), + ) + } + TvButton( + text = scheduleBackActionLabel().resolve(), + icon = Icons.AutoMirrored.Filled.ArrowBack, + onClick = onNavigateBack, + modifier = Modifier.width(150.dp), + secondary = true, + ) + } +} + +@Composable +private fun LoadingState() { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Box(modifier = Modifier.size(64.dp)) { LoadingIndicator() } + Spacer(Modifier.height(16.dp)) + Text( + text = scheduleLoadingMessage().resolve(), + style = TvTypography.body, + color = TextSecondary, + ) + } + } +} + +@Composable +private fun UnconfiguredState(onNavigateToSettings: () -> Unit) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = scheduleUnconfiguredTitle().resolve(), + style = TvTypography.subtitle, + color = TextPrimary, + ) + Spacer(Modifier.height(10.dp)) + Text( + text = scheduleUnconfiguredDescription().resolve(), + style = TvTypography.body, + color = TextSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.padding(horizontal = 64.dp), + ) + Spacer(Modifier.height(20.dp)) + TvButton( + text = scheduleGoSettingsActionLabel().resolve(), + icon = Icons.Filled.Settings, + onClick = onNavigateToSettings, + modifier = Modifier.width(220.dp), + ) + } + } +} + +@Composable +private fun EmptyState(onRetry: () -> Unit) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = scheduleEmptyTitle().resolve(), + style = TvTypography.subtitle, + color = TextPrimary, + ) + Spacer(Modifier.height(10.dp)) + Text( + text = scheduleEmptyDescription().resolve(), + style = TvTypography.body, + color = TextSecondary, + ) + Spacer(Modifier.height(20.dp)) + TvButton( + text = scheduleRetryActionLabel().resolve(), + icon = Icons.Filled.Refresh, + onClick = onRetry, + modifier = Modifier.width(180.dp), + ) + } + } +} + +@Composable +private fun ErrorState( + state: ScheduleUiState.Error, + onRetry: () -> Unit, + onNavigateToSettings: () -> Unit, +) { + Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text( + text = scheduleErrorTitle().resolve(), + style = TvTypography.subtitle, + color = WarningYellow, + ) + Spacer(Modifier.height(10.dp)) + Text( + text = scheduleErrorMessage(state.error).resolve(), + style = TvTypography.body, + color = TextSecondary, + textAlign = TextAlign.Center, + modifier = Modifier.padding(horizontal = 64.dp), + ) + Spacer(Modifier.height(20.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + TvButton( + text = scheduleRetryActionLabel().resolve(), + icon = Icons.Filled.Refresh, + onClick = onRetry, + modifier = Modifier.width(180.dp), + ) + TvButton( + text = scheduleGoSettingsActionLabel().resolve(), + icon = Icons.Filled.Settings, + onClick = onNavigateToSettings, + modifier = Modifier.width(220.dp), + secondary = true, + ) + } + } + } +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun ScheduleContent( + content: ScheduleUiState.Content, + onNavigateToDetail: (String) -> Unit, +) { + val firstNonEmptyDay = content.days.firstOrNull { it.rows.isNotEmpty() } + val firstRowKey = firstNonEmptyDay?.rows?.firstOrNull()?.airing?.subjectId + val initialFocus = rememberInitialFocusHandle( + key = firstRowKey, + enabled = firstRowKey != null, + initialDelayMillis = 300, + ) + + Column(modifier = Modifier.fillMaxSize()) { + ContentMetaRow(content) + Spacer(Modifier.height(10.dp)) + LazyColumn( + modifier = Modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(8.dp), + contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 24.dp), + ) { + content.days.forEach { day -> + item(key = "day-${day.weekday}") { + DayHeader(day = day) + } + if (day.rows.isEmpty()) { + item(key = "empty-${day.weekday}") { + EmptyDayRow() + } + } else { + itemsIndexed( + items = day.rows, + key = { index, row -> "entry-${day.weekday}-${row.airing.subjectId}-$index" }, + ) { index, row -> + val isFirstRow = day.weekday == firstNonEmptyDay?.weekday && index == 0 + ScheduleRow( + row = row, + initialFocus = if (isFirstRow) initialFocus else null, + onOpenDetail = onNavigateToDetail, + ) + } + } + } + } + } +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun ContentMetaRow(content: ScheduleUiState.Content) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = scheduleSeasonLabel( + season = content.season, + seasonStart = content.seasonStart, + seasonEnd = content.seasonEnd, + )?.resolve() ?: "", + style = TvTypography.subtitle, + color = TextPrimary, + ) + Spacer(Modifier.height(2.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) { + content.generatedAtLocal?.let { generatedAt -> + Text( + text = scheduleUpdatedAtLabel(generatedAt).resolve(), + style = TvTypography.caption, + color = TextSecondary, + ) + } + Text( + text = scheduleLocalZoneNote(content.localTimezone).resolve(), + style = TvTypography.caption, + color = TextSecondary, + ) + Text( + text = scheduleMatchedSummary(content.matchedCount, content.totalCount).resolve(), + style = TvTypography.caption, + color = if (content.matchedCount > 0) ProgressGreen else TextSecondary, + ) + if (content.skippedItemCount > 0) { + Text( + text = scheduleSkippedItemsLabel(content.skippedItemCount).resolve(), + style = TvTypography.caption, + color = WarningYellow, + ) + } + } + } + if (content.fromCache) { + Text( + text = scheduleCachedBadgeLabel().resolve(), + style = TvTypography.caption, + color = TextSecondary, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(DarkSurface) + .padding(horizontal = 10.dp, vertical = 4.dp), + ) + } + } + if (content.stale) { + Spacer(Modifier.height(6.dp)) + Text( + text = scheduleStaleBannerLabel().resolve(), + style = TvTypography.caption, + color = WarningYellow, + ) + } +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun DayHeader(day: ScheduleDayUi) { + Row( + modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 2.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text( + text = scheduleWeekdayLabel(day.weekday).resolve(), + style = TvTypography.subtitle, + color = if (day.isToday) AnimeRed else TextPrimary, + ) + if (day.isToday) { + Text( + text = scheduleTodayLabel().resolve(), + style = TvTypography.caption, + color = Color.Black, + modifier = Modifier + .clip(RoundedCornerShape(6.dp)) + .background(AnimeRed) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) + } + Text( + text = "${day.rows.size}", + style = TvTypography.caption, + color = TextSecondary, + ) + } +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun EmptyDayRow() { + Text( + text = scheduleEmptyDayLabel().resolve(), + style = TvTypography.caption, + color = TextSecondary.copy(alpha = 0.6f), + modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), + ) +} + +@OptIn(ExperimentalTvMaterial3Api::class) +@Composable +private fun ScheduleRow( + row: ScheduleRowUi, + initialFocus: InitialFocusHandle?, + onOpenDetail: (String) -> Unit, +) { + val interactionSource = remember { MutableInteractionSource() } + val focused by interactionSource.collectIsFocusedAsState() + val airing = row.airing + val borderColor = if (focused) FocusBorder else Color.White.copy(alpha = 0.10f) + val backgroundColor = if (focused) AccentBlue else DarkSurface + + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 88.dp) + .clip(RoundedCornerShape(10.dp)) + .background(backgroundColor) + .border(if (focused) 3.dp else 1.dp, borderColor, RoundedCornerShape(10.dp)) + .then(initialFocus?.modifier() ?: Modifier) + .tvFocusableClickable( + interactionSource = interactionSource, + onClick = { row.matchedAnimeId?.let(onOpenDetail) }, + ) + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(14.dp), + ) { + Column(modifier = Modifier.width(186.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = scheduleLocalTimeLabel(airing.localWeekday, airing.localTimeLabel).resolve(), + style = TvTypography.subtitle, + color = if (focused) Color.White else AnimeRed, + maxLines = 1, + ) + val crossDayLabel = when { + airing.crossDayOffset > 0 -> scheduleCrossDayNextDayLabel() + airing.crossDayOffset < 0 -> scheduleCrossDayPreviousDayLabel() + else -> null + } + if (crossDayLabel != null) { + Spacer(Modifier.width(6.dp)) + Text( + text = crossDayLabel.resolve(), + style = TvTypography.caption, + color = WarningYellow, + ) + } + } + Text( + text = scheduleJstTimeLabel(airing.jstWeekday, airing.jstTimeLabel).resolve(), + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.82f) else TextSecondary, + maxLines = 1, + ) + } + + RemoteImage( + url = airing.imageUrl, + contentDescription = null, + modifier = Modifier + .width(46.dp) + .height(64.dp) + .clip(RoundedCornerShape(6.dp)), + ) + + Column(modifier = Modifier.weight(1f)) { + Text( + text = airing.displayName, + style = TvTypography.body.copy(fontWeight = FontWeight.SemiBold), + color = if (focused) Color.White else TextPrimary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (airing.originalName.isNotBlank() && airing.originalName != airing.displayName) { + Text( + text = airing.originalName, + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.82f) else TextSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.height(3.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = scheduleConfidenceLabel(airing.confidence).resolve(), + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.82f) else TextSecondary, + ) + if (airing.sourceCount > 0) { + Text( + text = scheduleSourceCountLabel(airing.sourceCount).resolve(), + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.82f) else TextSecondary, + ) + } + } + } + + Column( + modifier = Modifier.width(260.dp), + horizontalAlignment = Alignment.End, + ) { + if (row.isMatched) { + Text( + text = scheduleMatchedLabel().resolve(), + style = TvTypography.caption, + color = if (focused) Color.White else ProgressGreen, + maxLines = 1, + ) + row.matchedAnimeTitle?.let { title -> + Text( + text = title, + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.9f) else TextSecondary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Text( + text = scheduleOpenDetailHint().resolve(), + style = TvTypography.caption, + color = if (focused) Color.White.copy(alpha = 0.82f) else TextSecondary.copy(alpha = 0.7f), + maxLines = 1, + ) + } else { + Text( + text = scheduleUnmatchedLabel().resolve(), + style = TvTypography.caption, + color = if (focused) Color.White else WarningYellow, + maxLines = 1, + ) + } + } + } +} diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleViewModel.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleViewModel.kt new file mode 100644 index 00000000..ebfff8db --- /dev/null +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/schedule/ScheduleViewModel.kt @@ -0,0 +1,168 @@ +package com.miruplay.tv.ui.schedule + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.miruplay.tv.data.schedule.ScheduleLoadResult +import com.miruplay.tv.data.schedule.ScheduleRepository +import com.miruplay.tv.model.Anime +import com.miruplay.tv.model.ScheduleAiring +import com.miruplay.tv.model.ScheduleDay +import com.miruplay.tv.model.ScheduleFetchError +import com.miruplay.tv.model.ScheduleTimeConversion +import com.miruplay.tv.model.displayTitle +import com.miruplay.tv.model.indexAnimeByBangumiId +import com.miruplay.tv.model.matchedAnime +import com.miruplay.tv.repository.MetadataRepository +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import javax.inject.Inject + +data class ScheduleRowUi( + val airing: ScheduleAiring, + val matchedAnimeId: String?, + val matchedAnimeTitle: String?, +) { + val isMatched: Boolean + get() = matchedAnimeId != null +} + +data class ScheduleDayUi( + val weekday: Int, + val isToday: Boolean, + val rows: List, +) + +sealed interface ScheduleUiState { + data object Loading : ScheduleUiState + data object Unconfigured : ScheduleUiState + data object Empty : ScheduleUiState + data class Error(val error: ScheduleFetchError) : ScheduleUiState + data class Content( + val season: String?, + val seasonStart: String?, + val seasonEnd: String?, + val generatedAtLocal: String?, + val localTimezone: String, + val days: List, + val fromCache: Boolean, + val stale: Boolean, + val matchedCount: Int, + val totalCount: Int, + val skippedItemCount: Int, + ) : ScheduleUiState +} + +/** + * 时间表页状态机: + * - 未配置地址 → Unconfigured(引导去设置) + * - 404 / 无可解析条目 → Empty + * - 请求失败且无缓存 → Error(可重试) + * - 成功 → Content(已把 JST 周几/时刻换算成本地时区并按本地时间升序分组) + */ +@HiltViewModel +class ScheduleViewModel @Inject constructor( + private val scheduleRepository: ScheduleRepository, + private val metadataRepository: MetadataRepository, +) : ViewModel() { + + private val _state = MutableStateFlow(ScheduleUiState.Loading) + val state: StateFlow = _state.asStateFlow() + + private var loadJob: Job? = null + + init { + load(forceRefresh = false) + } + + fun refresh() { + load(forceRefresh = true) + } + + fun retry() { + load(forceRefresh = false) + } + + private fun load(forceRefresh: Boolean) { + if (loadJob?.isActive == true) return + loadJob = viewModelScope.launch { + _state.value = ScheduleUiState.Loading + when (val result = scheduleRepository.load(forceRefresh = forceRefresh)) { + ScheduleLoadResult.NotConfigured -> _state.value = ScheduleUiState.Unconfigured + ScheduleLoadResult.Empty -> _state.value = ScheduleUiState.Empty + is ScheduleLoadResult.Failure -> _state.value = ScheduleUiState.Error(result.error) + is ScheduleLoadResult.Success -> _state.value = buildContent(result) + } + } + } + + private suspend fun buildContent( + result: ScheduleLoadResult.Success, + ): ScheduleUiState { + val localZone = ZoneId.systemDefault() + val weekly = withContext(Dispatchers.Default) { + ScheduleTimeConversion.buildWeeklySchedule(result.snapshot, localZone) + } + val animeIndex = metadataRepository.getCachedAnimeWithBangumiId() + .getOrNull() + .orEmpty() + .indexAnimeByBangumiId() + if (weekly.totalCount == 0) { + return ScheduleUiState.Empty + } + + val today = LocalDate.now(localZone).dayOfWeek.value + val days = weekly.days.map { day -> buildDay(day, animeIndex, today) } + val matchedCount = days.sumOf { day -> day.rows.count { it.isMatched } } + return ScheduleUiState.Content( + season = weekly.season, + seasonStart = weekly.seasonStart, + seasonEnd = weekly.seasonEnd, + generatedAtLocal = formatGeneratedAt(weekly.generatedAt, localZone), + localTimezone = weekly.localTimezone, + days = days, + fromCache = result.fromCache, + stale = result.stale, + matchedCount = matchedCount, + totalCount = weekly.totalCount, + skippedItemCount = weekly.skippedItemCount, + ) + } + + private fun buildDay( + day: ScheduleDay, + animeIndex: Map, + today: Int, + ): ScheduleDayUi = ScheduleDayUi( + weekday = day.weekday, + isToday = day.weekday == today, + rows = day.airings.map { airing -> + val anime = airing.matchedAnime(animeIndex) + ScheduleRowUi( + airing = airing, + matchedAnimeId = anime?.id, + matchedAnimeTitle = anime?.displayTitle(), + ) + }, + ) + + private fun formatGeneratedAt(raw: String?, localZone: ZoneId): String? { + val text = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null + val instant = runCatching { Instant.parse(text) }.getOrNull() ?: return null + return GENERATED_AT_FORMATTER.format(instant.atZone(localZone)) + } + + companion object { + private val GENERATED_AT_FORMATTER: DateTimeFormatter = + DateTimeFormatter.ofPattern("MM-dd HH:mm") + } +} 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 37be962d..41bc25d7 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 @@ -79,6 +79,7 @@ import androidx.compose.material.icons.filled.Storage import androidx.compose.material.icons.filled.Subtitles import androidx.compose.material.icons.filled.Sync import androidx.compose.material.icons.filled.Tune +import androidx.compose.material.icons.filled.Tv import androidx.compose.material.icons.filled.Upload import androidx.compose.material.icons.filled.Warning import androidx.compose.material.icons.filled.WifiTethering @@ -325,6 +326,14 @@ import com.miruplay.tv.model.settingsProxyToggleLabel import com.miruplay.tv.model.settingsSaveTokenActionLabel import com.miruplay.tv.model.settingsScreenSubtitleLabel import com.miruplay.tv.model.settingsScreenTitleLabel +import com.miruplay.tv.model.settingsScheduleClearActionLabel +import com.miruplay.tv.model.settingsScheduleCurrentStatus +import com.miruplay.tv.model.settingsScheduleCurrentUnsetStatus +import com.miruplay.tv.model.settingsScheduleOpenScheduleActionLabel +import com.miruplay.tv.model.settingsSchedulePanelDescription +import com.miruplay.tv.model.settingsSchedulePanelTitleLabel +import com.miruplay.tv.model.settingsScheduleSaveActionLabel +import com.miruplay.tv.model.settingsScheduleUrlFieldLabel import com.miruplay.tv.model.settingsWebUiAccessTokenLabel import com.miruplay.tv.model.settingsWebUiAddressLabel import com.miruplay.tv.model.settingsWebUiAvailableAddressesLabel @@ -427,6 +436,7 @@ private fun MiruPlaySettingsSection.androidTvIcon(): ImageVector = when (this) { MiruPlaySettingsSection.WEB_UI -> Icons.Filled.WifiTethering MiruPlaySettingsSection.SOURCES -> Icons.Filled.Storage + MiruPlaySettingsSection.SCHEDULE -> Icons.Filled.Tv MiruPlaySettingsSection.PLAYBACK -> Icons.Filled.PlayArrow MiruPlaySettingsSection.AUDIO_DSP -> Icons.Filled.GraphicEq MiruPlaySettingsSection.CLOUD_DRIVE -> Icons.Filled.Cloud @@ -444,6 +454,7 @@ fun AddSourceScreen( onNavigateBack: () -> Unit, onRestartApp: () -> Unit = {}, onExitApp: () -> Unit = {}, + onNavigateToSchedule: () -> Unit = {}, viewModel: SettingsViewModel = hiltViewModel() ) { val context = LocalContext.current @@ -698,6 +709,7 @@ fun AddSourceScreen( hasTmdbToken = savedTmdbToken.isNotBlank() || tmdbTokenSaved, appVersionName = appAboutInfo.versionName, appMode = currentAppMode.storageValue, + viewModel = viewModel, menuFocusRequesters = menuFocusRequesters, onSectionSelected = { selectedSection = it }, modifier = Modifier @@ -920,6 +932,8 @@ fun AddSourceScreen( rssProxyPort = rssProxyPort, onRssProxyPortChange = { rssProxyPort = it.filter(Char::isDigit).take(5) }, proxyStatusMessage = proxyStatusMessage, + scheduleViewModel = viewModel, + onOpenSchedule = onNavigateToSchedule, rssSubscriptions = rssSubscriptions, rssName = rssName, onRssNameChange = { rssName = it }, @@ -1140,10 +1154,12 @@ private fun SettingsMenuPanel( hasTmdbToken: Boolean, appVersionName: String, appMode: String, + viewModel: SettingsViewModel, menuFocusRequesters: Map, onSectionSelected: (MiruPlaySettingsSection) -> Unit, modifier: Modifier = Modifier ) { + val scheduleConfigured by viewModel.scheduleConfigured.collectAsStateWithLifecycle() val menuSummaryInput = SettingsSectionMenuSummaryInput( webUiAddressCount = webUiAddressCount, sourceCount = sourcesCount, @@ -1163,6 +1179,7 @@ private fun SettingsMenuPanel( proxyEnabled = proxyEnabled, proxyHost = proxyHost, proxyPort = proxyPort, + scheduleConfigured = scheduleConfigured, autoScanEnabled = autoScanEnabled, mergeSameAnimeEnabled = mergeSameAnimeEnabled, posterWallArrangement = posterWallArrangement, @@ -1430,6 +1447,8 @@ private fun SettingsContent( rssProxyPort: String, onRssProxyPortChange: (String) -> Unit, proxyStatusMessage: UiMessage, + scheduleViewModel: SettingsViewModel, + onOpenSchedule: () -> Unit, rssSubscriptions: List, rssName: String, onRssNameChange: (String) -> Unit, @@ -1605,6 +1624,16 @@ private fun SettingsContent( ) } + MiruPlaySettingsSection.SCHEDULE -> SettingsSingleSectionPage( + section = selectedSection, + modifier = modifier + ) { + ScheduleSourcePanel( + viewModel = scheduleViewModel, + onOpenSchedule = onOpenSchedule, + ) + } + MiruPlaySettingsSection.SCAN -> SettingsSingleSectionPage( section = selectedSection, modifier = modifier @@ -4693,6 +4722,91 @@ private fun ProxySettingsPanel( } } +@Composable +private fun ScheduleSourcePanel( + viewModel: SettingsViewModel, + onOpenSchedule: () -> Unit, +) { + // 状态收集/草稿都留在子组合里:AddSourceScreen 本体已经太大,继续往它的 + // 主组合 lambda 里加捕获的 State 会触发 D8 校验失败(settings 页 VerifyError)。 + val storedDataSourceUrl by viewModel.scheduleDataSourceUrl.collectAsStateWithLifecycle() + val statusMessage by viewModel.scheduleStatusMessage.collectAsStateWithLifecycle() + var dataSourceUrl by remember { mutableStateOf("") } + LaunchedEffect(storedDataSourceUrl) { + dataSourceUrl = storedDataSourceUrl + } + SettingsPanel { + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Filled.Tv, + contentDescription = null, + tint = TextPrimary, + modifier = Modifier.size(26.dp) + ) + Spacer(Modifier.width(10.dp)) + Text( + text = settingsSchedulePanelTitleLabel().resolve(), + style = TvTypography.subtitle, + color = TextPrimary + ) + } + + Spacer(Modifier.height(6.dp)) + Text( + text = settingsSchedulePanelDescription().resolve(), + style = TvTypography.body, + color = TextSecondary + ) + + Spacer(Modifier.height(16.dp)) + TvTextField( + value = dataSourceUrl, + onValueChange = { dataSourceUrl = it }, + label = settingsScheduleUrlFieldLabel().resolve(), + modifier = Modifier.fillMaxWidth(), + ) + + Spacer(Modifier.height(14.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + TvButton( + text = settingsScheduleSaveActionLabel().resolve(), + icon = Icons.Filled.Save, + enabled = dataSourceUrl.isNotBlank(), + onClick = { viewModel.saveScheduleDataSourceUrl(dataSourceUrl) } + ) + TvButton( + text = settingsScheduleOpenScheduleActionLabel().resolve(), + icon = Icons.Filled.Tv, + onClick = onOpenSchedule, + secondary = true + ) + TvButton( + text = settingsScheduleClearActionLabel().resolve(), + icon = Icons.Filled.Delete, + enabled = dataSourceUrl.isNotBlank(), + onClick = viewModel::clearScheduleDataSourceUrl, + secondary = true + ) + } + + Spacer(Modifier.height(8.dp)) + StatusMessage( + icon = Icons.Filled.Tv, + text = if (dataSourceUrl.isBlank()) { + settingsScheduleCurrentUnsetStatus().resolve() + } else { + settingsScheduleCurrentStatus(dataSourceUrl.trim()).resolve() + }, + color = TextSecondary + ) + StatusMessage( + icon = Icons.Filled.Refresh, + text = statusMessage.text.resolve(), + color = if (statusMessage is UiMessage.Error) WarningYellow else ProgressGreen + ) + } +} + @Composable private fun BangumiOAuthSection( hasToken: Boolean, diff --git a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/SettingsViewModel.kt b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/SettingsViewModel.kt index f822c820..c601544d 100644 --- a/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/SettingsViewModel.kt +++ b/ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/SettingsViewModel.kt @@ -16,6 +16,7 @@ import com.miruplay.tv.core.common.WebControlConfig import com.miruplay.tv.core.common.logging.MiruLog import com.miruplay.tv.data.preferences.ScanPreferencesManager import com.miruplay.tv.data.preferences.PlaybackPreferencesManager +import com.miruplay.tv.data.schedule.ScheduleRepository import com.miruplay.tv.model.EpisodeVersionSelectionPolicy import com.miruplay.tv.model.FormatAwareToneMappingPreferences import com.miruplay.tv.model.AudioDspBand @@ -122,6 +123,9 @@ import com.miruplay.tv.model.settingsAppUpdateReadyStatus import com.miruplay.tv.model.settingsAndroidTvLogUploadStatusMessage import com.miruplay.tv.model.settingsLogUploadStatusMessage import com.miruplay.tv.model.settingsProxySavedStatus +import com.miruplay.tv.model.settingsScheduleClearedStatus +import com.miruplay.tv.model.settingsScheduleInvalidUrlStatus +import com.miruplay.tv.model.settingsScheduleSavedStatus import com.miruplay.tv.model.validateCloudDriveApiTokenForm import com.miruplay.tv.model.validateCloudDriveLoginForm import dagger.hilt.android.lifecycle.HiltViewModel @@ -163,6 +167,7 @@ class SettingsViewModel @Inject constructor( private val cloudDriveClient: CloudDriveClient, private val cloudDriveEngine: CloudDriveRssAutomationEngine, private val cloudDriveScheduler: CloudDriveRssScheduler, + private val scheduleRepository: ScheduleRepository, private val bangumiArchiveStore: BangumiArchiveStore, private val backgroundTasks: BackgroundTaskForegroundController, private val audioDspRuntimeConfig: AudioDspRuntimeConfig, @@ -606,6 +611,18 @@ class SettingsViewModel @Inject constructor( MutableStateFlow(settingsProxySavedStatus().asInfo()) val proxyStatusMessage: StateFlow = _proxyStatusMessage.asStateFlow() + private val _scheduleDataSourceUrl = + MutableStateFlow(scheduleRepository.rawConfiguredUrl()) + val scheduleDataSourceUrl: StateFlow = _scheduleDataSourceUrl.asStateFlow() + + private val _scheduleConfigured = + MutableStateFlow(scheduleRepository.configuredUrlOrNull() != null) + val scheduleConfigured: StateFlow = _scheduleConfigured.asStateFlow() + + private val _scheduleStatusMessage = + MutableStateFlow(settingsScheduleSavedStatus().asInfo()) + val scheduleStatusMessage: StateFlow = _scheduleStatusMessage.asStateFlow() + init { loadSources() loadAppMode() @@ -861,6 +878,23 @@ class SettingsViewModel @Inject constructor( } } + fun saveScheduleDataSourceUrl(rawUrl: String) { + if (scheduleRepository.saveDataSourceUrl(rawUrl)) { + _scheduleDataSourceUrl.value = scheduleRepository.rawConfiguredUrl() + _scheduleConfigured.value = true + _scheduleStatusMessage.value = settingsScheduleSavedStatus().asInfo() + } else { + _scheduleStatusMessage.value = settingsScheduleInvalidUrlStatus().asError() + } + } + + fun clearScheduleDataSourceUrl() { + scheduleRepository.clearDataSourceUrl() + _scheduleDataSourceUrl.value = "" + _scheduleConfigured.value = false + _scheduleStatusMessage.value = settingsScheduleClearedStatus().asInfo() + } + fun refreshBangumiArchive() { viewModelScope.launch(Dispatchers.IO) { _bangumiArchiveState.value = bangumiArchiveStore.snapshot().toBangumiArchiveUiState( diff --git a/ui-tv/src/main/res/values-en-rGB/strings.xml b/ui-tv/src/main/res/values-en-rGB/strings.xml index 3249c228..0e95b5ab 100644 --- a/ui-tv/src/main/res/values-en-rGB/strings.xml +++ b/ui-tv/src/main/res/values-en-rGB/strings.xml @@ -6,4 +6,65 @@ %1$s; last run: %2$s submitted, %3$s skipped, %4$s failed, %5$s organised. organised %1$s Downloading, organising and scanning subscriptions + Anime Schedule + Data source and weekly air times + Configured + Not configured + Anime Schedule + After setting the schedule service address, open the weekly schedule from the library top bar. The address is stored on this device only. + Schedule service address + Save address + Clear address + Schedule address saved. + Schedule address cleared. + Invalid address: enter a full URL starting with http:// or https://. + No schedule address configured yet. + Current address: %1$s + Open schedule + Schedule + Anime Schedule + Weekly air times · converted to device time zone + Loading schedule… + Schedule service not configured + Set the service address in Settings → Anime Schedule to see weekly air times here. + Open settings + No airing data yet + The service has not published this season schedule yet. Try again later. + Failed to load schedule + The data source address is invalid. Please update it in Settings. + Network unavailable. Check your connection and retry. + Request timed out. Please retry. + Service returned an error (HTTP %1$d). + Unrecognized schedule data format. Please check the data source address. + Retry + Refresh + Back + %1$s · %2$s to %3$s + Updated %1$s + Device time zone: %1$s + Today + Mon + Tue + Wed + Thu + Fri + Sat + Sun + %1$s %2$s + Japan time %1$s %2$s + next day + prev day + High confidence + Medium confidence + Low confidence + Unknown confidence + %1$d sources + In library + Not in library + Press OK to open details + Library match %1$d/%2$d + Cached + Network unavailable, showing cached data. + %1$d items skipped (unparseable time). + No anime today diff --git a/ui-tv/src/main/res/values-en/strings.xml b/ui-tv/src/main/res/values-en/strings.xml index 497b534c..2b9964ad 100644 --- a/ui-tv/src/main/res/values-en/strings.xml +++ b/ui-tv/src/main/res/values-en/strings.xml @@ -1161,4 +1161,65 @@ Russian Portuguese Music + Anime Schedule + Data source and weekly air times + Configured + Not configured + Anime Schedule + After setting the schedule service address, open the weekly schedule from the library top bar. The address is stored on this device only. + Schedule service address + Save address + Clear address + Schedule address saved. + Schedule address cleared. + Invalid address: enter a full URL starting with http:// or https://. + No schedule address configured yet. + Current address: %1$s + Open schedule + Schedule + Anime Schedule + Weekly air times · converted to device time zone + Loading schedule… + Schedule service not configured + Set the service address in Settings → Anime Schedule to see weekly air times here. + Open settings + No airing data yet + The service has not published this season schedule yet. Try again later. + Failed to load schedule + The data source address is invalid. Please update it in Settings. + Network unavailable. Check your connection and retry. + Request timed out. Please retry. + Service returned an error (HTTP %1$d). + Unrecognized schedule data format. Please check the data source address. + Retry + Refresh + Back + %1$s · %2$s to %3$s + Updated %1$s + Device time zone: %1$s + Today + Mon + Tue + Wed + Thu + Fri + Sat + Sun + %1$s %2$s + Japan time %1$s %2$s + next day + prev day + High confidence + Medium confidence + Low confidence + Unknown confidence + %1$d sources + In library + Not in library + Press OK to open details + Library match %1$d/%2$d + Cached + Network unavailable, showing cached data. + %1$d items skipped (unparseable time). + No anime today 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 afae023e..0232df40 100644 --- a/ui-tv/src/main/res/values-zh-rHK/strings.xml +++ b/ui-tv/src/main/res/values-zh-rHK/strings.xml @@ -1161,4 +1161,65 @@ 俄文 葡萄牙文 音樂 + 新番時間表 + 資料來源與每週播出時間 + 已設定 + 未設定 + 新番時間表 + 填入時間表服務位址後,媒體庫頂欄可開啟每週新番表。位址只儲存在本機。 + 時間表服務位址 + 儲存位址 + 清除位址 + 時間表位址已儲存。 + 時間表位址已清除。 + 位址無效:需要以 http:// 或 https:// 開頭的完整位址。 + 尚未設定時間表位址。 + 目前位址:%1$s + 開啟時間表 + 時間表 + 新番時間表 + 每週播出時間 · 已換算為裝置時區 + 正在取得時間表… + 尚未設定時間表服務 + 到「設定 → 新番時間表」填入服務位址後,這裡會顯示每週播出時間。 + 前往設定 + 暫無播出資料 + 服務端尚未發布本季時間表,請稍後再試。 + 時間表取得失敗 + 資料來源位址無效,請到設定重新填寫。 + 網絡不可用,請檢查網絡後重試。 + 請求逾時,請稍後重試。 + 服務回傳錯誤(HTTP %1$d)。 + 無法辨識時間表資料格式,請確認資料來源位址。 + 重試 + 重新整理 + 返回 + %1$s · %2$s 至 %3$s + 更新於 %1$s + 裝置時區:%1$s + 今天 + 週一 + 週二 + 週三 + 週四 + 週五 + 週六 + 週日 + %1$s %2$s + 日本時間 %1$s %2$s + 次日 + 前日 + 置信度高 + 置信度中 + 置信度低 + 置信度未知 + %1$d 個來源 + 已匹配媒體庫 + 未在媒體庫 + 按確定開啟詳情 + 媒體庫匹配 %1$d/%2$d + 快取 + 網絡不可用,正在顯示上次快取的資料。 + %1$d 筆資料時間無法解析,已略過。 + 本日無新番 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 812c1944..f6777251 100644 --- a/ui-tv/src/main/res/values-zh-rTW/strings.xml +++ b/ui-tv/src/main/res/values-zh-rTW/strings.xml @@ -1161,4 +1161,65 @@ 俄語 葡萄牙語 音樂 + 新番時間表 + 資料來源與每週播出時間 + 已設定 + 未設定 + 新番時間表 + 填入時間表服務位址後,媒體庫頂欄可開啟每週新番表。位址只儲存在本機。 + 時間表服務位址 + 儲存位址 + 清除位址 + 時間表位址已儲存。 + 時間表位址已清除。 + 位址無效:需要以 http:// 或 https:// 開頭的完整位址。 + 尚未設定時間表位址。 + 目前位址:%1$s + 開啟時間表 + 時間表 + 新番時間表 + 每週播出時間 · 已換算為裝置時區 + 正在取得時間表… + 尚未設定時間表服務 + 到「設定 → 新番時間表」填入服務位址後,這裡會顯示每週播出時間。 + 前往設定 + 暫無播出資料 + 服務端尚未發布本季時間表,請稍後再試。 + 時間表取得失敗 + 資料來源位址無效,請到設定重新填寫。 + 網路無法使用,請檢查網路後重試。 + 請求逾時,請稍後重試。 + 服務回傳錯誤(HTTP %1$d)。 + 無法辨識時間表資料格式,請確認資料來源位址。 + 重試 + 重新整理 + 返回 + %1$s · %2$s 至 %3$s + 更新於 %1$s + 裝置時區:%1$s + 今天 + 週一 + 週二 + 週三 + 週四 + 週五 + 週六 + 週日 + %1$s %2$s + 日本時間 %1$s %2$s + 次日 + 前日 + 置信度高 + 置信度中 + 置信度低 + 置信度未知 + %1$d 個來源 + 已匹配媒體庫 + 未在媒體庫 + 按確定開啟詳情 + 媒體庫匹配 %1$d/%2$d + 快取 + 網路無法使用,正在顯示上次快取的資料。 + %1$d 筆資料時間無法解析,已略過。 + 本日無新番 diff --git a/ui-tv/src/main/res/values/strings.xml b/ui-tv/src/main/res/values/strings.xml index dc4f18b9..00ac7eb5 100644 --- a/ui-tv/src/main/res/values/strings.xml +++ b/ui-tv/src/main/res/values/strings.xml @@ -1163,4 +1163,65 @@ 俄语 葡萄牙语 音乐 + 新番时间表 + 数据源与每周播出时间 + 已配置 + 未配置 + 新番时间表 + 填入时间表服务地址后,媒体库顶栏可打开每周新番表。地址只保存在本机。 + 时间表服务地址 + 保存地址 + 清除地址 + 时间表地址已保存。 + 时间表地址已清除。 + 地址无效:需要以 http:// 或 https:// 开头的完整地址。 + 尚未配置时间表地址。 + 当前地址:%1$s + 打开时间表 + 时间表 + 新番时间表 + 每周播出时间 · 已换算到设备时区 + 正在获取时间表… + 尚未配置时间表服务 + 到「设置 → 新番时间表」填入服务地址后,这里会显示每周播出时间。 + 去设置 + 暂无播出数据 + 服务端还没有发布本季时间表,稍后再试。 + 时间表获取失败 + 数据源地址无效,请到设置里重新填写。 + 网络不可用,请检查网络后重试。 + 请求超时,请稍后重试。 + 服务返回错误(HTTP %1$d)。 + 时间表数据格式无法识别,请确认数据源地址。 + 重试 + 刷新 + 返回 + %1$s · %2$s 至 %3$s + 更新于 %1$s + 设备时区:%1$s + 今天 + 周一 + 周二 + 周三 + 周四 + 周五 + 周六 + 周日 + %1$s %2$s + 日本时间 %1$s %2$s + 次日 + 前日 + 置信度高 + 置信度中 + 置信度低 + 置信度未知 + %1$d 个来源 + 已匹配媒体库 + 未在媒体库 + 按确定打开详情 + 媒体库匹配 %1$d/%2$d + 缓存 + 网络不可用,正在显示上次缓存的数据。 + %1$d 条数据时间无法解析,已跳过。 + 本日无新番 \ No newline at end of file diff --git a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/SettingsViewModelTokenTest.kt b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/SettingsViewModelTokenTest.kt index 39619153..9cc924b7 100644 --- a/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/SettingsViewModelTokenTest.kt +++ b/ui-tv/src/test/kotlin/com/miruplay/tv/ui/settings/SettingsViewModelTokenTest.kt @@ -74,6 +74,7 @@ class SettingsViewModelTokenTest { @MockK lateinit var bangumiSyncEngine: BangumiSyncEngine @MockK lateinit var bangumiOAuth: com.miruplay.tv.sync.BangumiOAuthCoordinator @MockK lateinit var backgroundTasks: BackgroundTaskForegroundController + @MockK lateinit var scheduleRepository: com.miruplay.tv.data.schedule.ScheduleRepository private val logStatus = MutableStateFlow(LogUploadStatus()) @@ -116,6 +117,9 @@ class SettingsViewModelTokenTest { every { webControlPreferences.webControlEnabled } returns false every { webControlPreferences.accessToken } returns "test-token" + every { scheduleRepository.rawConfiguredUrl() } returns "" + every { scheduleRepository.configuredUrlOrNull() } returns null + every { cloudDriveRepository.observeConfig() } returns emptyFlow() every { cloudDriveRepository.observeSubscriptions() } returns emptyFlow() @@ -260,6 +264,7 @@ class SettingsViewModelTokenTest { cloudDriveClient = cloudDriveClient, cloudDriveEngine = cloudDriveEngine, cloudDriveScheduler = cloudDriveScheduler, + scheduleRepository = scheduleRepository, bangumiArchiveStore = bangumiArchiveStore, bangumiSyncEngine = bangumiSyncEngine, bangumiOAuth = bangumiOAuth, diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt index 42b10e24..11151721 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt @@ -258,6 +258,13 @@ open class NanoHttpWebControlServer( val request = parseBody(session, ScanSettingsRequest.serializer()) jsonResponse(ScanSettingsDto.serializer(), webControlService.saveScanSettings(request)) } + session.method == Method.GET && route == "/api/settings/schedule" -> { + jsonResponse(ScheduleSettingsDto.serializer(), webControlService.getScheduleSettings()) + } + session.method == Method.PUT && route == "/api/settings/schedule" -> { + val request = parseBody(session, ScheduleSettingsRequest.serializer()) + jsonResponse(ScheduleSettingsDto.serializer(), webControlService.saveScheduleSettings(request)) + } session.method == Method.GET && route == "/api/settings/playback" -> { jsonResponse(PlaybackSettingsDto.serializer(), webControlService.getPlaybackSettings()) } diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt index 857be718..c2e24951 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt @@ -86,6 +86,8 @@ interface WebControlEndpointService { throw UnsupportedOperationException("扫描设置 not supported") suspend fun saveScanSettings(request: ScanSettingsRequest): ScanSettingsDto = throw UnsupportedOperationException("扫描设置 not supported") + suspend fun getScheduleSettings(): ScheduleSettingsDto = ScheduleSettingsDto() + suspend fun saveScheduleSettings(request: ScheduleSettingsRequest): ScheduleSettingsDto = ScheduleSettingsDto() suspend fun getPlaybackSettings(): PlaybackSettingsDto = throw UnsupportedOperationException("播放设置 not supported") suspend fun savePlaybackSettings(request: PlaybackSettingsRequest): PlaybackSettingsDto = diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt index 197145ad..d53d9393 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt @@ -337,6 +337,17 @@ data class ScanSettingsRequest( val currentAppMode: String? = null, ) +@Serializable +data class ScheduleSettingsDto( + val dataSourceUrl: String = "", + val configured: Boolean = false, +) + +@Serializable +data class ScheduleSettingsRequest( + val dataSourceUrl: String = "", +) + @Serializable data class PlaybackBackendOptionDto( val value: String, diff --git a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlScheduleSettingsRouteTest.kt b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlScheduleSettingsRouteTest.kt new file mode 100644 index 00000000..080d0958 --- /dev/null +++ b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlScheduleSettingsRouteTest.kt @@ -0,0 +1,184 @@ +package com.miruplay.tv.webcontrol + +import com.miruplay.tv.repository.WebControlAccessManager +import fi.iki.elonen.NanoHTTPD +import java.io.ByteArrayInputStream +import java.io.Closeable +import java.io.InputStream +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Route tests for the 新番时间表 data-source settings endpoints. */ +class WebControlScheduleSettingsRouteTest { + + @Test + fun `GET schedule settings returns unconfigured by default`() { + val service = ScheduleSettingsStubService() + val server = serverFor(service) + + val response = server.serve(FakeSession(method = NanoHTTPD.Method.GET, uri = "/api/settings/schedule")) + + assertEquals(NanoHTTPD.Response.Status.OK, response.status) + val body = response.bodyText() + assertTrue(body.contains("\"dataSourceUrl\":\"\"")) + assertTrue(body.contains("\"configured\":false")) + } + + @Test + fun `PUT schedule settings normalizes trailing slash and reports configured`() { + val service = ScheduleSettingsStubService() + val server = serverFor(service) + + val response = server.serve( + FakeSession( + method = NanoHTTPD.Method.PUT, + uri = "/api/settings/schedule", + body = """{"dataSourceUrl":"https://example.com/"}""", + ) + ) + + assertEquals(NanoHTTPD.Response.Status.OK, response.status) + assertEquals("https://example.com/", service.captured?.dataSourceUrl) + val body = response.bodyText() + assertTrue(body.contains("\"dataSourceUrl\":\"https://example.com\"")) + assertTrue(body.contains("\"configured\":true")) + assertEquals("https://example.com", service.dataSourceUrl) + } + + @Test + fun `PUT invalid schedule settings returns 400 and keeps previous url`() { + val service = ScheduleSettingsStubService() + val server = serverFor(service) + + val saved = server.serve( + FakeSession( + method = NanoHTTPD.Method.PUT, + uri = "/api/settings/schedule", + body = """{"dataSourceUrl":"https://example.com"}""", + ) + ) + assertEquals(NanoHTTPD.Response.Status.OK, saved.status) + + val invalid = server.serve( + FakeSession( + method = NanoHTTPD.Method.PUT, + uri = "/api/settings/schedule", + body = """{"dataSourceUrl":"not-a-url"}""", + ) + ) + assertEquals(NanoHTTPD.Response.Status.BAD_REQUEST, invalid.status) + assertTrue(invalid.bodyText().contains("地址无效")) + assertEquals("https://example.com", service.dataSourceUrl) + assertTrue(service.configured) + } + + @Test + fun `PUT empty schedule settings clears the stored url`() { + val service = ScheduleSettingsStubService() + val server = serverFor(service) + server.serve( + FakeSession( + method = NanoHTTPD.Method.PUT, + uri = "/api/settings/schedule", + body = """{"dataSourceUrl":"https://example.com"}""", + ) + ) + + val cleared = server.serve( + FakeSession( + method = NanoHTTPD.Method.PUT, + uri = "/api/settings/schedule", + body = """{"dataSourceUrl":""}""", + ) + ) + + assertEquals(NanoHTTPD.Response.Status.OK, cleared.status) + assertEquals("", service.dataSourceUrl) + assertEquals(false, service.configured) + assertTrue(cleared.bodyText().contains("\"configured\":false")) + } + + private fun serverFor(service: ScheduleSettingsStubService): NanoHttpWebControlServer = + NanoHttpWebControlServer( + webControlService = service, + webControlAccess = EnabledWebControlAccess, + staticAssets = WebControlStaticAssets { null }, + ) + + private class ScheduleSettingsStubService : EmptyWebControlEndpointService() { + var dataSourceUrl: String = "" + var configured: Boolean = false + var captured: ScheduleSettingsRequest? = null + + override suspend fun getScheduleSettings(): ScheduleSettingsDto = + ScheduleSettingsDto(dataSourceUrl = dataSourceUrl, configured = configured) + + override suspend fun saveScheduleSettings(request: ScheduleSettingsRequest): ScheduleSettingsDto { + captured = request + val rawUrl = request.dataSourceUrl.trim() + if (rawUrl.isEmpty()) { + dataSourceUrl = "" + configured = false + return getScheduleSettings() + } + val normalized = normalize(rawUrl) + ?: throw IllegalArgumentException("时间表数据源地址无效,请填写 http:// 或 https:// 开头的完整地址") + dataSourceUrl = normalized + configured = true + return getScheduleSettings() + } + + private fun normalize(rawUrl: String): String? { + if (rawUrl.any { it.isWhitespace() }) return null + val uri = runCatching { java.net.URI(rawUrl) }.getOrNull() ?: return null + val scheme = uri.scheme?.lowercase() + if (scheme != "http" && scheme != "https") return null + if (uri.host.isNullOrBlank()) return null + if (uri.rawQuery != null || uri.rawFragment != null) return null + return rawUrl.trimEnd('/').takeIf { it.isNotEmpty() } + } + } + + private object EnabledWebControlAccess : WebControlAccessManager { + override var webControlEnabled: Boolean = true + override val accessToken: String = "token" + override fun rotateAccessToken(): String = accessToken + override fun addEnabledChangeListener(onChanged: (Boolean) -> Unit): Closeable = Closeable { } + } + + private fun NanoHTTPD.Response.bodyText(): String { + val size = this.data.available().coerceAtLeast(0) + val bytes = ByteArray(size) + this.data.read(bytes) + return String(bytes, Charsets.UTF_8) + } + + private class FakeSession( + private val method: NanoHTTPD.Method, + private val uri: String, + body: String = "", + ) : NanoHTTPD.IHTTPSession { + private val bodyBytes = body.toByteArray(Charsets.UTF_8) + private val headers = mapOf( + "content-type" to "application/json", + "content-length" to bodyBytes.size.toString(), + "x-miruplay-token" to "token", + ) + + override fun execute() = Unit + override fun getCookies(): NanoHTTPD.CookieHandler = throw UnsupportedOperationException() + override fun getHeaders(): Map = headers + override fun getInputStream(): InputStream = ByteArrayInputStream(bodyBytes) + override fun getMethod(): NanoHTTPD.Method = method + @Suppress("OVERRIDE_DEPRECATION") + override fun getParms(): Map = emptyMap() + override fun getParameters(): Map> = emptyMap() + override fun getQueryParameterString(): String? = null + override fun getUri(): String = uri + @Suppress("OVERRIDE_DEPRECATION") + override fun parseBody(files: MutableMap) = Unit + override fun getRemoteIpAddress(): String = "127.0.0.1" + override fun getRemoteHostName(): String = "localhost" + } +} diff --git a/web-control/build.gradle.kts b/web-control/build.gradle.kts index 23739799..4a0b5e0f 100644 --- a/web-control/build.gradle.kts +++ b/web-control/build.gradle.kts @@ -82,6 +82,7 @@ dependencies { api(project(":core:model")) implementation(project(":core:common")) implementation(project(":repository-api")) + implementation(project(":data")) implementation(project(":cloud-drive")) implementation(project(":player-core")) implementation(project(":scanner")) diff --git a/web-control/frontend/src/App.vue b/web-control/frontend/src/App.vue index 842c8074..74f487bc 100644 --- a/web-control/frontend/src/App.vue +++ b/web-control/frontend/src/App.vue @@ -559,6 +559,77 @@ +
+ + + + + + + + +

+ 填写 AirRadar 兼容的时间表服务地址(http/https)。地址只保存在电视本机,不会上传。 +

+ +
+ + 保存地址 + + + 清除地址 + + + 刷新 + +
+
+
+ + + +
+
+ 数据源 + {{ scheduleForm.configured ? '已配置' : '未配置' }} +
+
+ 地址 + {{ scheduleForm.dataSourceUrl || '未填写' }} +
+
+ 保存位置 + 仅本机 +
+
+
+
+