From ce7558b191bfb71a14170cd9f77d1311a065b024 Mon Sep 17 00:00:00 2001 From: Priveetee <138765817+Priveetee@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:16:11 +0100 Subject: [PATCH 1/8] feat: read Twitch chat emotes, badges and colors --- .../data/livechat/TwitchChatSseParser.kt | 6 + .../data/twitch/RemoteTwitchRepository.kt | 16 +++ .../android/data/twitch/TwitchMappers.kt | 21 ++++ .../data/stream/FakeTwitchRepository.kt | 2 + .../android/domain/livechat/LiveChat.kt | 5 + .../domain/livechat/TwitchChatColor.kt | 52 ++++++++ .../domain/livechat/TwitchChatParts.kt | 118 ++++++++++++++++++ .../android/domain/twitch/TwitchModels.kt | 19 +++ .../android/domain/twitch/TwitchRepository.kt | 2 + .../domain/livechat/TwitchChatPartsTest.kt | 55 ++++++++ 10 files changed, 296 insertions(+) create mode 100644 core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatColor.kt create mode 100644 core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatParts.kt create mode 100644 core/model/src/test/java/dev/typetype/android/domain/livechat/TwitchChatPartsTest.kt diff --git a/core/data/src/main/java/dev/typetype/android/data/livechat/TwitchChatSseParser.kt b/core/data/src/main/java/dev/typetype/android/data/livechat/TwitchChatSseParser.kt index c90d128f..dd448306 100644 --- a/core/data/src/main/java/dev/typetype/android/data/livechat/TwitchChatSseParser.kt +++ b/core/data/src/main/java/dev/typetype/android/data/livechat/TwitchChatSseParser.kt @@ -1,5 +1,6 @@ package dev.typetype.android.data.livechat +import dev.typetype.android.domain.livechat.ChatEmoteRange import dev.typetype.android.data.network.dto.TwitchChatEventDto import dev.typetype.android.domain.livechat.LiveChatEvent import dev.typetype.android.domain.livechat.LiveChatMessage @@ -32,6 +33,11 @@ internal class TwitchChatSseParser(private val json: Json) { authorName = event.displayName?.ifBlank { null } ?: event.login, authorAvatarUrl = null, moderator = event.badges.any { it.startsWith("moderator/") || it.startsWith("broadcaster/") }, + login = event.login, + color = event.color, + emotes = event.emotes.map { ChatEmoteRange(it.id, it.start, it.end) }, + badges = event.badges, + action = event.action, ), ) } diff --git a/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchRepository.kt b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchRepository.kt index 8578ae91..d195cd16 100644 --- a/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchRepository.kt +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchRepository.kt @@ -1,5 +1,9 @@ package dev.typetype.android.data.twitch +import dev.typetype.android.data.network.dto.TwitchChatAssetsDto +import dev.typetype.android.domain.twitch.TwitchChatAssets +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import dev.typetype.android.core.error.suspendRunCatching import dev.typetype.android.data.account.ActiveAccountScope import dev.typetype.android.data.network.TypeTypeApi @@ -30,6 +34,9 @@ class RemoteTwitchRepository @Inject constructor( private val activeAccountScope: ActiveAccountScope, private val serverRepository: ServerRepository, ) : TwitchRepository { + @Volatile + private var globalChatAssets: TwitchChatAssetsDto? = null + override suspend fun popular(cursor: String?): Result> = call { twitchStreams(cursor) }.map { page -> page.map { it.toVideo() } } @@ -101,6 +108,15 @@ class RemoteTwitchRepository @Inject constructor( override suspend fun chatHighlights(login: String): Result = call { twitchChatHighlights(login) }.map { it.toDomain() } + // The global set is the same for every channel and large: it is fetched once per app run. + override suspend fun chatAssets(login: String): Result = suspendRunCatching { + coroutineScope { + val global = async { globalChatAssets ?: call { twitchChatAssets() }.getOrNull()?.also { globalChatAssets = it } } + val channel = async { call { twitchChannelChatAssets(segment(login)) }.getOrNull() } + mergeChatAssets(channel.await(), global.await()) + } + } + override suspend fun videoComments(id: String, offsetSeconds: Long?, cursor: String?): Result> = call { twitchVideoComments(segment(id), offset = offsetSeconds.takeIf { cursor == null }, cursor = cursor) } .map { page -> page.map { it.toDomain() } } diff --git a/core/data/src/main/java/dev/typetype/android/data/twitch/TwitchMappers.kt b/core/data/src/main/java/dev/typetype/android/data/twitch/TwitchMappers.kt index 0fd65115..bee9f1a1 100644 --- a/core/data/src/main/java/dev/typetype/android/data/twitch/TwitchMappers.kt +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/TwitchMappers.kt @@ -1,5 +1,10 @@ package dev.typetype.android.data.twitch +import dev.typetype.android.data.network.dto.TwitchChatAssetsDto +import dev.typetype.android.domain.livechat.ChatEmote +import dev.typetype.android.domain.livechat.ChatImage +import dev.typetype.android.domain.twitch.TwitchChatAssets +import dev.typetype.android.domain.twitch.TwitchLiveInfo import dev.typetype.android.data.network.dto.TwitchChannelDto import dev.typetype.android.data.network.dto.TwitchChatHighlightsDto import dev.typetype.android.data.network.dto.TwitchClipDto @@ -64,8 +69,24 @@ internal fun TwitchChannelDto.toChannel(): TwitchChannel = TwitchChannel( bannerUrl = bannerUrl?.ifBlank { null }, followers = followers, live = live?.toVideo(), + liveInfo = live?.let { + TwitchLiveInfo(it.title, it.viewers, twitchMillis(it.startedAt), it.game?.name?.ifBlank { null }, it.tags) + }, ) +internal fun mergeChatAssets(channel: TwitchChatAssetsDto?, global: TwitchChatAssetsDto?): TwitchChatAssets { + val emotes = LinkedHashMap() + for (emote in channel?.emotes.orEmpty() + global?.emotes.orEmpty()) { + if (emote.name.isBlank() || emote.url.isBlank()) continue + emotes.putIfAbsent(emote.name, ChatEmote(emote.name, emote.url2x ?: emote.url, emote.zeroWidth)) + } + val badges = HashMap() + for ((id, badge) in global?.badges.orEmpty() + channel?.badges.orEmpty()) { + if (badge.url.isNotBlank()) badges[id] = ChatImage(badge.title, badge.url2x ?: badge.url) + } + return TwitchChatAssets(emotes, badges) +} + internal fun TwitchGameDto.toCategory(): TwitchCategory = TwitchCategory(id = id, name = name, slug = slug, boxArtUrl = boxArtUrl?.ifBlank { null }, viewers = viewers) diff --git a/core/data/src/test/java/dev/typetype/android/data/stream/FakeTwitchRepository.kt b/core/data/src/test/java/dev/typetype/android/data/stream/FakeTwitchRepository.kt index 98a6958d..8c2cf636 100644 --- a/core/data/src/test/java/dev/typetype/android/data/stream/FakeTwitchRepository.kt +++ b/core/data/src/test/java/dev/typetype/android/data/stream/FakeTwitchRepository.kt @@ -1,5 +1,6 @@ package dev.typetype.android.data.stream +import dev.typetype.android.domain.twitch.TwitchChatAssets import dev.typetype.android.domain.feed.Video import dev.typetype.android.domain.stream.Chapter import dev.typetype.android.domain.twitch.TwitchCategory @@ -32,4 +33,5 @@ internal class FakeTwitchRepository( override suspend fun videoComments(id: String, offsetSeconds: Long?, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) override suspend fun chatHighlights(login: String): Result = Result.success(TwitchChatHighlights(null, null)) + override suspend fun chatAssets(login: String): Result = Result.success(TwitchChatAssets()) } diff --git a/core/model/src/main/java/dev/typetype/android/domain/livechat/LiveChat.kt b/core/model/src/main/java/dev/typetype/android/domain/livechat/LiveChat.kt index e8e6aa81..f7bfc5c9 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/livechat/LiveChat.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/livechat/LiveChat.kt @@ -8,6 +8,11 @@ data class LiveChatMessage( val authorName: String?, val authorAvatarUrl: String?, val moderator: Boolean, + val login: String? = null, + val color: String? = null, + val emotes: List = emptyList(), + val badges: List = emptyList(), + val action: Boolean = false, ) sealed interface LiveChatEvent { diff --git a/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatColor.kt b/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatColor.kt new file mode 100644 index 00000000..c29f68c2 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatColor.kt @@ -0,0 +1,52 @@ +package dev.typetype.android.domain.livechat + +import kotlin.math.abs +import kotlin.math.min +import kotlin.math.pow +import kotlin.math.roundToInt + +// The web chat's rule: a viewer without a color gets one from their login, and a color too dark for a dark theme (or +// too light for a light one) is mixed toward white (or black) until it reads. Returns an opaque ARGB value. +object TwitchChatColor { + private val DEFAULTS = listOf( + "#FF0000", "#0000FF", "#008000", "#B22222", "#FF7F50", "#9ACD32", "#FF4500", "#2E8B57", + "#DAA520", "#D2691E", "#5F9EA0", "#1E90FF", "#FF69B4", "#8A2BE2", "#00FF7F", + ) + + private val FALLBACK = intArrayOf(0x91, 0x46, 0xFF) + + fun name(color: String?, login: String, dark: Boolean): Int { + val rgb = rgb(color?.takeIf { it.isNotBlank() } ?: DEFAULTS[hash(login)]) ?: FALLBACK + val lum = luminance(rgb) + val mixed = when { + dark && lum < 0.18 -> mix(rgb, 255, min(0.75, (0.18 - lum) * 4 + 0.25)) + !dark && lum > 0.45 -> mix(rgb, 0, min(0.6, (lum - 0.45) * 2 + 0.2)) + else -> rgb + } + return (0xFF shl 24) or (mixed[0] shl 16) or (mixed[1] shl 8) or mixed[2] + } + + private fun hash(text: String): Int { + var value = 0 + text.codePoints().forEach { value = value * 31 + it } + return abs(value % DEFAULTS.size) + } + + private fun rgb(hex: String): IntArray? { + val digits = hex.removePrefix("#") + if (digits.length != 6) return null + val n = digits.toIntOrNull(16) ?: return null + return intArrayOf((n shr 16) and 255, (n shr 8) and 255, n and 255) + } + + private fun luminance(rgb: IntArray): Double { + fun channel(v: Int): Double { + val c = v / 255.0 + return if (c <= 0.03928) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4) + } + return 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]) + } + + private fun mix(rgb: IntArray, target: Int, amount: Double): IntArray = + IntArray(3) { (rgb[it] + (target - rgb[it]) * amount).roundToInt() } +} diff --git a/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatParts.kt b/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatParts.kt new file mode 100644 index 00000000..aa097634 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/livechat/TwitchChatParts.kt @@ -0,0 +1,118 @@ +package dev.typetype.android.domain.livechat + +data class ChatEmoteRange(val id: String, val start: Int, val end: Int) + +data class ChatImage(val name: String, val url: String) + +data class ChatEmote(val name: String, val url: String, val zeroWidth: Boolean = false) + +sealed interface ChatPart { + data class Text(val text: String) : ChatPart + data class Emote(val image: ChatImage, val overlays: List = emptyList()) : ChatPart + data class Mention(val text: String, val self: Boolean) : ChatPart + data class Link(val text: String, val href: String) : ChatPart +} + +// Same split as the web chat: Twitch's own emotes come as code point ranges, BTTV/FFZ/7TV ones as whole words, and a +// zero-width emote sits on top of the emote before it. +object TwitchChatParts { + private const val TWITCH_EMOTE_BASE = "https://static-cdn.jtvnw.net/emoticons/v2/" + private val LINK = Regex("""^(?:https?://)?(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d{2,5})?(?:[/?#]\S*)?$""", RegexOption.IGNORE_CASE) + private val TRAILING = Regex("""[),.!?:;'"\]]+$""") + private val SPACES = Regex("""(\s+)""") + private val BARE_TLDS = ( + "com net org info biz xyz io co app dev me tv gg ly to sh so ai fm am " + + "video live stream games game fun art blog club online site store shop tech link page news wiki social media " + + "be fr de uk es it nl eu ru jp cn kr br ca us au ch at se no dk fi pl pt cz ie in mx ar" + ).split(" ").toSet() + + fun twitchEmote(id: String, name: String): ChatImage = + ChatImage(name, "$TWITCH_EMOTE_BASE$id/default/dark/2.0") + + fun parts( + text: String, + native: List = emptyList(), + emotes: Map = emptyMap(), + selfLogin: String = "", + ): List { + val points = text.codePoints().toArray() + fun slice(from: Int, to: Int) = String(points, from, to - from) + val ranges = native.filter { it.start >= 0 && it.end < points.size && it.start <= it.end }.sortedBy { it.start } + val builder = Builder(emotes, selfLogin.lowercase()) + var cursor = 0 + for (range in ranges) { + if (range.start < cursor) continue + builder.segment(slice(cursor, range.start)) + builder.parts += ChatPart.Emote(twitchEmote(range.id, slice(range.start, range.end + 1))) + cursor = range.end + 1 + } + builder.segment(slice(cursor, points.size)) + return builder.parts + } + + fun linkHref(word: String): String? { + if (!LINK.matches(word)) return null + val schemed = word.startsWith("http://", ignoreCase = true) || word.startsWith("https://", ignoreCase = true) + val host = word.substringAfter("://").substringBefore('/').substringBefore('?').substringBefore('#') + .substringBefore(':').lowercase() + if (!schemed && !host.startsWith("www.") && host.substringAfterLast('.') !in BARE_TLDS) return null + return if (schemed) word else "https://$word" + } + + private class Builder(val emotes: Map, val self: String) { + val parts = mutableListOf() + + fun segment(text: String) { + var index = 0 + for (match in SPACES.findAll(text)) { + word(text.substring(index, match.range.first)) + pushText(match.value) + index = match.range.last + 1 + } + word(text.substring(index)) + } + + private fun word(word: String) { + if (word.isEmpty()) return + val emote = emotes[word] + if (emote != null) { + val image = ChatImage(emote.name, emote.url) + val base = if (emote.zeroWidth) lastEmoteIndex() else -1 + if (base >= 0) { + if (parts.lastOrNull() is ChatPart.Text) parts.removeAt(parts.lastIndex) + val target = parts[base] as ChatPart.Emote + parts[base] = target.copy(overlays = target.overlays + image) + } else { + parts += ChatPart.Emote(image) + } + return + } + if (word.startsWith("@") && word.length > 1) { + val name = word.drop(1).replace(TRAILING, "") + parts += ChatPart.Mention("@$name", name.lowercase() == self) + pushText(word.drop(name.length + 1)) + return + } + val trimmed = word.replace(TRAILING, "") + val href = linkHref(trimmed) + if (href != null) { + parts += ChatPart.Link(trimmed, href) + pushText(word.drop(trimmed.length)) + return + } + pushText(word) + } + + private fun lastEmoteIndex(): Int { + val last = parts.lastIndex + val index = if (last >= 0 && (parts[last] as? ChatPart.Text)?.text?.isBlank() == true) last - 1 else last + return if (index >= 0 && parts[index] is ChatPart.Emote) index else -1 + } + + private fun pushText(text: String) { + if (text.isEmpty()) return + val last = parts.lastOrNull() + if (last is ChatPart.Text) parts[parts.lastIndex] = ChatPart.Text(last.text + text) else parts += ChatPart.Text(text) + } + } +} diff --git a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchModels.kt b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchModels.kt index 2daced18..a742f745 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchModels.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchModels.kt @@ -1,5 +1,8 @@ package dev.typetype.android.domain.twitch +import dev.typetype.android.domain.livechat.ChatEmote +import dev.typetype.android.domain.livechat.ChatImage + import dev.typetype.android.domain.feed.Video data class TwitchCategory( @@ -20,6 +23,7 @@ data class TwitchChannel( val bannerUrl: String?, val followers: Long, val live: Video?, + val liveInfo: TwitchLiveInfo? = null, ) { val url: String get() = TwitchUrls.live(login) } @@ -51,3 +55,18 @@ data class TwitchVideoComment( val text: String, val moderator: Boolean, ) + +data class TwitchLiveInfo( + val title: String, + val viewers: Long, + val startedAtMillis: Long, + val category: String?, + val tags: List, +) + +// The emotes of BTTV, FFZ and 7TV keyed by the word that shows them, and the chat badges keyed as Twitch sends them +// on a message ("moderator/1"); the channel's own come before the global ones. +data class TwitchChatAssets( + val emotes: Map = emptyMap(), + val badges: Map = emptyMap(), +) diff --git a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchRepository.kt b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchRepository.kt index 531fdda2..563982e2 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchRepository.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchRepository.kt @@ -30,5 +30,7 @@ interface TwitchRepository { suspend fun chatHighlights(login: String): Result + suspend fun chatAssets(login: String): Result + suspend fun videoComments(id: String, offsetSeconds: Long?, cursor: String?): Result> } diff --git a/core/model/src/test/java/dev/typetype/android/domain/livechat/TwitchChatPartsTest.kt b/core/model/src/test/java/dev/typetype/android/domain/livechat/TwitchChatPartsTest.kt new file mode 100644 index 00000000..23deea1a --- /dev/null +++ b/core/model/src/test/java/dev/typetype/android/domain/livechat/TwitchChatPartsTest.kt @@ -0,0 +1,55 @@ +package dev.typetype.android.domain.livechat + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class TwitchChatPartsTest { + @Test + fun nativeEmoteRangesCountCodePointsNotUtf16Units() { + val parts = TwitchChatParts.parts("๐Ÿ˜€ Kappa hi", listOf(ChatEmoteRange("25", 2, 6))) + + assertEquals(ChatPart.Text("๐Ÿ˜€ "), parts[0]) + assertEquals("Kappa", (parts[1] as ChatPart.Emote).image.name) + assertEquals("https://static-cdn.jtvnw.net/emoticons/v2/25/default/dark/2.0", (parts[1] as ChatPart.Emote).image.url) + assertEquals(ChatPart.Text(" hi"), parts[2]) + } + + @Test + fun thirdPartyEmotesMatchWholeWordsAndZeroWidthOnesStackOnTheEmoteBefore() { + val emotes = mapOf( + "catJAM" to ChatEmote("catJAM", "https://cdn/cat"), + "RainTime" to ChatEmote("RainTime", "https://cdn/rain", zeroWidth = true), + ) + + val parts = TwitchChatParts.parts("catJAM RainTime catJAMs", emotes = emotes) + + val emote = parts[0] as ChatPart.Emote + assertEquals(listOf(ChatImage("RainTime", "https://cdn/rain")), emote.overlays) + assertEquals(ChatPart.Text(" catJAMs"), parts[1]) + } + + @Test + fun mentionsAndLinksAreTheirOwnParts() { + val parts = TwitchChatParts.parts("hey @Toasty, see typetype.tv!", selfLogin = "toasty") + + assertEquals(ChatPart.Mention("@Toasty", self = true), parts[1]) + assertEquals(ChatPart.Link("typetype.tv", "https://typetype.tv"), parts[3]) + assertEquals(ChatPart.Text("!"), parts[4]) + } + + @Test + fun bareWordsWithUnknownEndingsAreNotLinks() { + assertNull(TwitchChatParts.linkHref("file.txt")) + assertEquals("https://example.com/a", TwitchChatParts.linkHref("https://example.com/a")) + } + + @Test + fun darkNamesAreLightenedOnADarkThemeAndKeptOnALightOne() { + val navy = TwitchChatColor.name("#000080", "viewer", dark = true) + val red = TwitchChatColor.name("#FF0000", "viewer", dark = false) + + assertEquals(true, (navy and 0xFF) > 0x80) + assertEquals(0xFFFF0000.toInt(), red) + } +} From 92df856940d13f0f5cdef856ce76593fbc03afda Mon Sep 17 00:00:00 2001 From: Priveetee <138765817+Priveetee@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:16:11 +0100 Subject: [PATCH 2/8] feat: show Twitch chat lines with emotes, badges and colors --- .../feature/player/livechat/LiveChatSheet.kt | 14 ++- .../player/livechat/LiveChatViewModel.kt | 24 +++- .../feature/player/livechat/TwitchChatLine.kt | 105 ++++++++++++++++++ 3 files changed, 139 insertions(+), 4 deletions(-) create mode 100644 feature/player/src/main/java/dev/typetype/android/feature/player/livechat/TwitchChatLine.kt diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt index 794a4099..21be5907 100644 --- a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt @@ -1,5 +1,6 @@ package dev.typetype.android.feature.player.livechat +import dev.typetype.android.domain.twitch.TwitchChatAssets import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -77,7 +78,7 @@ internal fun LiveChatSheet(videoUrl: String, onDismiss: () -> Unit) { onHide = highlightsViewModel::hide, onVote = highlightsViewModel::vote.takeIf { canVote && highlights.poll?.id !in voted }, ) - LiveChatMessages(messages = state.messages, modifier = Modifier.weight(1f)) + LiveChatMessages(state.messages, Modifier.weight(1f), state.assets, state.selfLogin) TwitchChatComposer(videoUrl) } } @@ -112,7 +113,12 @@ private fun LiveChatHeader(status: LiveChatStatus, onRetry: () -> Unit) { } @Composable -internal fun LiveChatMessages(messages: List, modifier: Modifier) { +internal fun LiveChatMessages( + messages: List, + modifier: Modifier, + assets: TwitchChatAssets = TwitchChatAssets(), + selfLogin: String = "", +) { val listState = rememberLazyListState() val following by remember { derivedStateOf { @@ -139,7 +145,9 @@ internal fun LiveChatMessages(messages: List, modifier: Modifie contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { - items(messages, key = { it.id }) { LiveChatMessageRow(it) } + items(messages, key = { it.id }) { message -> + if (message.login != null) TwitchChatLine(message, assets, selfLogin) else LiveChatMessageRow(message) + } } } diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatViewModel.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatViewModel.kt index c129a342..2281c7bc 100644 --- a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatViewModel.kt +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatViewModel.kt @@ -1,5 +1,11 @@ package dev.typetype.android.feature.player.livechat +import dev.typetype.android.domain.twitch.TwitchAccountRepository +import dev.typetype.android.domain.twitch.TwitchChatAssets +import dev.typetype.android.domain.twitch.TwitchRepository +import dev.typetype.android.domain.twitch.TwitchTarget +import dev.typetype.android.domain.twitch.TwitchUrls +import kotlinx.coroutines.coroutineScope import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel @@ -22,11 +28,15 @@ enum class LiveChatStatus { Connecting, Live, Reconnecting, Ended, Failed } data class LiveChatState( val messages: List = emptyList(), val status: LiveChatStatus = LiveChatStatus.Connecting, + val assets: TwitchChatAssets = TwitchChatAssets(), + val selfLogin: String = "", ) @HiltViewModel class LiveChatViewModel @Inject constructor( private val repository: LiveChatRepository, + private val twitch: TwitchRepository, + private val accounts: TwitchAccountRepository, ) : ViewModel() { private val _state = MutableStateFlow(LiveChatState()) val state: StateFlow = _state.asStateFlow() @@ -35,7 +45,19 @@ class LiveChatViewModel @Inject constructor( fun start(videoUrl: String) { job?.cancel() _state.value = LiveChatState() - job = viewModelScope.launch { follow(videoUrl) } + job = viewModelScope.launch { + (TwitchUrls.parse(videoUrl) as? TwitchTarget.Live)?.let { live -> launch { loadTwitchAssets(live.login) } } + follow(videoUrl) + } + } + + private suspend fun loadTwitchAssets(login: String) = coroutineScope { + launch { twitch.chatAssets(login).onSuccess { assets -> _state.update { it.copy(assets = assets) } } } + launch { + accounts.status().getOrNull()?.name?.takeIf { it.isNotBlank() }?.let { name -> + _state.update { it.copy(selfLogin = name) } + } + } } fun stop() { diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/TwitchChatLine.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/TwitchChatLine.kt new file mode 100644 index 00000000..7e7c07f3 --- /dev/null +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/TwitchChatLine.kt @@ -0,0 +1,105 @@ +package dev.typetype.android.feature.player.livechat + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.Placeholder +import androidx.compose.ui.text.PlaceholderVerticalAlign +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.withLink +import androidx.compose.ui.text.withStyle +import androidx.compose.foundation.text.InlineTextContent +import androidx.compose.foundation.text.appendInlineContent +import androidx.compose.ui.unit.sp +import coil3.compose.AsyncImage +import dev.typetype.android.core.ui.share.LocalServerBaseUrl +import dev.typetype.android.core.url.buildImageUrl +import dev.typetype.android.domain.livechat.ChatImage +import dev.typetype.android.domain.livechat.ChatPart +import dev.typetype.android.domain.livechat.LiveChatMessage +import dev.typetype.android.domain.livechat.TwitchChatColor +import dev.typetype.android.domain.livechat.TwitchChatParts +import dev.typetype.android.domain.twitch.TwitchChatAssets + +// One Twitch chat line as the web shows it: badges, the name in the viewer's color (made readable on the theme), then +// the message with its emotes inline. Images go through the instance proxy like every other picture in the app; each +// one is read out by its name. +@Composable +internal fun TwitchChatLine(message: LiveChatMessage, assets: TwitchChatAssets, selfLogin: String) { + val colors = MaterialTheme.colorScheme + val dark = colors.background.luminance() < 0.5f + val serverBaseUrl = LocalServerBaseUrl.current + val parts = remember(message.id, assets) { + TwitchChatParts.parts(message.text, message.emotes, assets.emotes, selfLogin) + } + val badges = remember(message.badges, assets) { message.badges.mapNotNull { assets.badges[it] } } + val name = message.authorName.orEmpty() + val nameColor = Color(TwitchChatColor.name(message.color, message.login ?: name, dark)) + val inline = HashMap() + fun image(id: String, images: List, size: Float) { + inline[id] = InlineTextContent(Placeholder(size.sp, size.sp, PlaceholderVerticalAlign.TextCenter)) { + Box { + images.forEach { picture -> + AsyncImage( + model = buildImageUrl(serverBaseUrl, picture.url), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.fillMaxSize(), + ) + } + } + } + } + val text = buildAnnotatedString { + badges.forEachIndexed { index, badge -> + val id = "badge-$index" + image(id, listOf(badge), BADGE_SIZE) + appendInlineContent(id, badge.name) + append(' ') + } + withStyle(SpanStyle(color = nameColor, fontWeight = FontWeight.SemiBold)) { append(name) } + append(if (message.action) " " else ": ") + val body = if (message.action) SpanStyle(color = nameColor, fontStyle = FontStyle.Italic) else SpanStyle() + withStyle(body) { + parts.forEachIndexed { index, part -> + when (part) { + is ChatPart.Text -> append(part.text) + is ChatPart.Emote -> { + val id = "emote-$index" + image(id, listOf(part.image) + part.overlays, EMOTE_SIZE) + appendInlineContent(id, part.image.name) + } + is ChatPart.Mention -> withStyle( + SpanStyle( + fontWeight = FontWeight.Bold, + background = if (part.self) colors.primary.copy(alpha = 0.2f) else Color.Unspecified, + ), + ) { append(part.text) } + is ChatPart.Link -> withLink( + LinkAnnotation.Url( + part.href, + TextLinkStyles(SpanStyle(color = colors.primary, textDecoration = TextDecoration.Underline)), + ), + ) { append(part.text) } + } + } + } + } + Text(text = text, inlineContent = inline, style = MaterialTheme.typography.bodyMedium) +} + +private const val BADGE_SIZE = 18f +private const val EMOTE_SIZE = 28f From 6fcc618cf053838c241ca08dee814459ac6aa9e1 Mon Sep 17 00:00:00 2001 From: Priveetee <138765817+Priveetee@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:22:53 +0100 Subject: [PATCH 3/8] feat: watch a Twitch live with its chat docked under the video --- .../resources/src/main/res/values/strings.xml | 1 + .../android/feature/player/LoadedPlayer.kt | 16 ++- .../feature/player/PlayerContentLayout.kt | 49 ++++++-- .../feature/player/livechat/LiveChatSheet.kt | 34 ++++-- .../player/twitch/TwitchLiveDetails.kt | 114 ++++++++++++++++++ .../twitch/TwitchLiveDetailsViewModel.kt | 75 ++++++++++++ 6 files changed, 269 insertions(+), 20 deletions(-) create mode 100644 feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetails.kt create mode 100644 feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetailsViewModel.kt diff --git a/core/resources/src/main/res/values/strings.xml b/core/resources/src/main/res/values/strings.xml index 103527fd..87493802 100644 --- a/core/resources/src/main/res/values/strings.xml +++ b/core/resources/src/main/res/values/strings.xml @@ -95,6 +95,7 @@ Followed channels live Follow Following + Live for %1$s Couldn\'t load Shorts Couldn\'t load more Shorts No Shorts are available yet. diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/LoadedPlayer.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/LoadedPlayer.kt index 258dacd2..ea42f979 100644 --- a/feature/player/src/main/java/dev/typetype/android/feature/player/LoadedPlayer.kt +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/LoadedPlayer.kt @@ -1,5 +1,11 @@ package dev.typetype.android.feature.player +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.imePadding +import dev.typetype.android.domain.twitch.TwitchTarget +import dev.typetype.android.domain.twitch.TwitchUrls +import dev.typetype.android.feature.player.livechat.LiveChatPanel +import dev.typetype.android.feature.player.twitch.TwitchLiveDetails import android.graphics.Rect import androidx.activity.compose.LocalActivity import androidx.compose.foundation.background @@ -207,8 +213,14 @@ internal fun LoadedPlayer( }, ), ) { + // A Twitch live is watched with its chat: the chat is docked under the video (beside it on a wide screen) and + // the details above it shrink to what a live needs. + val twitchLive = (TwitchUrls.parse(videoUrl) as? TwitchTarget.Live)?.login?.takeIf { stream.isLive } PlayerContentLayout( isFullscreen = isFullscreen, + docked = twitchLive?.let { + { dockedModifier -> LiveChatPanel(videoUrl, dockedModifier.navigationBarsPadding().imePadding()) } + }, isInPip = isInPip, hostTransitionProgress = hostTransitionProgress, viewport = { viewportModifier -> @@ -289,7 +301,9 @@ internal fun LoadedPlayer( ) }, details = { detailsModifier -> - PlayerDetails( + if (twitchLive != null) { + TwitchLiveDetails(stream, twitchLive, onOpenChannel, detailsModifier) + } else PlayerDetails( stream = stream, videoUrl = videoUrl, player = controller, diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/PlayerContentLayout.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/PlayerContentLayout.kt index 1cf566a9..f3b77ade 100644 --- a/feature/player/src/main/java/dev/typetype/android/feature/player/PlayerContentLayout.kt +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/PlayerContentLayout.kt @@ -60,6 +60,7 @@ fun PlayerContentLayout( viewport: @Composable (Modifier) -> Unit, details: @Composable (Modifier) -> Unit, recommendations: @Composable (Modifier) -> Unit = {}, + docked: (@Composable (Modifier) -> Unit)? = null, ) { val currentViewport by rememberUpdatedState(viewport) val retainedViewport = remember { @@ -95,7 +96,35 @@ fun PlayerContentLayout( ) .fillMaxSize(), ) - PlayerContentLayoutMode.SingleColumn -> { + PlayerContentLayoutMode.SingleColumn -> if (docked != null) { + // A live chat fills what the video and the details leave, so the column does not scroll. + Column(modifier = Modifier.fillMaxSize().testTag(PLAYER_SINGLE_COLUMN_LAYOUT_TAG)) { + retainedViewport( + Modifier + .playerViewportTransition( + progress = hostTransitionProgress, + miniWidthPx = miniWidthPx, + miniHeightPx = miniHeightPx, + miniStartPx = miniStartPx, + miniTopPx = miniTopPx, + ) + .fillMaxWidth() + .aspectRatio(VIDEO_ASPECT_RATIO) + .testTag(PLAYER_VIEWPORT_TAG), + ) + val hidden = if (detailsHidden) Modifier.clearAndSetSemantics { } else Modifier + details( + Modifier.fillMaxWidth() + .playerDetailsTransition(hostTransitionProgress, singleColumnDetailsTravelPx) + .then(hidden), + ) + docked( + Modifier.weight(1f).fillMaxWidth() + .playerDetailsTransition(hostTransitionProgress, singleColumnDetailsTravelPx) + .then(hidden), + ) + } + } else { Column( modifier = Modifier .fillMaxSize() @@ -168,14 +197,16 @@ fun PlayerContentLayout( .then(if (detailsHidden) Modifier.clearAndSetSemantics { } else Modifier), ) } - recommendations( - Modifier - .weight(DETAILS_PANE_WEIGHT) - .fillMaxHeight() - .verticalScroll(rememberScrollState()) - .playerDetailsTransition(hostTransitionProgress) - .then(if (detailsHidden) Modifier.clearAndSetSemantics { } else Modifier), - ) + val sidePane = Modifier + .weight(DETAILS_PANE_WEIGHT) + .fillMaxHeight() + .playerDetailsTransition(hostTransitionProgress) + .then(if (detailsHidden) Modifier.clearAndSetSemantics { } else Modifier) + if (docked != null) { + docked(sidePane) + } else { + recommendations(sidePane.verticalScroll(rememberScrollState())) + } } } } diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt index 21be5907..f9476e53 100644 --- a/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/livechat/LiveChatSheet.kt @@ -1,5 +1,8 @@ package dev.typetype.android.feature.player.livechat +import androidx.compose.foundation.layout.isImeVisible +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.ExperimentalLayoutApi import dev.typetype.android.domain.twitch.TwitchChatAssets import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement @@ -52,6 +55,19 @@ import dev.typetype.android.domain.livechat.LiveChatMessage @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun LiveChatSheet(videoUrl: String, onDismiss: () -> Unit) { + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = MaterialTheme.colorScheme.surface, + ) { + LiveChatPanel(videoUrl, Modifier.fillMaxWidth().fillMaxHeight(0.7f)) + } +} + +// The chat itself, in the sheet for YouTube or docked under a Twitch live where it fills the rest of the screen. +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun LiveChatPanel(videoUrl: String, modifier: Modifier) { val viewModel: LiveChatViewModel = hiltViewModel(key = "live-chat") val state by viewModel.state.collectAsStateWithLifecycle() val highlightsViewModel: TwitchChatHighlightsViewModel = hiltViewModel(key = "live-chat-highlights") @@ -64,23 +80,21 @@ internal fun LiveChatSheet(videoUrl: String, onDismiss: () -> Unit) { highlightsViewModel.stop() } } - ModalBottomSheet( - onDismissRequest = onDismiss, - sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), - containerColor = MaterialTheme.colorScheme.surface, - ) { - Column(modifier = Modifier.fillMaxWidth().fillMaxHeight(0.7f)) { + // While typing, the keyboard leaves room for the last lines and the message only. + val typing = WindowInsets.isImeVisible + Column(modifier = modifier) { + val canVote by highlightsViewModel.canVote.collectAsStateWithLifecycle() + val voted by highlightsViewModel.voted.collectAsStateWithLifecycle() + if (!typing) { LiveChatHeader(status = state.status, onRetry = { viewModel.retry(videoUrl) }) - val canVote by highlightsViewModel.canVote.collectAsStateWithLifecycle() - val voted by highlightsViewModel.voted.collectAsStateWithLifecycle() TwitchChatHighlightsCards( highlights, onHide = highlightsViewModel::hide, onVote = highlightsViewModel::vote.takeIf { canVote && highlights.poll?.id !in voted }, ) - LiveChatMessages(state.messages, Modifier.weight(1f), state.assets, state.selfLogin) - TwitchChatComposer(videoUrl) } + LiveChatMessages(state.messages, Modifier.weight(1f), state.assets, state.selfLogin) + TwitchChatComposer(videoUrl) } } diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetails.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetails.kt new file mode 100644 index 00000000..2a230b7e --- /dev/null +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetails.kt @@ -0,0 +1,114 @@ +package dev.typetype.android.feature.player.twitch + +import android.icu.text.CompactDecimalFormat +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.produceState +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import dev.typetype.android.R +import dev.typetype.android.core.ui.components.ProfileAvatar +import dev.typetype.android.domain.stream.Stream +import java.util.Locale +import kotlinx.coroutines.delay + +// What sits between a Twitch live and its chat: the title, how many watch and for how long, the category, and the +// channel with its follow button. Kept short so the chat under it gets most of the screen. +@Composable +internal fun TwitchLiveDetails(stream: Stream, login: String, onOpenChannel: (String) -> Unit, modifier: Modifier) { + val viewModel: TwitchLiveDetailsViewModel = hiltViewModel(key = "twitch-live-details") + LaunchedEffect(login) { viewModel.start(login) } + val state by viewModel.state.collectAsStateWithLifecycle() + val info = state.channel?.liveInfo + val startedAt = info?.startedAtMillis ?: stream.uploadedAtMillis + val now by produceState(System.currentTimeMillis()) { + while (true) { + delay(CLOCK_TICK_MS) + value = System.currentTimeMillis() + } + } + Column(modifier = modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = info?.title ?: stream.title, + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = stringResource(R.string.video_live_badge), + color = Color.White, + style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.Bold), + modifier = Modifier.background(LIVE_RED, RoundedCornerShape(4.dp)).padding(horizontal = 6.dp, vertical = 2.dp), + ) + val meta = listOfNotNull( + stringResource(R.string.video_watching_short, compact(info?.viewers ?: stream.viewCount)), + uptime(startedAt, now)?.let { stringResource(R.string.twitch_live_for, it) }, + info?.category, + ) + Text( + text = meta.joinToString(" ยท "), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + val name = state.channel?.displayName ?: stream.uploaderName + Row( + modifier = Modifier.weight(1f).clickable(role = Role.Button) { onOpenChannel(stream.uploaderUrl) }, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + ProfileAvatar( + imageUrl = state.channel?.avatarUrl ?: stream.uploaderAvatarUrl, + fallbackLetter = name.take(1), + contentDescription = null, + modifier = Modifier.size(36.dp), + ) + Text(name, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (state.followable) { + val label = stringResource(if (state.following) R.string.twitch_channel_following else R.string.twitch_channel_follow) + if (state.following) { + OutlinedButton(onClick = viewModel::toggleFollow) { Text(label) } + } else { + Button(onClick = viewModel::toggleFollow) { Text(label) } + } + } + } + } +} + +private fun compact(count: Long): String = + CompactDecimalFormat.getInstance(Locale.getDefault(), CompactDecimalFormat.CompactStyle.SHORT).format(count.coerceAtLeast(0)) + +private fun uptime(startedAtMillis: Long, now: Long): String? { + if (startedAtMillis <= 0) return null + val minutes = ((now - startedAtMillis) / 60_000).coerceAtLeast(0) + return "%d:%02d".format(minutes / 60, minutes % 60) +} + +private val LIVE_RED = Color(0xFFE91916) +private const val CLOCK_TICK_MS = 30_000L diff --git a/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetailsViewModel.kt b/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetailsViewModel.kt new file mode 100644 index 00000000..b8889289 --- /dev/null +++ b/feature/player/src/main/java/dev/typetype/android/feature/player/twitch/TwitchLiveDetailsViewModel.kt @@ -0,0 +1,75 @@ +package dev.typetype.android.feature.player.twitch + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import dev.typetype.android.domain.twitch.TwitchAccountRepository +import dev.typetype.android.domain.twitch.TwitchChannel +import dev.typetype.android.domain.twitch.TwitchRepository +import javax.inject.Inject +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +data class TwitchLiveDetailsState( + val channel: TwitchChannel? = null, + val followable: Boolean = false, + val following: Boolean = false, +) + +// The channel behind a live, read again every minute like the web watch page so the viewer count and the category +// follow the stream; following goes through the linked Twitch account when there is one. +@HiltViewModel +class TwitchLiveDetailsViewModel @Inject constructor( + private val twitch: TwitchRepository, + private val accounts: TwitchAccountRepository, +) : ViewModel() { + private val _state = MutableStateFlow(TwitchLiveDetailsState()) + val state: StateFlow = _state.asStateFlow() + private var job: Job? = null + private var login: String? = null + + fun start(login: String) { + if (this.login == login && job?.isActive == true) return + this.login = login + job?.cancel() + _state.value = TwitchLiveDetailsState() + job = viewModelScope.launch { + launch { + if (accounts.status().getOrNull()?.linked != true) return@launch + accounts.isFollowing(login).onSuccess { following -> + _state.update { it.copy(followable = true, following = following) } + } + } + while (isActive) { + twitch.channel(login).onSuccess { channel -> _state.update { it.copy(channel = channel) } } + delay(REFRESH_MS) + } + } + } + + fun toggleFollow() { + val target = login ?: return + val current = _state.value + if (!current.followable) return + _state.update { it.copy(following = !current.following) } + viewModelScope.launch { + accounts.setFollowing(target, !current.following).onFailure { + _state.update { it.copy(following = current.following) } + } + } + } + + override fun onCleared() { + job?.cancel() + } + + private companion object { + const val REFRESH_MS = 60_000L + } +} From df1eee3bf22eb42e0209547c6c14a7e727ddfc0b Mon Sep 17 00:00:00 2001 From: Priveetee <138765817+Priveetee@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:25:30 +0100 Subject: [PATCH 4/8] feat: show followed replays and channels on the Live tab --- .../twitch/RemoteTwitchAccountRepository.kt | 7 ++ .../domain/twitch/TwitchAccountRepository.kt | 4 + .../resources/src/main/res/values/strings.xml | 3 + .../android/feature/live/LiveRails.kt | 89 +++++++++++++++++++ .../android/feature/live/LiveScreen.kt | 25 +++++- .../android/feature/live/LiveViewModel.kt | 10 ++- 6 files changed, 133 insertions(+), 5 deletions(-) create mode 100644 feature/live/src/main/java/dev/typetype/android/feature/live/LiveRails.kt diff --git a/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchAccountRepository.kt b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchAccountRepository.kt index 00d9b570..64596752 100644 --- a/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchAccountRepository.kt +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchAccountRepository.kt @@ -1,5 +1,6 @@ package dev.typetype.android.data.twitch +import dev.typetype.android.domain.twitch.TwitchChannel import dev.typetype.android.core.error.suspendRunCatching import dev.typetype.android.data.account.ActiveAccountScope import dev.typetype.android.data.network.TypeTypeApi @@ -54,6 +55,12 @@ class RemoteTwitchAccountRepository @Inject constructor( override suspend fun followedLives(cursor: String?): Result> = call { twitchFollowedLives(cursor) } .map { page -> TwitchPage(page.items.map { it.toVideo() }, page.cursor?.takeIf { page.hasMore && it.isNotBlank() }) } + override suspend fun followedVideos(cursor: String?): Result> = call { twitchFollowedVideos(cursor) } + .map { page -> TwitchPage(page.items.map { it.toVideo() }, page.cursor?.takeIf { page.hasMore && it.isNotBlank() }) } + + override suspend fun followedChannels(cursor: String?): Result> = call { twitchFollows(cursor) } + .map { page -> TwitchPage(page.items.map { it.toChannel() }, page.cursor?.takeIf { page.hasMore && it.isNotBlank() }) } + override suspend fun isFollowing(login: String): Result = call { twitchFollowState(login) }.map { it.following } override suspend fun setFollowing(login: String, follow: Boolean): Result = diff --git a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchAccountRepository.kt b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchAccountRepository.kt index 2ef0a396..fac97657 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchAccountRepository.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchAccountRepository.kt @@ -32,6 +32,10 @@ interface TwitchAccountRepository { suspend fun followedLives(cursor: String? = null): Result> + suspend fun followedVideos(cursor: String? = null): Result> + + suspend fun followedChannels(cursor: String? = null): Result> + suspend fun isFollowing(login: String): Result suspend fun setFollowing(login: String, follow: Boolean): Result diff --git a/core/resources/src/main/res/values/strings.xml b/core/resources/src/main/res/values/strings.xml index 87493802..2a3c7c27 100644 --- a/core/resources/src/main/res/values/strings.xml +++ b/core/resources/src/main/res/values/strings.xml @@ -91,6 +91,9 @@ Nothing here yet Search Twitch channels Live now + %1$s, live now + Past broadcasts of followed channels + Followed channels All Followed channels live Follow diff --git a/feature/live/src/main/java/dev/typetype/android/feature/live/LiveRails.kt b/feature/live/src/main/java/dev/typetype/android/feature/live/LiveRails.kt new file mode 100644 index 00000000..bc27c7c3 --- /dev/null +++ b/feature/live/src/main/java/dev/typetype/android/feature/live/LiveRails.kt @@ -0,0 +1,89 @@ +package dev.typetype.android.feature.live + +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import dev.typetype.android.R +import dev.typetype.android.core.ui.components.ProfileAvatar +import dev.typetype.android.core.ui.components.VideoCard +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.twitch.TwitchChannel + +// A row that scrolls sideways, so the followed sections stay short and the popular lives stay in sight below them. +@Composable +internal fun LiveVideoRail(videos: List