diff --git a/.github/workflows/discord-app-release.yml b/.github/workflows/discord-app-release.yml new file mode 100644 index 00000000..7ccb0bee --- /dev/null +++ b/.github/workflows/discord-app-release.yml @@ -0,0 +1,44 @@ +# For app repos (TypeType-Android, TypeType-IOS, TypeType-TV, TypeType-tvOS). +# Pre-releases (-beta.N, -rc.N) go to #🧪・releases-rc, stable releases go to #🚀・releases-main, +# with the release notes. Needs the secrets DISCORD_WEBHOOK_RC and DISCORD_WEBHOOK_MAIN. +name: Discord release notify + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + notify: + runs-on: ubuntu-latest + steps: + - name: Post to Discord + env: + WEBHOOK_RC: ${{ secrets.DISCORD_WEBHOOK_RC }} + WEBHOOK_MAIN: ${{ secrets.DISCORD_WEBHOOK_MAIN }} + PRERELEASE: ${{ github.event.release.prerelease }} + TAG: ${{ github.event.release.tag_name }} + RNAME: ${{ github.event.release.name }} + URL: ${{ github.event.release.html_url }} + BODY: ${{ github.event.release.body }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + if [ "$PRERELEASE" = "true" ]; then + WEBHOOK="$WEBHOOK_RC"; BOT="The Lab TV"; EMOJI="🧪"; COLOR=15105570; INTRO="Beta build, might break, have fun (・ω・)" + else + WEBHOOK="$WEBHOOK_MAIN"; BOT="Rocket TV"; EMOJI="🚀"; COLOR=5763719; INTRO="New release (。•̀ᴗ-)✧" + fi + [ -n "$WEBHOOK" ] || { echo "webhook secret not set"; exit 0; } + TITLE="${EMOJI} ${RNAME:-${REPO#*/} ${TAG}}" + jq -n \ + --arg title "$TITLE" \ + --arg url "$URL" \ + --arg desc "$(printf '%s\n\n%s' "$INTRO" "${BODY:-}" | cut -c1-3900)" \ + --argjson color "$COLOR" \ + --arg bot "$BOT" \ + '{username: $bot, embeds: [{title: $title, url: $url, description: $desc, color: $color}]}' \ + > payload.json + curl -fsS -H "Content-Type: application/json" -d @payload.json "$WEBHOOK" diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 7df31aa2..3ec55924 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -22,8 +22,8 @@ android { defaultConfig { applicationId = "dev.typetype.android" - versionCode = 11119 - versionName = "1.13.0-beta.4" + versionCode = 11121 + versionName = "1.14.0-beta.1" } signingConfigs { @@ -105,6 +105,7 @@ dependencies { implementation(project(":feature:setup")) implementation(project(":feature:channel")) implementation(project(":feature:library")) + implementation(project(":feature:live")) implementation(project(":feature:subscriptions")) implementation(project(":feature:settings")) implementation(project(":feature:player")) diff --git a/app/src/androidTest/java/dev/typetype/android/TopLevelNavigationTest.kt b/app/src/androidTest/java/dev/typetype/android/TopLevelNavigationTest.kt index 27885d58..222ce059 100644 --- a/app/src/androidTest/java/dev/typetype/android/TopLevelNavigationTest.kt +++ b/app/src/androidTest/java/dev/typetype/android/TopLevelNavigationTest.kt @@ -11,7 +11,10 @@ import androidx.navigation.compose.rememberNavController import dev.typetype.android.core.ui.navigation.ChannelRoute import dev.typetype.android.core.ui.navigation.HomeRoute import dev.typetype.android.core.ui.navigation.LibraryRoute +import dev.typetype.android.core.ui.navigation.LiveRoute +import dev.typetype.android.core.ui.navigation.ShortsRoute import dev.typetype.android.core.ui.navigation.SubscriptionsRoute +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -49,4 +52,26 @@ class TopLevelNavigationTest { } composeRule.onNodeWithText("Subscriptions").assertExists() } + + @Test + fun everyTabIsRecognizedOnItsOwnDestination() { + composeRule.setContent { + controller = rememberNavController() + NavHost(controller, startDestination = HomeRoute) { + composable { Text("Home") } + composable { Text("Shorts") } + composable { Text("Subscriptions") } + composable { Text("Live") } + composable { Text("Library") } + } + } + topLevelTabs.forEach { tab -> + composeRule.runOnIdle { + controller.navigateTopLevel(tab.route, controller.currentDestination?.route) + } + composeRule.runOnIdle { + assertTrue(tab.route.toString(), controller.currentDestination.matchesRoute(tab.route)) + } + } + } } diff --git a/app/src/main/java/dev/typetype/android/AppNavHost.kt b/app/src/main/java/dev/typetype/android/AppNavHost.kt index 9795bbb3..bfc4080b 100644 --- a/app/src/main/java/dev/typetype/android/AppNavHost.kt +++ b/app/src/main/java/dev/typetype/android/AppNavHost.kt @@ -1,5 +1,11 @@ package dev.typetype.android +import dev.typetype.android.core.ui.navigation.LiveRoute +import dev.typetype.android.core.ui.navigation.TwitchChannelRoute +import dev.typetype.android.feature.live.TwitchChannelRouteScreen +import dev.typetype.android.feature.live.TwitchChannelViewModel +import dev.typetype.android.feature.live.LiveRouteScreen +import dev.typetype.android.feature.live.LiveViewModel import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable @@ -122,6 +128,7 @@ fun AppNavHost( avatarUrl = avatarUrl, avatarFallbackLetter = avatarFallback, showShorts = !deArrowSettings.hideShorts, + showLive = currentServer?.twitchEnabled == true, accessiblePlayerControls = appPreferences.playerAccessibleControlsEnabled, onPlayVideo = onPlayVideo, onOpenChannel = onOpenChannel, @@ -171,6 +178,12 @@ fun AppNavHost( onOpenChannel = onOpenChannel, ) } + composable { + LiveRouteScreen(viewModel = hiltViewModel(), onPlayVideo = onPlayVideo, onOpenChannel = onOpenChannel) + } + composable { + TwitchChannelRouteScreen(viewModel = hiltViewModel(), onPlayVideo = onPlayVideo) + } composable { SearchRouteScreen( onNavigateBack = { navController.popBackStack() }, diff --git a/app/src/main/java/dev/typetype/android/AppNavigation.kt b/app/src/main/java/dev/typetype/android/AppNavigation.kt index 4e96f8ad..69b404a8 100644 --- a/app/src/main/java/dev/typetype/android/AppNavigation.kt +++ b/app/src/main/java/dev/typetype/android/AppNavigation.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.text.TextAutoSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings @@ -51,6 +52,7 @@ import androidx.navigation.NavDestination.Companion.hasRoute import dev.typetype.android.core.ui.navigation.LibraryLandingRoute import dev.typetype.android.core.ui.navigation.HomeRoute import dev.typetype.android.core.ui.navigation.LibraryRoute +import dev.typetype.android.core.ui.navigation.LiveRoute import dev.typetype.android.core.ui.navigation.ShortsRoute import dev.typetype.android.core.ui.navigation.SubscriptionsRoute import dev.typetype.android.core.ui.components.ProfileAvatar @@ -65,11 +67,12 @@ internal val topLevelTabs = listOf( TopLevelTab(HomeRoute, R.string.tab_home, R.drawable.ic_home), TopLevelTab(ShortsRoute, R.string.tab_shorts, R.drawable.ic_shorts), TopLevelTab(SubscriptionsRoute, R.string.tab_subscriptions, R.drawable.ic_subscriptions), + TopLevelTab(LiveRoute, R.string.tab_live, R.drawable.ic_live), TopLevelTab(LibraryRoute, R.string.tab_library, R.drawable.ic_library), ) -internal fun visibleTopLevelTabs(showShorts: Boolean): List = - topLevelTabs.filter { showShorts || it.route != ShortsRoute } +internal fun visibleTopLevelTabs(showShorts: Boolean, showLive: Boolean = false): List = + topLevelTabs.filter { (showShorts || it.route != ShortsRoute) && (showLive || it.route != LiveRoute) } @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -168,8 +171,16 @@ internal fun AppBottomBar( onClick = { onTabClick(tab) }, icon = { Icon(painterResource(tab.iconRes), contentDescription = null, modifier = Modifier.size(if (expanded) 32.dp else 24.dp)) }, - label = { Text(stringResource(tab.labelRes), style = if (expanded) - MaterialTheme.typography.titleSmall else MaterialTheme.typography.labelMedium) }, + label = { + val style = if (expanded) MaterialTheme.typography.titleSmall else MaterialTheme.typography.labelMedium + // Five tabs leave little width: a long label shrinks instead of wrapping. + Text( + text = stringResource(tab.labelRes), + style = style, + maxLines = 1, + autoSize = TextAutoSize.StepBased(minFontSize = 9.sp, maxFontSize = style.fontSize), + ) + }, ) } } @@ -234,6 +245,7 @@ internal fun NavDestination?.matchesRoute(route: Any): Boolean { HomeRoute -> destination.hasRoute() ShortsRoute -> destination.hasRoute() SubscriptionsRoute -> destination.hasRoute() + LiveRoute -> destination.hasRoute() LibraryRoute -> destination.hasRoute() || destination.hasRoute() else -> false diff --git a/app/src/main/java/dev/typetype/android/AppShell.kt b/app/src/main/java/dev/typetype/android/AppShell.kt index 8933b2fc..5c591967 100644 --- a/app/src/main/java/dev/typetype/android/AppShell.kt +++ b/app/src/main/java/dev/typetype/android/AppShell.kt @@ -43,6 +43,7 @@ import dev.typetype.android.core.ui.navigation.PodcastRoute import dev.typetype.android.core.ui.navigation.PublicPlaylistRoute import dev.typetype.android.core.ui.navigation.SearchRoute import dev.typetype.android.core.ui.navigation.ShortsRoute +import dev.typetype.android.core.ui.navigation.TwitchChannelRoute import dev.typetype.android.core.ui.player.PlayerHostController import dev.typetype.android.core.ui.player.PlayerHostTarget import dev.typetype.android.feature.player.components.LocalMediaController @@ -76,6 +77,7 @@ fun AppShell( avatarUrl: String? = null, avatarFallbackLetter: String? = null, showShorts: Boolean = true, + showLive: Boolean = false, accessiblePlayerControls: Boolean = false, onPlayVideo: (videoUrl: String) -> Unit, onOpenChannel: (channelUrl: String) -> Unit, @@ -86,11 +88,12 @@ fun AppShell( val backStackEntry by navController.currentBackStackEntryAsState() val currentDestination = backStackEntry?.destination val isShorts = currentDestination.matchesRoute(ShortsRoute) - val navigationTabs = visibleTopLevelTabs(showShorts) + val navigationTabs = visibleTopLevelTabs(showShorts, showLive) val isTopLevel = topLevelTabs.any { currentDestination.matchesRoute(it.route) } val showsNavigation = !isShorts && ( isTopLevel || currentDestination?.hasRoute() == true || + currentDestination?.hasRoute() == true || currentDestination?.hasRoute() == true || currentDestination?.hasRoute() == true || currentDestination?.hasRoute() == true || diff --git a/app/src/main/java/dev/typetype/android/ChannelNavigation.kt b/app/src/main/java/dev/typetype/android/ChannelNavigation.kt index 722ac50e..c9951698 100644 --- a/app/src/main/java/dev/typetype/android/ChannelNavigation.kt +++ b/app/src/main/java/dev/typetype/android/ChannelNavigation.kt @@ -1,9 +1,13 @@ package dev.typetype.android +import dev.typetype.android.core.ui.navigation.TwitchChannelRoute +import dev.typetype.android.domain.twitch.TwitchTarget +import dev.typetype.android.domain.twitch.TwitchUrls import androidx.navigation.NavHostController import dev.typetype.android.core.ui.navigation.ChannelRoute import dev.typetype.android.core.ui.navigation.channelNavigationUrl internal fun NavHostController.navigateToChannel(channelUrl: String) { - navigate(ChannelRoute(channelUrl = channelNavigationUrl(channelUrl))) + val twitch = TwitchUrls.parse(channelUrl) as? TwitchTarget.Live + if (twitch != null) navigate(TwitchChannelRoute(twitch.login)) else navigate(ChannelRoute(channelUrl = channelNavigationUrl(channelUrl))) } diff --git a/core/data/schemas/dev.typetype.android.data.database.TypeTypeDatabase/25.json b/core/data/schemas/dev.typetype.android.data.database.TypeTypeDatabase/25.json new file mode 100644 index 00000000..b39159da --- /dev/null +++ b/core/data/schemas/dev.typetype.android.data.database.TypeTypeDatabase/25.json @@ -0,0 +1,2298 @@ +{ + "formatVersion": 1, + "database": { + "version": 25, + "identityHash": "413096956a06971cdaffacfb8ee3f32e", + "entities": [ + { + "tableName": "servers", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `baseUrl` TEXT NOT NULL, `displayName` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `tagline` TEXT, `version` TEXT NOT NULL DEFAULT '', `revision` TEXT NOT NULL DEFAULT '', `apiVersion` INTEGER NOT NULL DEFAULT 0, `logoUrl` TEXT, `bannerUrl` TEXT, `supportedServicesCsv` TEXT NOT NULL DEFAULT '', `minAndroidClientVersion` TEXT, `registrationAllowed` INTEGER NOT NULL DEFAULT 0, `guestAllowed` INTEGER NOT NULL DEFAULT 0, `localLoginEnabled` INTEGER NOT NULL DEFAULT 1, `oidcEnabled` INTEGER NOT NULL DEFAULT 0, `oidcProviderName` TEXT, `oidcAutoRedirect` INTEGER NOT NULL DEFAULT 0, `youtubeRemoteLoginSupported` INTEGER NOT NULL DEFAULT 0, `youtubeRemoteLoginEnabled` INTEGER NOT NULL DEFAULT 0, `youtubeRemoteLoginReady` INTEGER NOT NULL DEFAULT 0, `youtubeRemoteLoginUnavailableReason` TEXT, `rssEnabled` INTEGER NOT NULL DEFAULT 0, `rssMaxFeedsPerUser` INTEGER NOT NULL DEFAULT 0, `rssMaxItems` INTEGER NOT NULL DEFAULT 0, `rssMinimumPollMinutes` INTEGER NOT NULL DEFAULT 0, `rssRateLimitPerMinute` INTEGER NOT NULL DEFAULT 0, `pushEnabled` INTEGER NOT NULL DEFAULT 0, `pushProvider` TEXT NOT NULL DEFAULT 'unifiedpush', `pushEventTypesCsv` TEXT NOT NULL DEFAULT '', `pushMaxDevicesPerAccount` INTEGER NOT NULL DEFAULT 0, `recommenderInstalled` INTEGER NOT NULL DEFAULT 0, `recommenderEnabled` INTEGER NOT NULL DEFAULT 0, `recommenderExperimental` INTEGER NOT NULL DEFAULT 0, `twitchEnabled` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseUrl", + "columnName": "baseUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "addedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tagline", + "columnName": "tagline", + "affinity": "TEXT" + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "revision", + "columnName": "revision", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "apiVersion", + "columnName": "apiVersion", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "logoUrl", + "columnName": "logoUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "bannerUrl", + "columnName": "bannerUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "supportedServicesCsv", + "columnName": "supportedServicesCsv", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "minAndroidClientVersion", + "columnName": "minAndroidClientVersion", + "affinity": "TEXT" + }, + { + "fieldPath": "registrationAllowed", + "columnName": "registrationAllowed", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "guestAllowed", + "columnName": "guestAllowed", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "localLoginEnabled", + "columnName": "localLoginEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "oidcEnabled", + "columnName": "oidcEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "oidcProviderName", + "columnName": "oidcProviderName", + "affinity": "TEXT" + }, + { + "fieldPath": "oidcAutoRedirect", + "columnName": "oidcAutoRedirect", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "youtubeRemoteLoginSupported", + "columnName": "youtubeRemoteLoginSupported", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "youtubeRemoteLoginEnabled", + "columnName": "youtubeRemoteLoginEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "youtubeRemoteLoginReady", + "columnName": "youtubeRemoteLoginReady", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "youtubeRemoteLoginUnavailableReason", + "columnName": "youtubeRemoteLoginUnavailableReason", + "affinity": "TEXT" + }, + { + "fieldPath": "rssEnabled", + "columnName": "rssEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rssMaxFeedsPerUser", + "columnName": "rssMaxFeedsPerUser", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rssMaxItems", + "columnName": "rssMaxItems", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rssMinimumPollMinutes", + "columnName": "rssMinimumPollMinutes", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rssRateLimitPerMinute", + "columnName": "rssRateLimitPerMinute", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "pushEnabled", + "columnName": "pushEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "pushProvider", + "columnName": "pushProvider", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'unifiedpush'" + }, + { + "fieldPath": "pushEventTypesCsv", + "columnName": "pushEventTypesCsv", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "pushMaxDevicesPerAccount", + "columnName": "pushMaxDevicesPerAccount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "recommenderInstalled", + "columnName": "recommenderInstalled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "recommenderEnabled", + "columnName": "recommenderEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "recommenderExperimental", + "columnName": "recommenderExperimental", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "twitchEnabled", + "columnName": "twitchEnabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "favorites", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `videoUrl` TEXT NOT NULL, `favoritedAtMillis` INTEGER NOT NULL, `title` TEXT NOT NULL DEFAULT '', `thumbnailUrl` TEXT NOT NULL DEFAULT '', `durationSeconds` INTEGER NOT NULL DEFAULT 0, `channelName` TEXT NOT NULL DEFAULT '', `channelUrl` TEXT NOT NULL DEFAULT '', `channelAvatarUrl` TEXT NOT NULL DEFAULT '', `viewCount` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`serverId`, `accountId`, `videoUrl`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "favoritedAtMillis", + "columnName": "favoritedAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "videoUrl" + ] + }, + "indices": [ + { + "name": "index_favorites_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "history", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `id` TEXT NOT NULL, `url` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `channelName` TEXT NOT NULL, `channelUrl` TEXT NOT NULL DEFAULT '', `channelAvatarUrl` TEXT NOT NULL DEFAULT '', `durationSeconds` INTEGER NOT NULL, `progressSeconds` INTEGER NOT NULL, `watchedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `id`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "progressSeconds", + "columnName": "progressSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "watchedAtMillis", + "columnName": "watchedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "id" + ] + }, + "indices": [ + { + "name": "index_history_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_history_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + }, + { + "name": "index_history_serverId_accountId_url", + "unique": false, + "columnNames": [ + "serverId", + "accountId", + "url" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_history_serverId_accountId_url` ON `${TABLE_NAME}` (`serverId`, `accountId`, `url`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "watch_later", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `url` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `durationSeconds` INTEGER NOT NULL, `addedAtMillis` INTEGER NOT NULL, `channelName` TEXT NOT NULL DEFAULT '', `channelUrl` TEXT NOT NULL DEFAULT '', `channelAvatarUrl` TEXT NOT NULL DEFAULT '', `viewCount` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`serverId`, `accountId`, `url`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addedAtMillis", + "columnName": "addedAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "url" + ] + }, + "indices": [ + { + "name": "index_watch_later_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_watch_later_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "playlists", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`cacheKey` TEXT NOT NULL, `serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `id` TEXT NOT NULL, `name` TEXT NOT NULL, `description` TEXT NOT NULL, `createdAtMillis` INTEGER NOT NULL, `videoCount` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`cacheKey`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "cacheKey", + "columnName": "cacheKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "description", + "columnName": "description", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "videoCount", + "columnName": "videoCount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "cacheKey" + ] + }, + "indices": [ + { + "name": "index_playlists_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_playlists_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + }, + { + "name": "index_playlists_serverId_accountId_id", + "unique": true, + "columnNames": [ + "serverId", + "accountId", + "id" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playlists_serverId_accountId_id` ON `${TABLE_NAME}` (`serverId`, `accountId`, `id`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "playlist_videos", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`playlistCacheKey` TEXT NOT NULL, `playlistId` TEXT NOT NULL, `id` TEXT NOT NULL, `url` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `durationSeconds` INTEGER NOT NULL, `position` INTEGER NOT NULL, `channelName` TEXT NOT NULL DEFAULT '', `channelUrl` TEXT NOT NULL DEFAULT '', `channelAvatarUrl` TEXT NOT NULL DEFAULT '', `viewCount` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`playlistCacheKey`, `id`), FOREIGN KEY(`playlistCacheKey`) REFERENCES `playlists`(`cacheKey`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "playlistCacheKey", + "columnName": "playlistCacheKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "playlistId", + "columnName": "playlistId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "playlistCacheKey", + "id" + ] + }, + "indices": [ + { + "name": "index_playlist_videos_playlistCacheKey", + "unique": false, + "columnNames": [ + "playlistCacheKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_playlist_videos_playlistCacheKey` ON `${TABLE_NAME}` (`playlistCacheKey`)" + } + ], + "foreignKeys": [ + { + "table": "playlists", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "playlistCacheKey" + ], + "referencedColumns": [ + "cacheKey" + ] + } + ] + }, + { + "tableName": "video_meta", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `videoUrl` TEXT NOT NULL, `channelName` TEXT NOT NULL, `channelUrl` TEXT NOT NULL, `channelAvatarUrl` TEXT NOT NULL, `viewCount` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `videoUrl`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "videoUrl" + ] + }, + "indices": [ + { + "name": "index_video_meta_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_video_meta_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "accounts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `publicUsername` TEXT, `role` TEXT, `avatarUrl` TEXT, `avatarType` TEXT, `avatarCode` TEXT, `isGuest` INTEGER NOT NULL, `lastUsedAt` INTEGER NOT NULL, `sessionGeneration` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`serverId`, `accountId`), FOREIGN KEY(`serverId`) REFERENCES `servers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicUsername", + "columnName": "publicUsername", + "affinity": "TEXT" + }, + { + "fieldPath": "role", + "columnName": "role", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarType", + "columnName": "avatarType", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarCode", + "columnName": "avatarCode", + "affinity": "TEXT" + }, + { + "fieldPath": "isGuest", + "columnName": "isGuest", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUsedAt", + "columnName": "lastUsedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sessionGeneration", + "columnName": "sessionGeneration", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId" + ] + }, + "indices": [ + { + "name": "index_accounts_serverId", + "unique": false, + "columnNames": [ + "serverId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_accounts_serverId` ON `${TABLE_NAME}` (`serverId`)" + } + ], + "foreignKeys": [ + { + "table": "servers", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "downloads", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `sessionGeneration` INTEGER NOT NULL DEFAULT 0, `requestId` TEXT NOT NULL, `workId` TEXT NOT NULL, `videoUrl` TEXT NOT NULL, `title` TEXT NOT NULL, `quality` TEXT NOT NULL, `serverJobId` TEXT, `systemDownloadId` INTEGER, `fileName` TEXT, `status` TEXT NOT NULL, `progressPercent` INTEGER, `stage` TEXT, `errorMessage` TEXT, `cached` INTEGER NOT NULL, `createdAtMillis` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `requestId`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionGeneration", + "columnName": "sessionGeneration", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "workId", + "columnName": "workId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "quality", + "columnName": "quality", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "serverJobId", + "columnName": "serverJobId", + "affinity": "TEXT" + }, + { + "fieldPath": "systemDownloadId", + "columnName": "systemDownloadId", + "affinity": "INTEGER" + }, + { + "fieldPath": "fileName", + "columnName": "fileName", + "affinity": "TEXT" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "progressPercent", + "columnName": "progressPercent", + "affinity": "INTEGER" + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "TEXT" + }, + { + "fieldPath": "errorMessage", + "columnName": "errorMessage", + "affinity": "TEXT" + }, + { + "fieldPath": "cached", + "columnName": "cached", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "requestId" + ] + }, + "indices": [ + { + "name": "index_downloads_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + }, + { + "name": "index_downloads_workId", + "unique": true, + "columnNames": [ + "workId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_downloads_workId` ON `${TABLE_NAME}` (`workId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "progress_outbox", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `videoUrl` TEXT NOT NULL, `positionMillis` INTEGER NOT NULL, `sessionGeneration` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `videoUrl`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "positionMillis", + "columnName": "positionMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sessionGeneration", + "columnName": "sessionGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "videoUrl" + ] + }, + "indices": [ + { + "name": "index_progress_outbox_serverId_accountId_sessionGeneration", + "unique": false, + "columnNames": [ + "serverId", + "accountId", + "sessionGeneration" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_progress_outbox_serverId_accountId_sessionGeneration` ON `${TABLE_NAME}` (`serverId`, `accountId`, `sessionGeneration`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "library_sync_state", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `collection` TEXT NOT NULL, `refreshGeneration` INTEGER NOT NULL, `lastAttemptAtMillis` INTEGER NOT NULL, `lastSuccessAtMillis` INTEGER, `lastFailureAtMillis` INTEGER, `failureCode` TEXT, `failureStatusCode` INTEGER, `requestId` TEXT, PRIMARY KEY(`serverId`, `accountId`, `collection`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "collection", + "columnName": "collection", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "refreshGeneration", + "columnName": "refreshGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAttemptAtMillis", + "columnName": "lastAttemptAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSuccessAtMillis", + "columnName": "lastSuccessAtMillis", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastFailureAtMillis", + "columnName": "lastFailureAtMillis", + "affinity": "INTEGER" + }, + { + "fieldPath": "failureCode", + "columnName": "failureCode", + "affinity": "TEXT" + }, + { + "fieldPath": "failureStatusCode", + "columnName": "failureStatusCode", + "affinity": "INTEGER" + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "collection" + ] + }, + "indices": [ + { + "name": "index_library_sync_state_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_library_sync_state_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "library_mutation_outbox", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `mutationKey` TEXT NOT NULL, `collection` TEXT NOT NULL, `kind` TEXT NOT NULL, `targetId` TEXT NOT NULL, `parentId` TEXT, `desiredPresent` INTEGER NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `durationSeconds` INTEGER NOT NULL, `channelName` TEXT NOT NULL, `channelUrl` TEXT NOT NULL, `channelAvatarUrl` TEXT NOT NULL, `viewCount` INTEGER NOT NULL, `sessionGeneration` INTEGER NOT NULL, `mutationVersion` INTEGER NOT NULL, `state` TEXT NOT NULL, `createdAtMillis` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, `lastAttemptAtMillis` INTEGER, `attemptCount` INTEGER NOT NULL, `failureCode` TEXT, `failureStatusCode` INTEGER, `requestId` TEXT, PRIMARY KEY(`serverId`, `accountId`, `mutationKey`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mutationKey", + "columnName": "mutationKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "collection", + "columnName": "collection", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "targetId", + "columnName": "targetId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentId", + "columnName": "parentId", + "affinity": "TEXT" + }, + { + "fieldPath": "desiredPresent", + "columnName": "desiredPresent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelAvatarUrl", + "columnName": "channelAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sessionGeneration", + "columnName": "sessionGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mutationVersion", + "columnName": "mutationVersion", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAttemptAtMillis", + "columnName": "lastAttemptAtMillis", + "affinity": "INTEGER" + }, + { + "fieldPath": "attemptCount", + "columnName": "attemptCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureCode", + "columnName": "failureCode", + "affinity": "TEXT" + }, + { + "fieldPath": "failureStatusCode", + "columnName": "failureStatusCode", + "affinity": "INTEGER" + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "mutationKey" + ] + }, + "indices": [ + { + "name": "index_library_mutation_outbox_serverId_accountId_sessionGeneration_state", + "unique": false, + "columnNames": [ + "serverId", + "accountId", + "sessionGeneration", + "state" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_library_mutation_outbox_serverId_accountId_sessionGeneration_state` ON `${TABLE_NAME}` (`serverId`, `accountId`, `sessionGeneration`, `state`)" + }, + { + "name": "index_library_mutation_outbox_serverId_accountId_collection", + "unique": false, + "columnNames": [ + "serverId", + "accountId", + "collection" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_library_mutation_outbox_serverId_accountId_collection` ON `${TABLE_NAME}` (`serverId`, `accountId`, `collection`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "subscriptions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `channelUrl` TEXT NOT NULL, `name` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, `subscribedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `channelUrl`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "channelUrl", + "columnName": "channelUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subscribedAtMillis", + "columnName": "subscribedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "channelUrl" + ] + }, + "indices": [ + { + "name": "index_subscriptions_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_subscriptions_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "playback_resume", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `videoUrl` TEXT NOT NULL, `positionMillis` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "positionMillis", + "columnName": "positionMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId" + ] + }, + "indices": [ + { + "name": "index_playback_resume_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_resume_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "playback_queue", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `position` INTEGER NOT NULL, `currentIndex` INTEGER NOT NULL, `queueTitle` TEXT NOT NULL, `repeatMode` TEXT NOT NULL DEFAULT 'Off', `videoUrl` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `durationSeconds` INTEGER NOT NULL, `channelName` TEXT NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `position`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentIndex", + "columnName": "currentIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "queueTitle", + "columnName": "queueTitle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "repeatMode", + "columnName": "repeatMode", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'Off'" + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "channelName", + "columnName": "channelName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "position" + ] + }, + "indices": [ + { + "name": "index_playback_queue_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_queue_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "saved_public_playlists", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `id` TEXT NOT NULL, `publicPlaylistId` TEXT NOT NULL, `url` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `uploaderName` TEXT NOT NULL, `streamCount` INTEGER NOT NULL, `playlistType` TEXT NOT NULL, `savedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `id`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicPlaylistId", + "columnName": "publicPlaylistId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uploaderName", + "columnName": "uploaderName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "streamCount", + "columnName": "streamCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "playlistType", + "columnName": "playlistType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "savedAtMillis", + "columnName": "savedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "id" + ] + }, + "indices": [ + { + "name": "index_saved_public_playlists_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_saved_public_playlists_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + }, + { + "name": "index_saved_public_playlists_serverId_accountId_url", + "unique": true, + "columnNames": [ + "serverId", + "accountId", + "url" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_saved_public_playlists_serverId_accountId_url` ON `${TABLE_NAME}` (`serverId`, `accountId`, `url`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "feed_videos", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `feed` TEXT NOT NULL, `position` INTEGER NOT NULL, `videoUrl` TEXT NOT NULL, `videoId` TEXT NOT NULL, `title` TEXT NOT NULL, `thumbnailUrl` TEXT NOT NULL, `uploaderName` TEXT NOT NULL, `uploaderUrl` TEXT NOT NULL, `uploaderAvatarUrl` TEXT NOT NULL, `uploaderVerified` INTEGER NOT NULL, `durationSeconds` INTEGER NOT NULL, `isLive` INTEGER NOT NULL, `viewCount` INTEGER NOT NULL, `uploadedAtMillis` INTEGER NOT NULL, `isShortFormContent` INTEGER NOT NULL, `shortDescription` TEXT, `publishedAtMillis` INTEGER, `isPostLive` INTEGER NOT NULL, `isLiveContent` INTEGER NOT NULL, `requiresMembership` INTEGER NOT NULL, `savedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `feed`, `videoUrl`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "feed", + "columnName": "feed", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "videoUrl", + "columnName": "videoUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "videoId", + "columnName": "videoId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "thumbnailUrl", + "columnName": "thumbnailUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uploaderName", + "columnName": "uploaderName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uploaderUrl", + "columnName": "uploaderUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uploaderAvatarUrl", + "columnName": "uploaderAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "uploaderVerified", + "columnName": "uploaderVerified", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "durationSeconds", + "columnName": "durationSeconds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLive", + "columnName": "isLive", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "viewCount", + "columnName": "viewCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "uploadedAtMillis", + "columnName": "uploadedAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isShortFormContent", + "columnName": "isShortFormContent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "shortDescription", + "columnName": "shortDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "publishedAtMillis", + "columnName": "publishedAtMillis", + "affinity": "INTEGER" + }, + { + "fieldPath": "isPostLive", + "columnName": "isPostLive", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLiveContent", + "columnName": "isLiveContent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresMembership", + "columnName": "requiresMembership", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "savedAtMillis", + "columnName": "savedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "feed", + "videoUrl" + ] + }, + "indices": [ + { + "name": "index_feed_videos_serverId_accountId_feed", + "unique": false, + "columnNames": [ + "serverId", + "accountId", + "feed" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_feed_videos_serverId_accountId_feed` ON `${TABLE_NAME}` (`serverId`, `accountId`, `feed`)" + }, + { + "name": "index_feed_videos_serverId_accountId_feed_position", + "unique": true, + "columnNames": [ + "serverId", + "accountId", + "feed", + "position" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_feed_videos_serverId_accountId_feed_position` ON `${TABLE_NAME}` (`serverId`, `accountId`, `feed`, `position`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + }, + { + "tableName": "youtube_takeout_imports", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`serverId` TEXT NOT NULL, `accountId` TEXT NOT NULL, `sessionGeneration` INTEGER NOT NULL, `requestId` TEXT NOT NULL, `workId` TEXT NOT NULL, `documentUri` TEXT NOT NULL, `displayName` TEXT NOT NULL, `sizeBytes` INTEGER, `serverJobId` TEXT, `status` TEXT NOT NULL, `phase` TEXT, `progressPercent` INTEGER, `previewSubscriptions` INTEGER, `previewPlaylists` INTEGER, `previewPlaylistItems` INTEGER, `previewFavorites` INTEGER, `previewWatchLater` INTEGER, `previewHistory` INTEGER, `importedCount` INTEGER, `skippedCount` INTEGER, `failedCount` INTEGER, `warningCount` INTEGER NOT NULL, `errorCount` INTEGER NOT NULL, `failureCode` TEXT, `failureRequestId` TEXT, `collectionsRefreshed` INTEGER NOT NULL, `createdAtMillis` INTEGER NOT NULL, `updatedAtMillis` INTEGER NOT NULL, PRIMARY KEY(`serverId`, `accountId`, `requestId`), FOREIGN KEY(`serverId`, `accountId`) REFERENCES `accounts`(`serverId`, `accountId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "serverId", + "columnName": "serverId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sessionGeneration", + "columnName": "sessionGeneration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requestId", + "columnName": "requestId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "workId", + "columnName": "workId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "documentUri", + "columnName": "documentUri", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sizeBytes", + "columnName": "sizeBytes", + "affinity": "INTEGER" + }, + { + "fieldPath": "serverJobId", + "columnName": "serverJobId", + "affinity": "TEXT" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "phase", + "columnName": "phase", + "affinity": "TEXT" + }, + { + "fieldPath": "progressPercent", + "columnName": "progressPercent", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewSubscriptions", + "columnName": "previewSubscriptions", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewPlaylists", + "columnName": "previewPlaylists", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewPlaylistItems", + "columnName": "previewPlaylistItems", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewFavorites", + "columnName": "previewFavorites", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewWatchLater", + "columnName": "previewWatchLater", + "affinity": "INTEGER" + }, + { + "fieldPath": "previewHistory", + "columnName": "previewHistory", + "affinity": "INTEGER" + }, + { + "fieldPath": "importedCount", + "columnName": "importedCount", + "affinity": "INTEGER" + }, + { + "fieldPath": "skippedCount", + "columnName": "skippedCount", + "affinity": "INTEGER" + }, + { + "fieldPath": "failedCount", + "columnName": "failedCount", + "affinity": "INTEGER" + }, + { + "fieldPath": "warningCount", + "columnName": "warningCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "errorCount", + "columnName": "errorCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failureCode", + "columnName": "failureCode", + "affinity": "TEXT" + }, + { + "fieldPath": "failureRequestId", + "columnName": "failureRequestId", + "affinity": "TEXT" + }, + { + "fieldPath": "collectionsRefreshed", + "columnName": "collectionsRefreshed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAtMillis", + "columnName": "updatedAtMillis", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "serverId", + "accountId", + "requestId" + ] + }, + "indices": [ + { + "name": "index_youtube_takeout_imports_serverId_accountId", + "unique": false, + "columnNames": [ + "serverId", + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_youtube_takeout_imports_serverId_accountId` ON `${TABLE_NAME}` (`serverId`, `accountId`)" + }, + { + "name": "index_youtube_takeout_imports_workId", + "unique": true, + "columnNames": [ + "workId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_youtube_takeout_imports_workId` ON `${TABLE_NAME}` (`workId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "serverId", + "accountId" + ], + "referencedColumns": [ + "serverId", + "accountId" + ] + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '413096956a06971cdaffacfb8ee3f32e')" + ] + } +} \ No newline at end of file diff --git a/core/data/src/androidTest/java/dev/typetype/android/data/database/ContinueWatchingCacheTest.kt b/core/data/src/androidTest/java/dev/typetype/android/data/database/ContinueWatchingCacheTest.kt index 03eb0dd2..d941e077 100644 --- a/core/data/src/androidTest/java/dev/typetype/android/data/database/ContinueWatchingCacheTest.kt +++ b/core/data/src/androidTest/java/dev/typetype/android/data/database/ContinueWatchingCacheTest.kt @@ -56,9 +56,14 @@ class ContinueWatchingCacheTest { dao.upsert(history(id = "older-active", duration = 60, progress = 53, watchedAt = 2)) dao.upsert(history(id = "newer-active", duration = 120, progress = 59, watchedAt = 3)) - val items = dao.observeContinueWatching(SERVER_ID, ACCOUNT_ID, limit = 2).first() + val items = dao.observeContinueWatching(SERVER_ID, ACCOUNT_ID, limit = 2, threshold = 0).first() + val untilTheEnd = dao.observeContinueWatching(SERVER_ID, ACCOUNT_ID, limit = 5, threshold = 100).first() assertEquals(listOf("newer-active", "older-active"), items.map { it.id }) + assertEquals( + listOf("long-finished", "short-finished", "newer-active", "older-active"), + untilTheEnd.map { it.id }, + ) } private fun history( diff --git a/core/data/src/androidTest/java/dev/typetype/android/data/database/HistoryPagingDaoTest.kt b/core/data/src/androidTest/java/dev/typetype/android/data/database/HistoryPagingDaoTest.kt index 93d5072e..64fb3592 100644 --- a/core/data/src/androidTest/java/dev/typetype/android/data/database/HistoryPagingDaoTest.kt +++ b/core/data/src/androidTest/java/dev/typetype/android/data/database/HistoryPagingDaoTest.kt @@ -77,7 +77,8 @@ class HistoryPagingDaoTest { assertEquals(listOf("Alpha", "Beta"), result.data.map { it.title }) assertEquals(3, dao.observeCount(SERVER_ID, ACCOUNT_ID).first()) - assertEquals(listOf("url-a"), dao.observeWatchedUrls(SERVER_ID, ACCOUNT_ID).first()) + assertEquals(setOf("url-z", "url-a"), dao.observeWatchedUrls(SERVER_ID, ACCOUNT_ID, threshold = 0).first().toSet()) + assertEquals(listOf("url-a"), dao.observeWatchedUrls(SERVER_ID, ACCOUNT_ID, threshold = 90).first()) } private fun history( diff --git a/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrationTest.kt b/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrationTest.kt index 305e7427..56448efe 100644 --- a/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrationTest.kt +++ b/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrationTest.kt @@ -316,7 +316,7 @@ class TypeTypeDatabaseMigrationTest { private companion object { const val DATABASE_NAME = "migration-test.db" const val FIRST_RETAINED_VERSION = 1 - const val CURRENT_VERSION = 24 + const val CURRENT_VERSION = 25 const val DRAFT_VERSION_10_SERVERS = "CREATE TABLE `servers` (" + "`id` TEXT NOT NULL, `baseUrl` TEXT NOT NULL, `displayName` TEXT NOT NULL, " + diff --git a/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseTwitchMigrationTest.kt b/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseTwitchMigrationTest.kt new file mode 100644 index 00000000..baa78a25 --- /dev/null +++ b/core/data/src/androidTest/java/dev/typetype/android/data/database/TypeTypeDatabaseTwitchMigrationTest.kt @@ -0,0 +1,55 @@ +package dev.typetype.android.data.database + +import androidx.room.testing.MigrationTestHelper +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class TypeTypeDatabaseTwitchMigrationTest { + @get:Rule + val helper = MigrationTestHelper( + instrumentation = InstrumentationRegistry.getInstrumentation(), + databaseClass = TypeTypeDatabase::class.java, + ) + + @After + fun deleteDatabase() { + ApplicationProvider.getApplicationContext().deleteDatabase(DATABASE_NAME) + } + + @Test + fun migratesVersion24WithTwitchUnavailable() { + helper.createDatabase(DATABASE_NAME, 24).apply { + execSQL( + "INSERT INTO servers(id, baseUrl, displayName, addedAt) " + + "VALUES('instance-a', 'https://example.test/api', 'TypeType', 1)", + ) + close() + } + + val migrated = helper.runMigrationsAndValidate( + DATABASE_NAME, + 25, + true, + TypeTypeDatabaseMigrations.MIGRATION_24_25, + ) + + migrated.query("SELECT displayName, twitchEnabled FROM servers WHERE id = 'instance-a'").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals("TypeType", cursor.getString(0)) + assertEquals(0, cursor.getInt(1)) + } + migrated.close() + } + + private companion object { + const val DATABASE_NAME = "twitch-migration-test.db" + } +} diff --git a/core/data/src/main/java/dev/typetype/android/core/di/TwitchModule.kt b/core/data/src/main/java/dev/typetype/android/core/di/TwitchModule.kt new file mode 100644 index 00000000..f472ad67 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/core/di/TwitchModule.kt @@ -0,0 +1,23 @@ +package dev.typetype.android.core.di + +import dagger.Binds +import dagger.Module +import dagger.hilt.InstallIn +import dagger.hilt.components.SingletonComponent +import dev.typetype.android.data.twitch.RemoteTwitchAccountRepository +import dev.typetype.android.data.twitch.RemoteTwitchRepository +import dev.typetype.android.domain.twitch.TwitchAccountRepository +import dev.typetype.android.domain.twitch.TwitchRepository +import javax.inject.Singleton + +@Module +@InstallIn(SingletonComponent::class) +abstract class TwitchModule { + @Binds + @Singleton + abstract fun bindTwitchRepository(impl: RemoteTwitchRepository): TwitchRepository + + @Binds + @Singleton + abstract fun bindTwitchAccountRepository(impl: RemoteTwitchAccountRepository): TwitchAccountRepository +} diff --git a/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabase.kt b/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabase.kt index 3d1dee70..ed9bca35 100644 --- a/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabase.kt +++ b/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabase.kt @@ -60,7 +60,7 @@ import dev.typetype.android.data.subscriptions.SubscriptionEntity FeedVideoEntity::class, YoutubeTakeoutImportEntity::class, ], - version = 24, + version = 25, exportSchema = true, autoMigrations = [ AutoMigration(from = 1, to = 2), diff --git a/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrations.kt b/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrations.kt index 596c843f..01208df4 100644 --- a/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrations.kt +++ b/core/data/src/main/java/dev/typetype/android/data/database/TypeTypeDatabaseMigrations.kt @@ -191,6 +191,12 @@ object TypeTypeDatabaseMigrations { } } + val MIGRATION_24_25 = object : Migration(24, 25) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `servers` ADD COLUMN `twitchEnabled` INTEGER NOT NULL DEFAULT 0") + } + } + val ALL = arrayOf( MIGRATION_7_8, MIGRATION_11_12, @@ -205,5 +211,6 @@ object TypeTypeDatabaseMigrations { MIGRATION_21_22, MIGRATION_22_23, MIGRATION_23_24, + MIGRATION_24_25, ) } diff --git a/core/data/src/main/java/dev/typetype/android/data/library/LibraryCacheObserver.kt b/core/data/src/main/java/dev/typetype/android/data/library/LibraryCacheObserver.kt index 8fac7614..f3de8815 100644 --- a/core/data/src/main/java/dev/typetype/android/data/library/LibraryCacheObserver.kt +++ b/core/data/src/main/java/dev/typetype/android/data/library/LibraryCacheObserver.kt @@ -4,6 +4,7 @@ import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.map +import dev.typetype.android.data.account.AccountScope import dev.typetype.android.data.account.ActiveAccountScope import dev.typetype.android.data.library.local.FavoritesDao import dev.typetype.android.data.library.local.HistoryDao @@ -14,12 +15,16 @@ import dev.typetype.android.domain.library.HistoryItem import dev.typetype.android.domain.library.HistoryQuery import dev.typetype.android.domain.library.Playlist import dev.typetype.android.domain.library.WatchLaterItem +import dev.typetype.android.domain.usersettings.UserSettingsRepository import javax.inject.Inject import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onStart @OptIn(ExperimentalCoroutinesApi::class) class LibraryCacheObserver @Inject constructor( @@ -28,6 +33,7 @@ class LibraryCacheObserver @Inject constructor( private val favoritesDao: FavoritesDao, private val watchLaterDao: WatchLaterDao, private val playlistsDao: PlaylistsDao, + private val userSettings: UserSettingsRepository, ) { fun history(query: HistoryQuery): Flow> = activeAccountScope.observe().flatMapLatest { scope -> @@ -61,20 +67,27 @@ class LibraryCacheObserver @Inject constructor( else historyDao.observeCount(scope.serverId, scope.accountId) } - fun watchedUrls(): Flow> = activeAccountScope.observe().flatMapLatest { scope -> + fun watchedUrls(): Flow> = withThreshold { scope, threshold -> if (scope == null) flowOf(emptySet()) - else historyDao.observeWatchedUrls(scope.serverId, scope.accountId).map { it.toSet() } + else historyDao.observeWatchedUrls(scope.serverId, scope.accountId, threshold).map { it.toSet() } } - fun continueWatching(limit: Int): Flow> = - activeAccountScope.observe().flatMapLatest { scope -> - if (scope == null) { - flowOf(emptyList()) - } else { - historyDao.observeContinueWatching(scope.serverId, scope.accountId, limit) - .map { rows -> rows.map { it.toDomain() } } - } + fun continueWatching(limit: Int): Flow> = withThreshold { scope, threshold -> + if (scope == null) { + flowOf(emptyList()) + } else { + historyDao.observeContinueWatching(scope.serverId, scope.accountId, limit, threshold) + .map { rows -> rows.map { it.toDomain() } } } + } + + private fun withThreshold(block: (AccountScope?, Int) -> Flow): Flow = + combine( + activeAccountScope.observe(), + userSettings.observe().map { it.watchedThresholdPercent }.onStart { emit(0) }.distinctUntilChanged(), + ) { scope, threshold -> scope to threshold } + .distinctUntilChanged() + .flatMapLatest { (scope, threshold) -> block(scope, threshold) } fun favorites(): Flow> = scoped { serverId, accountId -> favoritesDao.observeAll(serverId, accountId) diff --git a/core/data/src/main/java/dev/typetype/android/data/library/local/HistoryDao.kt b/core/data/src/main/java/dev/typetype/android/data/library/local/HistoryDao.kt index 846a261f..d519c282 100644 --- a/core/data/src/main/java/dev/typetype/android/data/library/local/HistoryDao.kt +++ b/core/data/src/main/java/dev/typetype/android/data/library/local/HistoryDao.kt @@ -51,21 +51,20 @@ interface HistoryDao { @Query( "SELECT url FROM history WHERE serverId = :serverId AND accountId = :accountId " + - "AND durationSeconds > 0 AND progressSeconds * 10 >= durationSeconds * 9", + "AND progressSeconds > 0 AND durationSeconds > 0 AND $WATCHED", ) - fun observeWatchedUrls(serverId: String, accountId: String): Flow> + fun observeWatchedUrls(serverId: String, accountId: String, threshold: Int): Flow> @Query( "SELECT * FROM history WHERE serverId = :serverId AND accountId = :accountId " + - "AND progressSeconds > 0 AND durationSeconds > 0 " + - "AND ((durationSeconds > 60 AND progressSeconds < durationSeconds - 60) " + - "OR (durationSeconds <= 60 AND progressSeconds * 10 < durationSeconds * 9)) " + + "AND progressSeconds > 0 AND durationSeconds > 0 AND NOT $WATCHED " + "ORDER BY watchedAtMillis DESC, id DESC LIMIT :limit", ) fun observeContinueWatching( serverId: String, accountId: String, limit: Int, + threshold: Int, ): Flow> @Query( @@ -113,3 +112,11 @@ interface HistoryDao { items.forEach { upsert(it) } } } + +// The web's rule (lib/watch-progress.ts isVideoWatched): the share chosen in the profile settings, or else the last +// minute of the video (the last tenth of a video shorter than a minute). +private const val WATCHED = + "(CASE WHEN :threshold BETWEEN 50 AND 100 " + + "THEN MIN(progressSeconds, durationSeconds) * 100 >= durationSeconds * :threshold " + + "WHEN durationSeconds > 60 THEN progressSeconds >= durationSeconds - 60 " + + "ELSE progressSeconds * 10 >= durationSeconds * 9 END)" diff --git a/core/data/src/main/java/dev/typetype/android/data/livechat/RemoteLiveChatRepository.kt b/core/data/src/main/java/dev/typetype/android/data/livechat/RemoteLiveChatRepository.kt index fe8dcd36..1c0dfd0e 100644 --- a/core/data/src/main/java/dev/typetype/android/data/livechat/RemoteLiveChatRepository.kt +++ b/core/data/src/main/java/dev/typetype/android/data/livechat/RemoteLiveChatRepository.kt @@ -5,6 +5,8 @@ import dev.typetype.android.data.network.TypeTypeApiHolder import dev.typetype.android.domain.livechat.LiveChatEvent import dev.typetype.android.domain.livechat.LiveChatRepository import dev.typetype.android.domain.livechat.LiveChatRequestException +import dev.typetype.android.domain.twitch.TwitchTarget +import dev.typetype.android.domain.twitch.TwitchUrls import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.Dispatchers @@ -25,7 +27,9 @@ class RemoteLiveChatRepository @Inject constructor( ) : LiveChatRepository { override fun connect(videoUrl: String): Flow = flow { val scope = activeAccountScope.require() - val response = apiHolder.requireLiveChat(scope).liveChat(videoUrl) + val twitchLogin = (TwitchUrls.parse(videoUrl) as? TwitchTarget.Live)?.login + val api = apiHolder.requireLiveChat(scope) + val response = if (twitchLogin != null) api.twitchChatEvents(twitchLogin) else api.liveChat(videoUrl) if (!response.isSuccessful) { response.errorBody()?.close() throw LiveChatRequestException(response.code(), "Live chat request failed (HTTP ${response.code()})") @@ -38,13 +42,21 @@ class RemoteLiveChatRepository @Inject constructor( // A blocked socket read only returns when the server writes, so closing the body is what stops it. val closer = launch { closeOnCancel(it) } try { - val parser = LiveChatSseParser(json) val source = it.source() - while (true) { - val line = source.readUtf8Line() ?: break - parser.accept(line.removeSuffix("\r"))?.let { event -> emit(event) } + if (twitchLogin != null) { + val parser = TwitchChatSseParser(json) + while (true) { + val line = source.readUtf8Line() ?: break + parser.accept(line.removeSuffix("\r"))?.let { event -> emit(event) } + } + } else { + val parser = LiveChatSseParser(json) + while (true) { + val line = source.readUtf8Line() ?: break + parser.accept(line.removeSuffix("\r"))?.let { event -> emit(event) } + } + parser.finish()?.let { event -> emit(event) } } - parser.finish()?.let { event -> emit(event) } } finally { closer.cancel() } 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 new file mode 100644 index 00000000..c90d128f --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/livechat/TwitchChatSseParser.kt @@ -0,0 +1,43 @@ +package dev.typetype.android.data.livechat + +import dev.typetype.android.data.network.dto.TwitchChatEventDto +import dev.typetype.android.domain.livechat.LiveChatEvent +import dev.typetype.android.domain.livechat.LiveChatMessage +import kotlinx.serialization.json.Json + +// Live relays the Twitch chat as server-sent events whose data is one chat event; the event name is not used. +internal class TwitchChatSseParser(private val json: Json) { + private val data = StringBuilder() + + fun accept(line: String): LiveChatEvent? { + if (line.isEmpty()) return dispatch() + if (line.startsWith("data:")) { + if (data.isNotEmpty()) data.append('\n') + data.append(line.removePrefix("data:").removePrefix(" ")) + } + return null + } + + private fun dispatch(): LiveChatEvent? { + val payload = data.toString() + data.setLength(0) + if (payload.isEmpty()) return null + val event = runCatching { json.decodeFromString(TwitchChatEventDto.serializer(), payload) }.getOrNull() ?: return null + return when (event.type) { + "message" -> event.text?.takeIf { it.isNotBlank() && !event.deleted }?.let { text -> + LiveChatEvent.Message( + LiveChatMessage( + id = event.id.orEmpty(), + text = text, + authorName = event.displayName?.ifBlank { null } ?: event.login, + authorAvatarUrl = null, + moderator = event.badges.any { it.startsWith("moderator/") || it.startsWith("broadcaster/") }, + ), + ) + } + "delete" -> event.targetId?.let(LiveChatEvent::Removed) + "clear" -> LiveChatEvent.Cleared(event.login) + else -> null + } + } +} diff --git a/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeApi.kt b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeApi.kt index 3f77bece..9a6885f6 100644 --- a/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeApi.kt +++ b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeApi.kt @@ -20,4 +20,5 @@ interface TypeTypeApi : TypeTypeAccountProfilesApi, TypeTypeLinkedSessionsApi, TypeTypeAllowedChannelsApi, - TypeTypeDeviceLinkApi + TypeTypeDeviceLinkApi, + TypeTypeTwitchApi diff --git a/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeLiveChatApi.kt b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeLiveChatApi.kt index 35d93623..86119a79 100644 --- a/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeLiveChatApi.kt +++ b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeLiveChatApi.kt @@ -4,6 +4,7 @@ import okhttp3.ResponseBody import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Header +import retrofit2.http.Path import retrofit2.http.Query import retrofit2.http.Streaming @@ -14,4 +15,11 @@ interface TypeTypeLiveChatApi { @Query("url") videoUrl: String, @Header("Accept") accept: String = "text/event-stream, application/json", ): Response + + @Streaming + @GET("twitch/chat/{login}/events") + suspend fun twitchChatEvents( + @Path("login") login: String, + @Header("Accept") accept: String = "text/event-stream", + ): Response } diff --git a/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeTwitchApi.kt b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeTwitchApi.kt new file mode 100644 index 00000000..f46d8053 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/network/TypeTypeTwitchApi.kt @@ -0,0 +1,152 @@ +package dev.typetype.android.data.network + +import dev.typetype.android.data.network.dto.TwitchAccountStatusDto +import dev.typetype.android.data.network.dto.TwitchChannelDto +import dev.typetype.android.data.network.dto.TwitchChatAssetsDto +import dev.typetype.android.data.network.dto.TwitchChatHighlightsDto +import dev.typetype.android.data.network.dto.TwitchChatSendRequest +import dev.typetype.android.data.network.dto.TwitchClipDto +import dev.typetype.android.data.network.dto.TwitchClipPlaybackDto +import dev.typetype.android.data.network.dto.TwitchDeviceCodeDto +import dev.typetype.android.data.network.dto.TwitchDevicePollDto +import dev.typetype.android.data.network.dto.TwitchDevicePollRequest +import dev.typetype.android.data.network.dto.TwitchFollowStateDto +import dev.typetype.android.data.network.dto.TwitchGameDto +import dev.typetype.android.data.network.dto.TwitchGameStreamsDto +import dev.typetype.android.data.network.dto.TwitchLiveDto +import dev.typetype.android.data.network.dto.TwitchPageDto +import dev.typetype.android.data.network.dto.TwitchPollVoteRequest +import dev.typetype.android.data.network.dto.TwitchStreamDto +import dev.typetype.android.data.network.dto.TwitchVideoChapterDto +import dev.typetype.android.data.network.dto.TwitchVideoCommentDto +import dev.typetype.android.data.network.dto.TwitchVideoDto +import dev.typetype.android.data.network.dto.TwitchVideoPlaybackDto +import retrofit2.Response +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.POST +import retrofit2.http.PUT +import retrofit2.http.Path +import retrofit2.http.Query + +interface TypeTypeTwitchApi { + @GET("twitch/streams") + suspend fun twitchStreams(@Query("after") after: String? = null, @Query("first") first: Int = TWITCH_PAGE): Response> + + @GET("twitch/games") + suspend fun twitchGames(@Query("after") after: String? = null, @Query("first") first: Int = TWITCH_PAGE): Response> + + @GET("twitch/games/{slug}/streams") + suspend fun twitchGameStreams( + @Path("slug") slug: String, + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response + + @GET("twitch/tags/{tag}/streams") + suspend fun twitchTagStreams( + @Path("tag") tag: String, + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response> + + @GET("twitch/channels/{login}") + suspend fun twitchChannel(@Path("login") login: String): Response + + @GET("twitch/channels/{login}/videos") + suspend fun twitchChannelVideos( + @Path("login") login: String, + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response> + + @GET("twitch/channels/{login}/clips") + suspend fun twitchChannelClips( + @Path("login") login: String, + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response> + + @GET("twitch/live/{login}") + suspend fun twitchLive(@Path("login") login: String): Response + + @GET("twitch/videos/{id}") + suspend fun twitchVideo(@Path("id") id: String): Response + + @GET("twitch/videos/{id}/chapters") + suspend fun twitchVideoChapters(@Path("id") id: String): Response> + + @GET("twitch/videos/{id}/comments") + suspend fun twitchVideoComments( + @Path("id") id: String, + @Query("offset") offset: Long? = null, + @Query("cursor") cursor: String? = null, + ): Response> + + @GET("twitch/clips/{slug}") + suspend fun twitchClip(@Path("slug") slug: String): Response + + @GET("twitch/search") + suspend fun twitchSearchChannels( + @Query("q") query: String, + @Query("type") type: String = "channels", + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response> + + @GET("twitch/search") + suspend fun twitchSearchStreams( + @Query("q") query: String, + @Query("type") type: String = "streams", + @Query("after") after: String? = null, + @Query("first") first: Int = TWITCH_PAGE, + ): Response> + + @GET("twitch/account") + suspend fun twitchAccount(): Response + + @POST("twitch/account/device") + suspend fun twitchStartDevice(): Response + + @POST("twitch/account/poll") + suspend fun twitchPollDevice(@Body body: TwitchDevicePollRequest): Response + + @POST("twitch/chat/{login}/messages") + suspend fun twitchSendChat(@Path("login") login: String, @Body body: TwitchChatSendRequest): Response + + @POST("twitch/polls/vote") + suspend fun twitchVotePoll(@Body body: TwitchPollVoteRequest): Response + + @DELETE("twitch/account") + suspend fun twitchUnlink(): Response + + @GET("twitch/me/live") + suspend fun twitchFollowedLives(@Query("after") after: String? = null): Response> + + @GET("twitch/me/videos") + suspend fun twitchFollowedVideos(@Query("after") after: String? = null): Response> + + @GET("twitch/me/follows") + suspend fun twitchFollows(@Query("after") after: String? = null): Response> + + @GET("twitch/me/follows/{login}") + suspend fun twitchFollowState(@Path("login") login: String): Response + + @PUT("twitch/me/follows/{login}") + suspend fun twitchFollow(@Path("login") login: String): Response + + @DELETE("twitch/me/follows/{login}") + suspend fun twitchUnfollow(@Path("login") login: String): Response + + @GET("twitch/chat/assets") + suspend fun twitchChatAssets(): Response + + @GET("twitch/chat/{login}/assets") + suspend fun twitchChannelChatAssets(@Path("login") login: String): Response + + @GET("twitch/chat/{login}/highlights") + suspend fun twitchChatHighlights(@Path("login") login: String): Response +} + +const val TWITCH_PAGE = 24 diff --git a/core/data/src/main/java/dev/typetype/android/data/network/dto/InstanceDto.kt b/core/data/src/main/java/dev/typetype/android/data/network/dto/InstanceDto.kt index bbbe2604..b23645a8 100644 --- a/core/data/src/main/java/dev/typetype/android/data/network/dto/InstanceDto.kt +++ b/core/data/src/main/java/dev/typetype/android/data/network/dto/InstanceDto.kt @@ -32,6 +32,7 @@ data class InstanceResponse( val rss: RssInstanceCapabilityDto? = null, val pushNotifications: PushCapabilityDto? = null, val recommender: RecommenderCapabilityDto? = null, + val twitch: TwitchCapabilityDto? = null, ) @Serializable @@ -51,6 +52,9 @@ data class PushCapabilityDto( val maxDevicesPerAccount: Int = 0, ) +@Serializable +data class TwitchCapabilityDto(val enabled: Boolean = false) + @Serializable data class RecommenderCapabilityDto( val installed: Boolean = false, diff --git a/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchAccountDto.kt b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchAccountDto.kt new file mode 100644 index 00000000..936e3956 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchAccountDto.kt @@ -0,0 +1,39 @@ +package dev.typetype.android.data.network.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class TwitchAccountStatusDto( + val linked: Boolean = false, + val login: String? = null, + val displayName: String? = null, + val avatarUrl: String? = null, +) + +@Serializable +data class TwitchDeviceCodeDto( + val deviceCode: String = "", + val userCode: String = "", + val verificationUri: String = "", + val interval: Int = 5, + val expiresIn: Int = 0, +) + +@Serializable +data class TwitchDevicePollRequest(val deviceCode: String) + +@Serializable +data class TwitchDevicePollDto(val status: String = "", val account: TwitchAccountStatusDto? = null) + +@Serializable +data class TwitchFollowStateDto( + val channelId: String = "", + val following: Boolean = false, + val followedAt: String? = null, +) + +@Serializable +data class TwitchChatSendRequest(val message: String) + +@Serializable +data class TwitchPollVoteRequest(val pollId: String, val choiceId: String) diff --git a/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchChatDto.kt b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchChatDto.kt new file mode 100644 index 00000000..a32d0a67 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchChatDto.kt @@ -0,0 +1,93 @@ +package dev.typetype.android.data.network.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class TwitchChatEmoteDto(val id: String = "", val start: Int = 0, val end: Int = 0) + +@Serializable +data class TwitchRoomStateDto( + val followersOnly: Int = -1, + val slow: Int = 0, + val emoteOnly: Boolean = false, + val subsOnly: Boolean = false, + val uniqueChat: Boolean = false, +) + +@Serializable +data class TwitchChatEventDto( + val type: String = "", + val id: String? = null, + val login: String? = null, + val displayName: String? = null, + val color: String? = null, + val text: String? = null, + val system: String? = null, + val emotes: List = emptyList(), + val badges: List = emptyList(), + val time: String = "", + val action: Boolean = false, + val targetId: String? = null, + val room: TwitchRoomStateDto? = null, + val deleted: Boolean = false, +) + +@Serializable +data class TwitchThirdPartyEmoteDto( + val name: String = "", + val url: String = "", + val url2x: String? = null, + val provider: String = "", + val animated: Boolean = false, + val zeroWidth: Boolean = false, +) + +@Serializable +data class TwitchChatBadgeDto(val title: String = "", val url: String = "", val url2x: String? = null) + +@Serializable +data class TwitchChatAssetsDto( + val channelId: String? = null, + val badges: Map = emptyMap(), + val emotes: List = emptyList(), +) + +@Serializable +data class TwitchPollChoiceDto(val id: String = "", val title: String = "", val votes: Long = 0) + +@Serializable +data class TwitchPollDto( + val id: String = "", + val title: String = "", + val status: String = "", + val startedAt: String = "", + val endedAt: String? = null, + val durationSeconds: Long = 0, + val remainingMs: Long = 0, + val voters: Long = 0, + val votes: Long = 0, + val choices: List = emptyList(), +) + +@Serializable +data class TwitchPinnedMessageDto( + val id: String = "", + val text: String = "", + val login: String = "", + val displayName: String = "", + val pinnedBy: String? = null, + val endsAt: String? = null, +) + +@Serializable +data class TwitchChatHighlightsDto(val poll: TwitchPollDto? = null, val pinned: TwitchPinnedMessageDto? = null) + +@Serializable +data class TwitchVideoCommentDto( + val id: String = "", + val offset: Long = 0, + val login: String? = null, + val displayName: String? = null, + val text: String = "", + val badges: List = emptyList(), +) diff --git a/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchDto.kt b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchDto.kt new file mode 100644 index 00000000..c2805320 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/network/dto/TwitchDto.kt @@ -0,0 +1,101 @@ +package dev.typetype.android.data.network.dto + +import kotlinx.serialization.Serializable + +@Serializable +data class TwitchPageDto( + val items: List = emptyList(), + val cursor: String? = null, + val hasMore: Boolean = false, +) + +@Serializable +data class TwitchGameDto( + val id: String = "", + val name: String = "", + val slug: String = "", + val boxArtUrl: String? = null, + val viewers: Long? = null, + val channels: Long? = null, +) + +@Serializable +data class TwitchUserDto( + val id: String = "", + val login: String = "", + val displayName: String = "", + val avatarUrl: String = "", +) + +@Serializable +data class TwitchArchiveDto(val id: String = "", val startedAt: String = "") + +@Serializable +data class TwitchStreamDto( + val id: String = "", + val title: String = "", + val user: TwitchUserDto = TwitchUserDto(), + val game: TwitchGameDto? = null, + val viewers: Long = 0, + val previewUrl: String = "", + val startedAt: String = "", + val tags: List = emptyList(), + val archive: TwitchArchiveDto? = null, +) + +@Serializable +data class TwitchChannelDto( + val id: String = "", + val login: String = "", + val displayName: String = "", + val avatarUrl: String = "", + val description: String = "", + val bannerUrl: String? = null, + val followers: Long = 0, + val partner: Boolean = false, + val live: TwitchStreamDto? = null, +) + +@Serializable +data class TwitchVideoDto( + val id: String = "", + val title: String = "", + val owner: TwitchUserDto = TwitchUserDto(), + val game: TwitchGameDto? = null, + val lengthSeconds: Long = 0, + val views: Long = 0, + val previewUrl: String = "", + val createdAt: String = "", + val type: String = "", + val recording: Boolean = false, +) + +@Serializable +data class TwitchClipDto( + val slug: String = "", + val title: String = "", + val broadcaster: TwitchUserDto = TwitchUserDto(), + val game: TwitchGameDto? = null, + val durationSeconds: Double = 0.0, + val views: Long = 0, + val thumbnailUrl: String = "", + val createdAt: String = "", +) + +@Serializable +data class TwitchClipQualityDto(val quality: String = "", val frameRate: Double = 0.0, val url: String = "") + +@Serializable +data class TwitchLiveDto(val channel: TwitchChannelDto = TwitchChannelDto(), val hlsUrl: String = "", val audioUrl: String? = null) + +@Serializable +data class TwitchVideoPlaybackDto(val video: TwitchVideoDto = TwitchVideoDto(), val hlsUrl: String = "", val audioUrl: String? = null) + +@Serializable +data class TwitchClipPlaybackDto(val clip: TwitchClipDto = TwitchClipDto(), val qualities: List = emptyList()) + +@Serializable +data class TwitchGameStreamsDto(val game: TwitchGameDto? = null, val streams: TwitchPageDto = TwitchPageDto()) + +@Serializable +data class TwitchVideoChapterDto(val start: Long = 0, val title: String = "", val game: TwitchGameDto? = null) diff --git a/core/data/src/main/java/dev/typetype/android/data/network/dto/UserSettingsDto.kt b/core/data/src/main/java/dev/typetype/android/data/network/dto/UserSettingsDto.kt index 41bb86e1..ae2ca221 100644 --- a/core/data/src/main/java/dev/typetype/android/data/network/dto/UserSettingsDto.kt +++ b/core/data/src/main/java/dev/typetype/android/data/network/dto/UserSettingsDto.kt @@ -38,6 +38,8 @@ data class UserSettingsDto( val hideShorts: Boolean = false, val hideMembersOnlyContent: Boolean = false, val hideSubscriptionLiveStreams: Boolean? = null, + val hideWatchedSubscriptionVideos: Boolean? = null, + val watchedThresholdPercent: Int? = null, val disableWatchHistory: Boolean = false, val deArrowEnabled: Boolean = false, val deArrowTitleMode: String = "dearrow", diff --git a/core/data/src/main/java/dev/typetype/android/data/preferences/DataStorePreferencesRepository.kt b/core/data/src/main/java/dev/typetype/android/data/preferences/DataStorePreferencesRepository.kt index 90f4f22c..6c0ff42e 100644 --- a/core/data/src/main/java/dev/typetype/android/data/preferences/DataStorePreferencesRepository.kt +++ b/core/data/src/main/java/dev/typetype/android/data/preferences/DataStorePreferencesRepository.kt @@ -14,6 +14,7 @@ import dev.typetype.android.domain.preferences.AppearanceMotion import dev.typetype.android.domain.preferences.AppearancePersonality import dev.typetype.android.domain.preferences.AppearanceTheme import dev.typetype.android.domain.preferences.AppPreferences +import dev.typetype.android.domain.preferences.HomeLayout import dev.typetype.android.domain.preferences.MangaHeadlineMarker import dev.typetype.android.domain.preferences.MangaPaper import dev.typetype.android.domain.preferences.PreferencesRepository @@ -73,6 +74,7 @@ class DataStorePreferencesRepository @Inject constructor( danmakuEnabled = prefs[KEY_DANMAKU_ENABLED] ?: false, danmakuSpeed = (prefs[KEY_DANMAKU_SPEED] ?: 1f).coerceIn(0.5f, 2f), danmakuSize = (prefs[KEY_DANMAKU_SIZE] ?: 1f).coerceIn(0.5f, 2f), + homeLayout = prefs.enum(KEY_HOME_LAYOUT, HomeLayout.Rows), ) } @@ -189,6 +191,8 @@ class DataStorePreferencesRepository @Inject constructor( dataStore.edit { it[KEY_DANMAKU_SIZE] = size.coerceIn(0.5f, 2f) } } + override suspend fun setHomeLayout(layout: HomeLayout) = store(KEY_HOME_LAYOUT, layout.name) + private suspend fun store(key: Preferences.Key, value: String) { dataStore.edit { it[key] = value } } @@ -230,6 +234,7 @@ class DataStorePreferencesRepository @Inject constructor( val KEY_DANMAKU_ENABLED = booleanPreferencesKey("player_danmaku_enabled") val KEY_DANMAKU_SPEED = floatPreferencesKey("player_danmaku_speed") val KEY_DANMAKU_SIZE = floatPreferencesKey("player_danmaku_size") + val KEY_HOME_LAYOUT = stringPreferencesKey("home_layout") const val DEFAULT_AUTOPLAY_COUNTDOWN_SECONDS = 10 const val MAX_AUTOPLAY_COUNTDOWN_SECONDS = 60 val ALLOWED_DOUBLE_TAP_SEEK_SECONDS = setOf(5, 10, 15, 20, 30) diff --git a/core/data/src/main/java/dev/typetype/android/data/server/RemoteServerCapabilitiesRepository.kt b/core/data/src/main/java/dev/typetype/android/data/server/RemoteServerCapabilitiesRepository.kt index eefeb294..b4b7061c 100644 --- a/core/data/src/main/java/dev/typetype/android/data/server/RemoteServerCapabilitiesRepository.kt +++ b/core/data/src/main/java/dev/typetype/android/data/server/RemoteServerCapabilitiesRepository.kt @@ -67,6 +67,7 @@ internal fun Server.withCapabilities(instance: InstanceResponse): Server = copy( } ?: RssCapability(), push = instance.pushNotifications.toCapability(), recommender = instance.recommender.toCapability(), + twitchEnabled = instance.twitch?.enabled == true, ) private fun PushCapabilityDto?.toCapability(): PushCapability = PushCapability( diff --git a/core/data/src/main/java/dev/typetype/android/data/server/ServerEntity.kt b/core/data/src/main/java/dev/typetype/android/data/server/ServerEntity.kt index b2f738cf..9c74695c 100644 --- a/core/data/src/main/java/dev/typetype/android/data/server/ServerEntity.kt +++ b/core/data/src/main/java/dev/typetype/android/data/server/ServerEntity.kt @@ -42,6 +42,7 @@ data class ServerEntity( @ColumnInfo(defaultValue = "0") val recommenderInstalled: Boolean = false, @ColumnInfo(defaultValue = "0") val recommenderEnabled: Boolean = false, @ColumnInfo(defaultValue = "0") val recommenderExperimental: Boolean = false, + @ColumnInfo(defaultValue = "0") val twitchEnabled: Boolean = false, ) { fun toDomain(): Server = Server( id = id, @@ -84,6 +85,7 @@ data class ServerEntity( enabled = recommenderEnabled, experimental = recommenderExperimental, ), + twitchEnabled = twitchEnabled, ) companion object { @@ -122,6 +124,7 @@ data class ServerEntity( recommenderInstalled = server.recommender.installed, recommenderEnabled = server.recommender.enabled, recommenderExperimental = server.recommender.experimental, + twitchEnabled = server.twitchEnabled, ) } } diff --git a/core/data/src/main/java/dev/typetype/android/data/setup/SetupRepositoryImpl.kt b/core/data/src/main/java/dev/typetype/android/data/setup/SetupRepositoryImpl.kt index 3d3cdbe0..59cd0f5b 100644 --- a/core/data/src/main/java/dev/typetype/android/data/setup/SetupRepositoryImpl.kt +++ b/core/data/src/main/java/dev/typetype/android/data/setup/SetupRepositoryImpl.kt @@ -79,6 +79,7 @@ class SetupRepositoryImpl @Inject constructor( experimental = it.experimental, ) } ?: RecommenderCapability(), + twitchEnabled = resolved.instance.twitch?.enabled == true, ) } diff --git a/core/data/src/main/java/dev/typetype/android/data/stream/StreamRepositoryImpl.kt b/core/data/src/main/java/dev/typetype/android/data/stream/StreamRepositoryImpl.kt index 8102f045..f0c5a6da 100644 --- a/core/data/src/main/java/dev/typetype/android/data/stream/StreamRepositoryImpl.kt +++ b/core/data/src/main/java/dev/typetype/android/data/stream/StreamRepositoryImpl.kt @@ -23,6 +23,7 @@ import dev.typetype.android.domain.stream.StreamVideoSource import dev.typetype.android.domain.stream.isServerSabrAudioFormat import dev.typetype.android.domain.stream.isServerSabrVideoFormat import dev.typetype.android.domain.server.ServerRepository +import dev.typetype.android.domain.twitch.TwitchUrls import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.CancellationException @@ -36,6 +37,7 @@ internal class StreamRepositoryImpl @Inject constructor( private val activeAccountScope: AccountScopeProvider, private val serverRepository: ServerRepository, private val networkMonitor: PlaybackNetworkObserver, + private val twitch: TwitchStreamLoader, ) : StreamRepository { private val playbackPrefetchCache = PlaybackStreamPrefetchCache() @@ -81,6 +83,7 @@ internal class StreamRepositoryImpl @Inject constructor( videoUrl: String, playbackBootstrap: Boolean, ): Result = cancellableStreamResult { + TwitchUrls.parse(videoUrl)?.let { target -> return@cancellableStreamResult twitch.load(target) } val scope = activeAccountScope.require() val server = serverRepository.getServer(scope.serverId) ?: error("Instance not found") val provider = videoUrl.streamProvider() @@ -139,9 +142,10 @@ internal class StreamRepositoryImpl @Inject constructor( hlsUrl = resolvedHlsUrl.takeIf { !serverSabr && it.isNotBlank() }, dashMpdUrl = dashMpdUrl.takeIf { !serverSabr && it.isNotBlank() }, progressiveUrl = pickBestProgressiveStream(baseUrl, videoStreams).takeUnless { serverSabr }, + // The server manifests only rebuild on-demand videos; a Bilibili or NicoNico live plays its own playlist. serverDashManifestUrl = serverManifestUrl(baseUrl, "streams/manifest", videoUrl) - .takeUnless { serverSabr || serverYoutube }, - serverHlsManifestUrl = hlsUrl.takeIf { !serverSabr && !serverYoutube && it.isNotBlank() } + .takeUnless { serverSabr || serverYoutube || isLive }, + serverHlsManifestUrl = hlsUrl.takeIf { !serverSabr && !serverYoutube && !isLive && it.isNotBlank() } ?.let { serverManifestUrl(baseUrl, "streams/hls-manifest", videoUrl) }, serverSabrManifestUrl = resolveServerUrl(baseUrl, firstSabrManifestUrl()), sabrVideoStreams = (videoOnlyStreams + videoStreams) diff --git a/core/data/src/main/java/dev/typetype/android/data/stream/TwitchStreamLoader.kt b/core/data/src/main/java/dev/typetype/android/data/stream/TwitchStreamLoader.kt new file mode 100644 index 00000000..5382f115 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/stream/TwitchStreamLoader.kt @@ -0,0 +1,77 @@ +package dev.typetype.android.data.stream + +import dev.typetype.android.core.error.CodedFailure +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.stream.Stream +import dev.typetype.android.domain.stream.StreamPlaybackContract +import dev.typetype.android.domain.twitch.TwitchRepository +import dev.typetype.android.domain.twitch.TwitchTarget +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope + +// Twitch plays from TypeType-Live's signed playlists (lives and past broadcasts) or a clip's MP4 file; nothing goes +// through the server's stream extractor. +@Singleton +internal class TwitchStreamLoader @Inject constructor( + private val twitch: TwitchRepository, +) { + suspend fun load(target: TwitchTarget): Stream = when (target) { + is TwitchTarget.Live -> { + val playback = twitch.live(target.login).getOrThrow() ?: throw TwitchOfflineException() + stream(playback.video, hlsUrl = playback.playlistUrl, live = true).copy(startOverUrl = playback.startOverUrl) + } + is TwitchTarget.Vod -> coroutineScope { + val chapters = async { twitch.chapters(target.id).getOrNull().orEmpty().takeIf { it.size > 1 }.orEmpty() } + val playback = twitch.vod(target.id).getOrThrow() + // A recording in progress plays like a past broadcast from where it was opened, with no live target to chase. + stream(playback.video, hlsUrl = playback.playlistUrl, live = false) + .copy(chapters = chapters.await(), holdsStartPosition = playback.live) + } + is TwitchTarget.Clip -> { + val clip = twitch.clip(target.slug).getOrThrow() + val quality = clip.qualities.firstOrNull { it.height <= CLIP_HEIGHT } ?: clip.qualities.last() + stream(clip.video, progressiveUrl = quality.url, live = false) + } + } + + private fun stream(video: Video, hlsUrl: String? = null, progressiveUrl: String? = null, live: Boolean) = Stream( + playbackContract = StreamPlaybackContract.ProviderMedia, + id = video.url, + title = video.title, + uploaderName = video.uploaderName, + uploaderAvatarUrl = video.uploaderAvatarUrl, + uploaderUrl = video.uploaderUrl, + uploaderSubscriberCount = 0, + uploaderVerified = false, + thumbnailUrl = video.thumbnailUrl, + description = "", + durationSeconds = if (live) 0 else video.durationSeconds, + viewCount = video.viewCount, + likeCount = 0, + dislikeCount = 0, + uploadedAtMillis = video.uploadedAtMillis, + hlsUrl = hlsUrl, + dashMpdUrl = null, + progressiveUrl = progressiveUrl, + serverDashManifestUrl = null, + serverHlsManifestUrl = null, + startPositionMillis = 0, + isLive = live, + isLiveContent = live, + liveTargetOffsetMillis = if (live) LOW_LATENCY_TARGET_MS else null, + ) + + private companion object { + const val CLIP_HEIGHT = 1080 + // The web player's low latency start: 8 s back with a few complete 2 s segments buffered. + const val LOW_LATENCY_TARGET_MS = 8_000L + } +} + +private class TwitchOfflineException : IllegalStateException("This Twitch channel is not live"), CodedFailure { + override val failureCode: String = "twitch_offline" + override val requestId: String? = null + override val statusCode: Int = 404 +} 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 new file mode 100644 index 00000000..00d9b570 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchAccountRepository.kt @@ -0,0 +1,87 @@ +package dev.typetype.android.data.twitch + +import dev.typetype.android.core.error.suspendRunCatching +import dev.typetype.android.data.account.ActiveAccountScope +import dev.typetype.android.data.network.TypeTypeApi +import dev.typetype.android.data.network.TypeTypeApiHolder +import dev.typetype.android.data.network.dto.TwitchChatSendRequest +import dev.typetype.android.data.network.dto.TwitchDevicePollRequest +import dev.typetype.android.data.network.dto.TwitchPollVoteRequest +import dev.typetype.android.data.network.requireSuccessfulResponse +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.twitch.TwitchAccountRepository +import dev.typetype.android.domain.twitch.TwitchAccountStatus +import dev.typetype.android.domain.twitch.TwitchLinkCode +import dev.typetype.android.domain.twitch.TwitchLinkPoll +import dev.typetype.android.domain.twitch.TwitchPage +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import retrofit2.Response + +@Singleton +class RemoteTwitchAccountRepository @Inject constructor( + private val apiHolder: TypeTypeApiHolder, + private val activeAccountScope: ActiveAccountScope, +) : TwitchAccountRepository { + override suspend fun status(): Result = call { twitchAccount() }.map { + TwitchAccountStatus(linked = it.linked, name = it.displayName?.ifBlank { null } ?: it.login) + } + + override suspend fun start(): Result = call { twitchStartDevice() }.map { dto -> + check(dto.deviceCode.isNotBlank() && dto.userCode.isNotBlank()) { "Twitch gave no device code" } + TwitchLinkCode( + deviceCode = dto.deviceCode, + userCode = dto.userCode, + activationUrl = "${dto.verificationUri.ifBlank { ACTIVATE }}?device-code=${dto.userCode}", + intervalSeconds = dto.interval.coerceAtLeast(MIN_INTERVAL), + expiresInSeconds = dto.expiresIn, + ) + } + + override suspend fun poll(deviceCode: String): Result = + call { twitchPollDevice(TwitchDevicePollRequest(deviceCode)) }.map { dto -> + when (dto.status) { + "ok" -> TwitchLinkPoll.Linked(dto.account?.displayName ?: dto.account?.login.orEmpty()) + "slow_down" -> TwitchLinkPoll.SlowDown + else -> TwitchLinkPoll.Pending + } + } + + override suspend fun unlink(): Result = write { twitchUnlink() } + + 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 isFollowing(login: String): Result = call { twitchFollowState(login) }.map { it.following } + + override suspend fun setFollowing(login: String, follow: Boolean): Result = + write { if (follow) twitchFollow(login) else twitchUnfollow(login) } + + override suspend fun sendChat(login: String, message: String): Result = + write { twitchSendChat(login, TwitchChatSendRequest(message)) } + + override suspend fun votePoll(pollId: String, choiceId: String): Result = + write { twitchVotePoll(TwitchPollVoteRequest(pollId, choiceId)) } + + private suspend fun write(block: suspend TypeTypeApi.() -> Response): Result = suspendRunCatching { + val scope = activeAccountScope.require() + val response = withContext(Dispatchers.IO) { apiHolder.require(scope).block() } + activeAccountScope.verify(scope) + response.requireSuccessfulResponse() + } + + private suspend fun call(block: suspend TypeTypeApi.() -> Response): Result = suspendRunCatching { + val scope = activeAccountScope.require() + val response = withContext(Dispatchers.IO) { apiHolder.require(scope).block() } + activeAccountScope.verify(scope) + response.requireSuccessfulResponse() + response.body() ?: error("Empty Twitch response") + } + + private companion object { + const val ACTIVATE = "https://www.twitch.tv/activate" + const val MIN_INTERVAL = 5 + } +} 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 new file mode 100644 index 00000000..8578ae91 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/RemoteTwitchRepository.kt @@ -0,0 +1,130 @@ +package dev.typetype.android.data.twitch + +import dev.typetype.android.core.error.suspendRunCatching +import dev.typetype.android.data.account.ActiveAccountScope +import dev.typetype.android.data.network.TypeTypeApi +import dev.typetype.android.data.network.TypeTypeApiHolder +import dev.typetype.android.data.network.dto.TwitchPageDto +import dev.typetype.android.data.network.requireSuccessfulResponse +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.stream.Chapter +import dev.typetype.android.domain.server.ServerRepository +import dev.typetype.android.domain.twitch.TwitchCategory +import dev.typetype.android.domain.twitch.TwitchChannel +import dev.typetype.android.domain.twitch.TwitchChatHighlights +import dev.typetype.android.domain.twitch.TwitchClipPlayback +import dev.typetype.android.domain.twitch.TwitchPage +import dev.typetype.android.domain.twitch.TwitchPlayback +import dev.typetype.android.domain.twitch.TwitchRepository +import dev.typetype.android.domain.twitch.TwitchUrls +import dev.typetype.android.domain.twitch.TwitchVideoComment +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import retrofit2.Response + +@Singleton +class RemoteTwitchRepository @Inject constructor( + private val apiHolder: TypeTypeApiHolder, + private val activeAccountScope: ActiveAccountScope, + private val serverRepository: ServerRepository, +) : TwitchRepository { + override suspend fun popular(cursor: String?): Result> = + call { twitchStreams(cursor) }.map { page -> page.map { it.toVideo() } } + + override suspend fun categories(cursor: String?): Result> = + call { twitchGames(cursor) }.map { page -> page.map { it.toCategory() } } + + override suspend fun categoryLives(slug: String, cursor: String?): Result> = + call { twitchGameStreams(segment(slug), cursor) }.map { body -> body.streams.map { it.toVideo() } } + + override suspend fun channel(login: String): Result = + call { twitchChannel(segment(login)) }.map { it.toChannel() } + + override suspend fun channelVods(login: String, cursor: String?): Result> = + call { twitchChannelVideos(segment(login), cursor) }.map { page -> page.map { it.toVideo() } } + + override suspend fun channelClips(login: String, cursor: String?): Result> = + call { twitchChannelClips(segment(login), cursor) }.map { page -> page.map { it.toVideo() } } + + override suspend fun live(login: String): Result = suspendRunCatching { + val (base, response) = request { twitchLive(segment(login)) } + if (response.code() == HTTP_NOT_FOUND) return@suspendRunCatching null + response.requireSuccessfulResponse() + val body = response.body() ?: error("Empty Twitch live body") + val channel = body.channel.toChannel() + val video = channel.live ?: error("Twitch live without a stream") + TwitchPlayback( + video = video, + playlistUrl = twitchPlaylistUrl(base, body.hlsUrl) ?: error("Twitch live without a playlist"), + audioPlaylistUrl = twitchPlaylistUrl(base, body.audioUrl), + live = true, + startOverUrl = body.channel.live?.archive?.id?.takeIf { it.isNotBlank() }?.let(TwitchUrls::vod), + ) + } + + override suspend fun vod(id: String): Result = suspendRunCatching { + val (base, response) = request { twitchVideo(segment(id)) } + response.requireSuccessfulResponse() + val body = response.body() ?: error("Empty Twitch video body") + TwitchPlayback( + video = body.video.toVideo(), + playlistUrl = twitchPlaylistUrl(base, body.hlsUrl) ?: error("Twitch video without a playlist"), + audioPlaylistUrl = twitchPlaylistUrl(base, body.audioUrl), + live = body.video.recording, + ) + } + + override suspend fun clip(slug: String): Result = suspendRunCatching { + val (base, response) = request { twitchClip(segment(slug)) } + response.requireSuccessfulResponse() + val body = response.body() ?: error("Empty Twitch clip body") + // Clip files are served by Live under the instance origin, like the playlists. + val qualities = body.qualities.mapNotNull { quality -> + quality.toQuality()?.let { it.copy(url = twitchPlaylistUrl(base, it.url) ?: return@mapNotNull null) } + }.sortedByDescending { it.height } + require(qualities.isNotEmpty()) { "Twitch clip without a playable quality" } + TwitchClipPlayback(body.clip.toVideo(), qualities) + } + + override suspend fun searchChannels(query: String, cursor: String?): Result> = + call { twitchSearchChannels(query.trim(), after = cursor) }.map { page -> page.map { it.toChannel() } } + + override suspend fun searchLives(query: String, cursor: String?): Result> = + call { twitchSearchStreams(query.trim(), after = cursor) }.map { page -> page.map { it.toVideo() } } + + override suspend fun chapters(id: String): Result> = call { twitchVideoChapters(id) }.map { chapters -> + chapters.map { Chapter(title = it.title.ifBlank { it.game?.name.orEmpty() }, startMs = it.start * 1_000, previewUrl = null) } + } + + override suspend fun chatHighlights(login: String): Result = + call { twitchChatHighlights(login) }.map { it.toDomain() } + + 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() } } + + private suspend fun call(block: suspend TypeTypeApi.() -> Response): Result = suspendRunCatching { + val (_, response) = request(block) + response.requireSuccessfulResponse() + response.body() ?: error("Empty Twitch response") + } + + private suspend fun request(block: suspend TypeTypeApi.() -> Response): Pair> { + val scope = activeAccountScope.require() + val base = serverRepository.getServer(scope.serverId)?.baseUrl ?: error("Instance not found") + val response = withContext(Dispatchers.IO) { apiHolder.require(scope).block() } + activeAccountScope.verify(scope) + return base to response + } + + private fun TwitchPageDto.map(transform: (T) -> R): TwitchPage = + TwitchPage(items.map(transform), cursor?.takeIf { hasMore && it.isNotBlank() }) + + private fun segment(value: String): String = value.trim().filter { it.isLetterOrDigit() || it in "_-" } + + private companion object { + const val HTTP_NOT_FOUND = 404 + } +} 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 new file mode 100644 index 00000000..0fd65115 --- /dev/null +++ b/core/data/src/main/java/dev/typetype/android/data/twitch/TwitchMappers.kt @@ -0,0 +1,148 @@ +package dev.typetype.android.data.twitch + +import dev.typetype.android.data.network.dto.TwitchChannelDto +import dev.typetype.android.data.network.dto.TwitchChatHighlightsDto +import dev.typetype.android.data.network.dto.TwitchClipDto +import dev.typetype.android.data.network.dto.TwitchClipQualityDto +import dev.typetype.android.data.network.dto.TwitchGameDto +import dev.typetype.android.data.network.dto.TwitchStreamDto +import dev.typetype.android.data.network.dto.TwitchUserDto +import dev.typetype.android.data.network.dto.TwitchVideoCommentDto +import dev.typetype.android.data.network.dto.TwitchVideoDto +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.twitch.TwitchCategory +import dev.typetype.android.domain.twitch.TwitchChannel +import dev.typetype.android.domain.twitch.TwitchChatHighlights +import dev.typetype.android.domain.twitch.TwitchClipQuality +import dev.typetype.android.domain.twitch.TwitchPinnedMessage +import dev.typetype.android.domain.twitch.TwitchPoll +import dev.typetype.android.domain.twitch.TwitchPollChoice +import dev.typetype.android.domain.twitch.TwitchUrls +import dev.typetype.android.domain.twitch.TwitchVideoComment +import java.net.URI +import java.util.Calendar +import java.util.TimeZone + +internal fun TwitchStreamDto.toVideo(): Video = video( + url = TwitchUrls.live(user.login), + title = title, + user = user, + thumbnailUrl = previewUrl, + durationSeconds = 0, + isLive = true, + count = viewers, + at = startedAt, +) + +internal fun TwitchVideoDto.toVideo(): Video = video( + url = TwitchUrls.vod(id), + title = title, + user = owner, + thumbnailUrl = previewUrl, + durationSeconds = lengthSeconds, + isLive = recording, + count = views, + at = createdAt, +) + +internal fun TwitchClipDto.toVideo(): Video = video( + url = TwitchUrls.clip(slug), + title = title, + user = broadcaster, + thumbnailUrl = thumbnailUrl, + durationSeconds = durationSeconds.toLong(), + isLive = false, + count = views, + at = createdAt, +) + +internal fun TwitchChannelDto.toChannel(): TwitchChannel = TwitchChannel( + login = login, + displayName = displayName.ifBlank { login }, + avatarUrl = avatarUrl.ifBlank { null }, + description = description.trim(), + bannerUrl = bannerUrl?.ifBlank { null }, + followers = followers, + live = live?.toVideo(), +) + +internal fun TwitchGameDto.toCategory(): TwitchCategory = + TwitchCategory(id = id, name = name, slug = slug, boxArtUrl = boxArtUrl?.ifBlank { null }, viewers = viewers) + +internal fun TwitchClipQualityDto.toQuality(): TwitchClipQuality? { + val height = quality.takeWhile(Char::isDigit).toIntOrNull() ?: return null + return TwitchClipQuality(height, frameRate.toInt(), url).takeIf { url.isNotBlank() } +} + +// Live serves its playlists under the instance origin (/live/hls/...), next to /api, not inside it. +internal fun twitchPlaylistUrl(apiBaseUrl: String, reference: String?): String? { + val trimmed = reference?.trim().orEmpty() + if (trimmed.isEmpty()) return null + return runCatching { URI(apiBaseUrl).resolve(trimmed).toString() }.getOrNull() +} + +// java.time is not there before API 26 and the app supports API 23: Twitch sends UTC times like 2026-11-17T18:06:44Z. +internal fun twitchMillis(value: String): Long { + val match = UTC_TIME.matchEntire(value.trim()) ?: return 0L + val (year, month, day, hour, minute, second) = match.destructured + return Calendar.getInstance(TimeZone.getTimeZone("UTC")).run { + clear() + set(year.toInt(), month.toInt() - 1, day.toInt(), hour.toInt(), minute.toInt(), second.toInt()) + timeInMillis + } +} + +private fun video( + url: String, + title: String, + user: TwitchUserDto, + thumbnailUrl: String, + durationSeconds: Long, + isLive: Boolean, + count: Long, + at: String, +): Video { + val millis = twitchMillis(at) + return Video( + id = url, + url = url, + title = title, + thumbnailUrl = thumbnailUrl, + uploaderName = user.displayName.ifBlank { user.login }, + uploaderUrl = TwitchUrls.live(user.login), + uploaderAvatarUrl = user.avatarUrl, + uploaderVerified = false, + durationSeconds = durationSeconds.coerceAtLeast(0), + isLive = isLive, + viewCount = count, + uploadedAtMillis = millis, + isShortFormContent = false, + shortDescription = null, + publishedAtMillis = millis.takeIf { it > 0 }, + isLiveContent = isLive, + ) +} + +private val UTC_TIME = Regex("""(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z""") + +internal fun TwitchChatHighlightsDto.toDomain() = TwitchChatHighlights( + poll = poll?.takeIf { it.id.isNotBlank() && it.choices.isNotEmpty() }?.let { dto -> + TwitchPoll( + id = dto.id, + title = dto.title, + votes = dto.votes, + choices = dto.choices.map { TwitchPollChoice(it.id, it.title, it.votes) }, + ) + }, + pinned = pinned?.takeIf { it.id.isNotBlank() && it.text.isNotBlank() }?.let { dto -> + TwitchPinnedMessage(dto.id, dto.text, dto.displayName.ifBlank { dto.login }) + }, +) + +internal fun TwitchVideoCommentDto.toDomain() = TwitchVideoComment( + id = id, + offsetSeconds = offset, + author = displayName?.ifBlank { null } ?: login, + text = text, + moderator = badges.any { it.startsWith("moderator/") || it.startsWith("broadcaster/") }, +) diff --git a/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsNetworkSource.kt b/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsNetworkSource.kt index e3b1282c..3eb288d7 100644 --- a/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsNetworkSource.kt +++ b/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsNetworkSource.kt @@ -86,6 +86,9 @@ internal fun UserSettingsDto.toDomain(serverBaseUrl: String? = null): UserSettin hideMembersOnlyContent = hideMembersOnlyContent, hideSubscriptionLiveStreams = hideSubscriptionLiveStreams == true, supportsHideSubscriptionLiveStreams = hideSubscriptionLiveStreams != null, + hideWatchedSubscriptionVideos = hideWatchedSubscriptionVideos == true, + watchedThresholdPercent = watchedThresholdPercent ?: 0, + supportsWatchedSettings = watchedThresholdPercent != null, disableWatchHistory = disableWatchHistory, deArrowEnabled = deArrowEnabled, deArrowTitleMode = deArrowTitleMode, diff --git a/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsPatch.kt b/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsPatch.kt index 0b62d3a8..b84fd155 100644 --- a/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsPatch.kt +++ b/core/data/src/main/java/dev/typetype/android/data/usersettings/UserSettingsPatch.kt @@ -94,6 +94,12 @@ internal fun UserSettings.patchFrom(previous: UserSettings): JsonObject = buildJ if (hideContinueWatching != previous.hideContinueWatching) { put("hideContinueWatching", hideContinueWatching) } + if (supportsWatchedSettings && hideWatchedSubscriptionVideos != previous.hideWatchedSubscriptionVideos) { + put("hideWatchedSubscriptionVideos", hideWatchedSubscriptionVideos) + } + if (supportsWatchedSettings && watchedThresholdPercent != previous.watchedThresholdPercent) { + put("watchedThresholdPercent", watchedThresholdPercent) + } if (hideRelatedVideos != previous.hideRelatedVideos) { put("hideRelatedVideos", hideRelatedVideos) } diff --git a/core/data/src/test/java/dev/typetype/android/data/livechat/TwitchChatSseParserTest.kt b/core/data/src/test/java/dev/typetype/android/data/livechat/TwitchChatSseParserTest.kt new file mode 100644 index 00000000..6c1b2a56 --- /dev/null +++ b/core/data/src/test/java/dev/typetype/android/data/livechat/TwitchChatSseParserTest.kt @@ -0,0 +1,42 @@ +package dev.typetype.android.data.livechat + +import dev.typetype.android.domain.livechat.LiveChatEvent +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TwitchChatSseParserTest { + private val parser = TwitchChatSseParser(Json { ignoreUnknownKeys = true }) + + private fun feed(json: String): LiveChatEvent? { + assertNull(parser.accept("event: message")) + assertNull(parser.accept("data: $json")) + return parser.accept("") + } + + @Test + fun aMessageKeepsItsAuthorAndModeratorBadge() { + val event = feed("""{"type":"message","id":"m1","login":"mod","displayName":"Mod","text":"be nice","badges":["moderator/1"],"time":"t"}""") + val message = (event as LiveChatEvent.Message).message + assertEquals("m1", message.id) + assertEquals("Mod", message.authorName) + assertTrue(message.moderator) + } + + @Test + fun moderationAndRoomEventsAreRead() { + assertEquals(LiveChatEvent.Removed("m1"), feed("""{"type":"delete","targetId":"m1","time":"t"}""")) + assertEquals(LiveChatEvent.Cleared("viewer"), feed("""{"type":"clear","login":"viewer","time":"t"}""")) + assertEquals(LiveChatEvent.Cleared(null), feed("""{"type":"clear","time":"t"}""")) + assertNull(feed("""{"type":"room","room":{"slow":3},"time":"t"}""")) + } + + @Test + fun keepAlivesAndBrokenDataAreIgnored() { + assertNull(parser.accept(": keep-alive")) + assertNull(parser.accept("")) + assertNull(feed("not json")) + } +} diff --git a/core/data/src/test/java/dev/typetype/android/data/network/TwitchContractTest.kt b/core/data/src/test/java/dev/typetype/android/data/network/TwitchContractTest.kt new file mode 100644 index 00000000..93a14ef3 --- /dev/null +++ b/core/data/src/test/java/dev/typetype/android/data/network/TwitchContractTest.kt @@ -0,0 +1,73 @@ +package dev.typetype.android.data.network + +import dev.typetype.android.data.network.dto.TwitchDevicePollRequest +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +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 + +class TwitchContractTest { + private lateinit var server: MockWebServer + private lateinit var api: TypeTypeApi + + @Before + fun setUp() { + server = MockWebServer().apply { start() } + api = RetrofitFactory(sessionClient = OkHttpClient(), json = Json { ignoreUnknownKeys = true }) + .create(server.url("/api/").toString()) + } + + @After + fun tearDown() { + server.shutdown() + } + + @Test + fun streamsArePagedWithTheServerParameters() = runBlocking { + server.enqueue(json("""{"items":[{"id":"9","title":"Spacewalk","user":{"login":"space","displayName":"Space"},"viewers":1084}],"cursor":"c2","hasMore":true}""")) + val body = api.twitchStreams(after = "c1").body()!! + assertEquals("/api/twitch/streams?after=c1&first=24", server.takeRequest().path) + assertEquals("space", body.items.single().user.login) + assertTrue(body.hasMore) + } + + @Test + fun channelLivesVodsAndClipsUseTheLoginInThePath() = runBlocking { + repeat(3) { server.enqueue(json("""{"items":[]}""")) } + api.twitchChannelVideos("space") + api.twitchChannelClips("space", after = "x") + api.twitchSearchStreams("space walk") + assertEquals("/api/twitch/channels/space/videos?first=24", server.takeRequest().path) + assertEquals("/api/twitch/channels/space/clips?after=x&first=24", server.takeRequest().path) + assertEquals("/api/twitch/search?q=space%20walk&type=streams&first=24", server.takeRequest().path) + } + + @Test + fun aLiveCarriesItsRelativePlaylists() = runBlocking { + server.enqueue(json("""{"channel":{"login":"space","live":{"title":"Live","user":{"login":"space"}}},"hlsUrl":"/live/hls/master.m3u8?c=space","audioUrl":"/live/hls/master.m3u8?a=1&c=space"}""")) + val live = api.twitchLive("space").body()!! + assertEquals("/live/hls/master.m3u8?c=space", live.hlsUrl) + assertEquals("Live", live.channel.live?.title) + } + + @Test + fun deviceLoginAndFollowUseTheirMethods() = runBlocking { + repeat(3) { server.enqueue(json("{}")) } + api.twitchPollDevice(TwitchDevicePollRequest("code-1")) + api.twitchFollow("space") + api.twitchUnfollow("space") + val poll = server.takeRequest() + assertEquals("POST /api/twitch/account/poll", "${poll.method} ${poll.path}") + assertEquals("""{"deviceCode":"code-1"}""", poll.body.readUtf8()) + assertEquals("PUT /api/twitch/me/follows/space", server.takeRequest().let { "${it.method} ${it.path}" }) + assertEquals("DELETE /api/twitch/me/follows/space", server.takeRequest().let { "${it.method} ${it.path}" }) + } + + private fun json(body: String) = MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json").setBody(body) +} diff --git a/core/data/src/test/java/dev/typetype/android/data/server/ServerCapabilitiesTest.kt b/core/data/src/test/java/dev/typetype/android/data/server/ServerCapabilitiesTest.kt index a5c55b5e..fab09ab1 100644 --- a/core/data/src/test/java/dev/typetype/android/data/server/ServerCapabilitiesTest.kt +++ b/core/data/src/test/java/dev/typetype/android/data/server/ServerCapabilitiesTest.kt @@ -114,6 +114,12 @@ class ServerCapabilitiesTest { assertTrue(refreshed.recommender.available) } + @Test + fun twitchFollowsTheInstanceAndStaysOffWhenMissing() { + assertTrue(server.withCapabilities(decode(BASE_INSTANCE.dropLast(1) + ",\"twitch\":{\"enabled\":true}}")).twitchEnabled) + assertFalse(server.withCapabilities(decode(BASE_INSTANCE)).twitchEnabled) + } + private fun decode(value: String): InstanceResponse = json.decodeFromString(value) private companion object { diff --git a/core/data/src/test/java/dev/typetype/android/data/server/ServerEntityMappingTest.kt b/core/data/src/test/java/dev/typetype/android/data/server/ServerEntityMappingTest.kt index 2053bcf6..867bb3a2 100644 --- a/core/data/src/test/java/dev/typetype/android/data/server/ServerEntityMappingTest.kt +++ b/core/data/src/test/java/dev/typetype/android/data/server/ServerEntityMappingTest.kt @@ -45,6 +45,7 @@ class ServerEntityMappingTest { assertEquals("unifiedpush", restored.push.provider) assertTrue(restored.push.eventTypes.isEmpty()) assertFalse(restored.recommender.available) + assertFalse(restored.twitchEnabled) } @Test @@ -67,4 +68,17 @@ class ServerEntityMappingTest { assertTrue(restored.recommender.enabled) assertTrue(restored.recommender.experimental) } + + @Test + fun preservesTwitchCapabilityAcrossRoomMapping() { + val server = Server( + id = "server", + baseUrl = "https://example.test/api/", + displayName = "Test", + addedAt = 1L, + twitchEnabled = true, + ) + + assertTrue(ServerEntity.fromDomain(server).toDomain().twitchEnabled) + } } 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 new file mode 100644 index 00000000..98a6958d --- /dev/null +++ b/core/data/src/test/java/dev/typetype/android/data/stream/FakeTwitchRepository.kt @@ -0,0 +1,35 @@ +package dev.typetype.android.data.stream + +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.stream.Chapter +import dev.typetype.android.domain.twitch.TwitchCategory +import dev.typetype.android.domain.twitch.TwitchChannel +import dev.typetype.android.domain.twitch.TwitchChatHighlights +import dev.typetype.android.domain.twitch.TwitchClipPlayback +import dev.typetype.android.domain.twitch.TwitchPage +import dev.typetype.android.domain.twitch.TwitchPlayback +import dev.typetype.android.domain.twitch.TwitchRepository +import dev.typetype.android.domain.twitch.TwitchVideoComment + +internal class FakeTwitchRepository( + private val livePlayback: TwitchPlayback? = null, + private val vodPlayback: TwitchPlayback? = null, + private val clipPlayback: TwitchClipPlayback? = null, + private val chapterList: List = emptyList(), +) : TwitchRepository { + override suspend fun popular(cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun categories(cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun categoryLives(slug: String, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun channel(login: String): Result = Result.failure(UnsupportedOperationException()) + override suspend fun channelVods(login: String, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun channelClips(login: String, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun live(login: String): Result = Result.success(livePlayback) + override suspend fun vod(id: String): Result = vodPlayback?.let { Result.success(it) } ?: Result.failure(IllegalStateException()) + override suspend fun clip(slug: String): Result = clipPlayback?.let { Result.success(it) } ?: Result.failure(IllegalStateException()) + override suspend fun searchChannels(query: String, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun searchLives(query: String, cursor: String?): Result> = Result.success(TwitchPage(emptyList(), null)) + override suspend fun chapters(id: String): Result> = Result.success(chapterList) + 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)) +} diff --git a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryLiveTest.kt b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryLiveTest.kt index 83d8be37..08c869df 100644 --- a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryLiveTest.kt +++ b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryLiveTest.kt @@ -41,6 +41,17 @@ class StreamRepositoryLiveTest { assertTrue(stream.sabrVideoStreams.isEmpty()) } + @Test + fun `a bilibili live plays its own playlist rather than a server manifest`() = runBlocking { + val repository = repository(response(isLive = true, hasLiveManifest = false, hlsUrl = "/media/m1_live")) + + val stream = repository.loadPlaybackStream("https://live.bilibili.com/1874910086").getOrThrow() + + assertEquals("${BASE_URL}media/m1_live", stream.hlsUrl) + assertNull(stream.serverHlsManifestUrl) + assertNull(stream.serverDashManifestUrl) + } + @Test fun `youtube live response without a server manifest is rejected`() = runBlocking { val repository = repository( @@ -88,6 +99,7 @@ class StreamRepositoryLiveTest { activeAccountScope = FixedAccountScope, serverRepository = FixedServerRepository, networkMonitor = AlwaysAvailablePlaybackNetworkObserver, + twitch = TwitchStreamLoader(FakeTwitchRepository()), ) private class FixedStreamRemoteSource( diff --git a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryPrefetchTest.kt b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryPrefetchTest.kt index 20f2313b..4a620983 100644 --- a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryPrefetchTest.kt +++ b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryPrefetchTest.kt @@ -26,6 +26,7 @@ class StreamRepositoryPrefetchTest { activeAccountScope = FixedAccountScope, serverRepository = FixedServerRepository, networkMonitor = AlwaysAvailablePlaybackNetworkObserver, + twitch = TwitchStreamLoader(FakeTwitchRepository()), ) repository.prefetchPlaybackStream(VIDEO_URL).getOrThrow() diff --git a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryProviderMediaTest.kt b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryProviderMediaTest.kt index 4b281bbd..4b913c34 100644 --- a/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryProviderMediaTest.kt +++ b/core/data/src/test/java/dev/typetype/android/data/stream/StreamRepositoryProviderMediaTest.kt @@ -80,6 +80,7 @@ class StreamRepositoryProviderMediaTest { activeAccountScope = FixedAccountScope, serverRepository = FixedServerRepository, networkMonitor = AlwaysAvailablePlaybackNetworkObserver, + twitch = TwitchStreamLoader(FakeTwitchRepository()), ) private class FixedStreamRemoteSource( diff --git a/core/data/src/test/java/dev/typetype/android/data/stream/TwitchStreamLoaderTest.kt b/core/data/src/test/java/dev/typetype/android/data/stream/TwitchStreamLoaderTest.kt new file mode 100644 index 00000000..d5039403 --- /dev/null +++ b/core/data/src/test/java/dev/typetype/android/data/stream/TwitchStreamLoaderTest.kt @@ -0,0 +1,83 @@ +package dev.typetype.android.data.stream + +import dev.typetype.android.core.error.CodedFailure +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.stream.Chapter +import dev.typetype.android.domain.stream.StreamPlaybackContract +import dev.typetype.android.domain.twitch.TwitchClipPlayback +import dev.typetype.android.domain.twitch.TwitchClipQuality +import dev.typetype.android.domain.twitch.TwitchPlayback +import dev.typetype.android.domain.twitch.TwitchTarget +import kotlinx.coroutines.runBlocking +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 TwitchStreamLoaderTest { + @Test + fun aLivePlaysItsPlaylistAtTheLowLatencyTarget() = runBlocking { + val loader = TwitchStreamLoader(FakeTwitchRepository(livePlayback = TwitchPlayback(video("https://www.twitch.tv/space"), PLAYLIST, null, live = true))) + val stream = loader.load(TwitchTarget.Live("space")) + assertEquals(StreamPlaybackContract.ProviderMedia, stream.playbackContract) + assertEquals(PLAYLIST, stream.hlsUrl) + assertTrue(stream.isLive) + assertEquals(0L, stream.durationSeconds) + assertEquals(8_000L, stream.liveTargetOffsetMillis) + } + + @Test + fun aLiveOffersItsRecordingWhichOpensFromWhereItWasAsked() = runBlocking { + val recording = "https://www.twitch.tv/videos/9" + val live = TwitchPlayback(video("https://www.twitch.tv/space"), PLAYLIST, null, live = true, startOverUrl = recording) + assertEquals(recording, TwitchStreamLoader(FakeTwitchRepository(livePlayback = live)).load(TwitchTarget.Live("space")).startOverUrl) + + val growing = TwitchPlayback(video(recording, 3_600), PLAYLIST, null, live = true) + val stream = TwitchStreamLoader(FakeTwitchRepository(vodPlayback = growing)).load(TwitchTarget.Vod("9")) + assertTrue(stream.holdsStartPosition) + assertFalse(stream.isLive) + assertNull(stream.liveTargetOffsetMillis) + } + + @Test + fun anOfflineChannelFailsWithItsOwnCode() = runBlocking { + val failure = runCatching { TwitchStreamLoader(FakeTwitchRepository()).load(TwitchTarget.Live("space")) }.exceptionOrNull() + assertEquals("twitch_offline", (failure as CodedFailure).failureCode) + } + + @Test + fun aPastBroadcastKeepsItsLengthAndNoLiveTarget() = runBlocking { + val loader = TwitchStreamLoader(FakeTwitchRepository(vodPlayback = TwitchPlayback(video("https://www.twitch.tv/videos/1", 3_600), PLAYLIST, null, live = false))) + val stream = loader.load(TwitchTarget.Vod("1")) + assertFalse(stream.isLive) + assertEquals(3_600L, stream.durationSeconds) + assertNull(stream.liveTargetOffsetMillis) + } + + @Test + fun aPastBroadcastCarriesItsGameChaptersOnlyWhenThereAreSeveral() = runBlocking { + val playback = TwitchPlayback(video("https://www.twitch.tv/videos/1", 3_600), PLAYLIST, null, live = false) + val two = listOf(Chapter("Fortnite", 0, null), Chapter("Chess", 3_641_000, null)) + assertEquals(two, TwitchStreamLoader(FakeTwitchRepository(vodPlayback = playback, chapterList = two)).load(TwitchTarget.Vod("1")).chapters) + val one = TwitchStreamLoader(FakeTwitchRepository(vodPlayback = playback, chapterList = two.take(1))) + assertEquals(emptyList(), one.load(TwitchTarget.Vod("1")).chapters) + } + + @Test + fun aClipPlaysTheBestFileUpTo1080p() = runBlocking { + val qualities = listOf(TwitchClipQuality(1440, 60, "1440"), TwitchClipQuality(1080, 60, "1080"), TwitchClipQuality(360, 30, "360")) + val loader = TwitchStreamLoader(FakeTwitchRepository(clipPlayback = TwitchClipPlayback(video("https://clips.twitch.tv/a"), qualities))) + assertEquals("1080", loader.load(TwitchTarget.Clip("a")).progressiveUrl) + } + + private fun video(url: String, duration: Long = 0) = Video( + id = url, url = url, title = "Title", thumbnailUrl = "", uploaderName = "Space", uploaderUrl = "https://www.twitch.tv/space", + uploaderAvatarUrl = "", uploaderVerified = false, durationSeconds = duration, isLive = duration == 0L, viewCount = 1, + uploadedAtMillis = 1, isShortFormContent = false, shortDescription = null, + ) + + private companion object { + const val PLAYLIST = "https://watch.example/live/hls/master.m3u8?c=space" + } +} diff --git a/core/data/src/test/java/dev/typetype/android/data/twitch/TwitchMappersTest.kt b/core/data/src/test/java/dev/typetype/android/data/twitch/TwitchMappersTest.kt new file mode 100644 index 00000000..2995a290 --- /dev/null +++ b/core/data/src/test/java/dev/typetype/android/data/twitch/TwitchMappersTest.kt @@ -0,0 +1,87 @@ +package dev.typetype.android.data.twitch + +import dev.typetype.android.data.network.dto.TwitchChatHighlightsDto +import dev.typetype.android.data.network.dto.TwitchClipQualityDto +import dev.typetype.android.data.network.dto.TwitchPinnedMessageDto +import dev.typetype.android.data.network.dto.TwitchPollChoiceDto +import dev.typetype.android.data.network.dto.TwitchPollDto +import dev.typetype.android.data.network.dto.TwitchStreamDto +import dev.typetype.android.data.network.dto.TwitchUserDto +import dev.typetype.android.data.network.dto.TwitchVideoDto +import dev.typetype.android.domain.twitch.TwitchTarget +import dev.typetype.android.domain.twitch.TwitchUrls +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class TwitchMappersTest { + @Test + fun aLiveBecomesALiveVideoOfItsChannel() { + val video = TwitchStreamDto( + title = "Spacewalk", + user = TwitchUserDto(login = "Space", displayName = "Space Agency", avatarUrl = "https://a.example/a.png"), + viewers = 1084, + previewUrl = "https://p.example/p.jpg", + startedAt = "2026-11-17T18:00:00Z", + ).toVideo() + assertEquals("https://www.twitch.tv/space", video.url) + assertEquals("https://www.twitch.tv/space", video.uploaderUrl) + assertEquals("Space Agency", video.uploaderName) + assertTrue(video.isLive) + assertEquals(1084L, video.viewCount) + assertEquals(1_794_938_400_000L, video.uploadedAtMillis) + } + + @Test + fun aPastBroadcastKeepsItsLengthAndProgressAddress() { + val video = TwitchVideoDto(id = "2920156347", title = "Walk", owner = TwitchUserDto(login = "space"), lengthSeconds = 33105).toVideo() + assertEquals("https://www.twitch.tv/videos/2920156347", video.url) + assertEquals(33105L, video.durationSeconds) + } + + @Test + fun playlistsResolveAgainstTheInstanceOrigin() { + assertEquals( + "https://watch.example/live/hls/master.m3u8?c=space", + twitchPlaylistUrl("https://watch.example/api/", "/live/hls/master.m3u8?c=space"), + ) + assertNull(twitchPlaylistUrl("https://watch.example/api/", " ")) + } + + @Test + fun clipQualitiesNeedAHeightAndAnAddress() { + assertEquals(720, TwitchClipQualityDto("720", 29.97, "https://c.example/720.mp4").toQuality()?.height) + assertNull(TwitchClipQualityDto("source", 30.0, "https://c.example/s.mp4").toQuality()) + assertNull(TwitchClipQualityDto("360", 30.0, "").toQuality()) + } + + @Test + fun twitchAddressesAreRecognised() { + assertEquals(TwitchTarget.Live("space"), TwitchUrls.parse("https://www.twitch.tv/Space")) + assertEquals(TwitchTarget.Vod("1"), TwitchUrls.parse("https://www.twitch.tv/videos/1")) + assertEquals(TwitchTarget.Clip("Funny-Clip"), TwitchUrls.parse("https://www.twitch.tv/space/clip/Funny-Clip")) + assertNull(TwitchUrls.parse("https://www.twitch.tv/directory")) + assertNull(TwitchUrls.parse("https://www.youtube.com/watch?v=a")) + } + + @Test + fun badTimesAreIgnored() { + assertEquals(0L, twitchMillis("soon")) + assertEquals(1_794_938_400_000L, twitchMillis("2026-11-17T18:00:00.5Z")) + } + + @Test + fun highlightsKeepARealPollAndPinOnly() { + val highlights = TwitchChatHighlightsDto( + poll = TwitchPollDto(id = "p1", title = "Next boss?", votes = 3, choices = listOf(TwitchPollChoiceDto("a", "Lion", 3))), + pinned = TwitchPinnedMessageDto(id = "m1", text = "Addons in discord", login = "streamelements", displayName = "StreamElements"), + ).toDomain() + assertEquals("Next boss?", highlights.poll?.title) + assertEquals("StreamElements", highlights.pinned?.author) + + val empty = TwitchChatHighlightsDto(poll = TwitchPollDto(id = "p2"), pinned = TwitchPinnedMessageDto(id = "m2")).toDomain() + assertNull(empty.poll) + assertNull(empty.pinned) + } +} 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 239125cf..e8e6aa81 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 @@ -14,6 +14,11 @@ sealed interface LiveChatEvent { data object Connected : LiveChatEvent data class Message(val message: LiveChatMessage) : LiveChatEvent data object Ended : LiveChatEvent + + // Moderation on Twitch: one message taken down, or a viewer's messages (every message when author is null). + data class Removed(val messageId: String) : LiveChatEvent + + data class Cleared(val author: String?) : LiveChatEvent } class LiveChatRequestException(val status: Int, message: String) : Exception(message) diff --git a/core/model/src/main/java/dev/typetype/android/domain/preferences/AppPreferences.kt b/core/model/src/main/java/dev/typetype/android/domain/preferences/AppPreferences.kt index 5a80d7dd..ecee1f22 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/preferences/AppPreferences.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/preferences/AppPreferences.kt @@ -33,4 +33,5 @@ data class AppPreferences( val danmakuEnabled: Boolean = false, val danmakuSpeed: Float = 1f, val danmakuSize: Float = 1f, + val homeLayout: HomeLayout = HomeLayout.Rows, ) diff --git a/core/model/src/main/java/dev/typetype/android/domain/preferences/HomeLayout.kt b/core/model/src/main/java/dev/typetype/android/domain/preferences/HomeLayout.kt new file mode 100644 index 00000000..67fa13bd --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/preferences/HomeLayout.kt @@ -0,0 +1,3 @@ +package dev.typetype.android.domain.preferences + +enum class HomeLayout { Grid, Rows } diff --git a/core/model/src/main/java/dev/typetype/android/domain/preferences/PreferencesRepository.kt b/core/model/src/main/java/dev/typetype/android/domain/preferences/PreferencesRepository.kt index 53402da6..9c00abdb 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/preferences/PreferencesRepository.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/preferences/PreferencesRepository.kt @@ -36,4 +36,5 @@ interface PreferencesRepository { suspend fun setDanmakuEnabled(enabled: Boolean) suspend fun setDanmakuSpeed(speed: Float) suspend fun setDanmakuSize(size: Float) + suspend fun setHomeLayout(layout: HomeLayout) } diff --git a/core/model/src/main/java/dev/typetype/android/domain/server/Server.kt b/core/model/src/main/java/dev/typetype/android/domain/server/Server.kt index 7904e60d..3703b559 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/server/Server.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/server/Server.kt @@ -26,4 +26,5 @@ data class Server( val rss: RssCapability = RssCapability(), val push: PushCapability = PushCapability(), val recommender: RecommenderCapability = RecommenderCapability(), + val twitchEnabled: Boolean = false, ) diff --git a/core/model/src/main/java/dev/typetype/android/domain/setup/SetupRepository.kt b/core/model/src/main/java/dev/typetype/android/domain/setup/SetupRepository.kt index 83486a4a..2e9a23fc 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/setup/SetupRepository.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/setup/SetupRepository.kt @@ -37,4 +37,5 @@ data class ProbeResult( val rss: RssCapability, val push: PushCapability, val recommender: RecommenderCapability = RecommenderCapability(), + val twitchEnabled: Boolean = false, ) diff --git a/core/model/src/main/java/dev/typetype/android/domain/stream/Stream.kt b/core/model/src/main/java/dev/typetype/android/domain/stream/Stream.kt index 34fc58b6..9e9a6e3a 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/stream/Stream.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/stream/Stream.kt @@ -44,6 +44,12 @@ data class Stream( val isLiveContent: Boolean = false, val requiresMembership: Boolean = false, val category: String? = null, + // Where a live settles behind its edge when the source asks for it; null keeps the playlist's own target. + val liveTargetOffsetMillis: Long? = null, + // A Twitch live's recording in progress, which the web rewinds into; the watch page offers to start over there. + val startOverUrl: String? = null, + // Media3 moves a growing playlist to its live edge once loaded; a recording keeps the position it was opened at. + val holdsStartPosition: Boolean = false, ) data class StreamStoryboard( 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 new file mode 100644 index 00000000..2ef0a396 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchAccountRepository.kt @@ -0,0 +1,42 @@ +package dev.typetype.android.domain.twitch + +import dev.typetype.android.domain.feed.Video + +data class TwitchAccountStatus(val linked: Boolean, val name: String?) + +data class TwitchLinkCode( + val deviceCode: String, + val userCode: String, + val activationUrl: String, + val intervalSeconds: Int, + val expiresInSeconds: Int, +) + +sealed interface TwitchLinkPoll { + data object Pending : TwitchLinkPoll + + data object SlowDown : TwitchLinkPoll + + data class Linked(val name: String) : TwitchLinkPoll +} + +// Twitch device code login: the app shows a code, the viewer confirms it on twitch.tv/activate. +interface TwitchAccountRepository { + suspend fun status(): Result + + suspend fun start(): Result + + suspend fun poll(deviceCode: String): Result + + suspend fun unlink(): Result + + suspend fun followedLives(cursor: String? = null): Result> + + suspend fun isFollowing(login: String): Result + + suspend fun setFollowing(login: String, follow: Boolean): Result + + suspend fun sendChat(login: String, message: String): Result + + suspend fun votePoll(pollId: String, choiceId: String): Result +} 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 new file mode 100644 index 00000000..2daced18 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchModels.kt @@ -0,0 +1,53 @@ +package dev.typetype.android.domain.twitch + +import dev.typetype.android.domain.feed.Video + +data class TwitchCategory( + val id: String, + val name: String, + val slug: String, + val boxArtUrl: String?, + val viewers: Long?, +) + +data class TwitchPage(val items: List, val cursor: String?) + +data class TwitchChannel( + val login: String, + val displayName: String, + val avatarUrl: String?, + val description: String, + val bannerUrl: String?, + val followers: Long, + val live: Video?, +) { + val url: String get() = TwitchUrls.live(login) +} + +data class TwitchPlayback( + val video: Video, + val playlistUrl: String, + val audioPlaylistUrl: String?, + val live: Boolean, + val startOverUrl: String? = null, +) + +data class TwitchClipQuality(val height: Int, val frameRate: Int, val url: String) + +data class TwitchClipPlayback(val video: Video, val qualities: List) + +data class TwitchPollChoice(val id: String, val title: String, val votes: Long) + +data class TwitchPoll(val id: String, val title: String, val votes: Long, val choices: List) + +data class TwitchPinnedMessage(val id: String, val text: String, val author: String) + +data class TwitchChatHighlights(val poll: TwitchPoll?, val pinned: TwitchPinnedMessage?) + +data class TwitchVideoComment( + val id: String, + val offsetSeconds: Long, + val author: String?, + val text: String, + val moderator: Boolean, +) 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 new file mode 100644 index 00000000..531fdda2 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchRepository.kt @@ -0,0 +1,34 @@ +package dev.typetype.android.domain.twitch + +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.stream.Chapter + +interface TwitchRepository { + suspend fun popular(cursor: String? = null): Result> + + suspend fun categories(cursor: String? = null): Result> + + suspend fun categoryLives(slug: String, cursor: String? = null): Result> + + suspend fun channel(login: String): Result + + suspend fun channelVods(login: String, cursor: String? = null): Result> + + suspend fun channelClips(login: String, cursor: String? = null): Result> + + suspend fun live(login: String): Result + + suspend fun vod(id: String): Result + + suspend fun chapters(id: String): Result> + + suspend fun clip(slug: String): Result + + suspend fun searchChannels(query: String, cursor: String? = null): Result> + + suspend fun searchLives(query: String, cursor: String? = null): Result> + + suspend fun chatHighlights(login: String): Result + + suspend fun videoComments(id: String, offsetSeconds: Long?, cursor: String?): Result> +} diff --git a/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchUrls.kt b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchUrls.kt new file mode 100644 index 00000000..ca52d967 --- /dev/null +++ b/core/model/src/main/java/dev/typetype/android/domain/twitch/TwitchUrls.kt @@ -0,0 +1,38 @@ +package dev.typetype.android.domain.twitch + +import java.net.URI + +sealed interface TwitchTarget { + data class Live(val login: String) : TwitchTarget + data class Vod(val id: String) : TwitchTarget + data class Clip(val slug: String) : TwitchTarget +} + +object TwitchUrls { + fun live(login: String) = "https://www.twitch.tv/${login.lowercase()}" + + fun vod(id: String) = "https://www.twitch.tv/videos/$id" + + fun clip(slug: String) = "https://clips.twitch.tv/$slug" + + fun parse(url: String): TwitchTarget? { + val uri = runCatching { URI(url.trim()) }.getOrNull() ?: return null + val host = uri.host?.lowercase() ?: return null + val segments = uri.path.orEmpty().split('/').filter { it.isNotEmpty() } + if (host == "clips.twitch.tv") return segments.singleOrNull()?.let(TwitchTarget::Clip) + if (host != "twitch.tv" && !host.endsWith(".twitch.tv")) return null + return when { + segments.size == 2 && segments[0] == "videos" && segments[1].all(Char::isDigit) -> TwitchTarget.Vod(segments[1]) + segments.size == 3 && segments[1] == "clip" -> TwitchTarget.Clip(segments[2]) + segments.size == 1 && LOGIN.matches(segments[0]) && segments[0].lowercase() !in RESERVED -> + TwitchTarget.Live(segments[0].lowercase()) + else -> null + } + } + + private val LOGIN = Regex("[A-Za-z0-9_]{1,25}") + private val RESERVED = setOf( + "directory", "search", "settings", "videos", "downloads", "drops", "inventory", "jobs", "p", "prime", + "store", "subscriptions", "turbo", "wallet", + ) +} diff --git a/core/model/src/main/java/dev/typetype/android/domain/usersettings/UserSettings.kt b/core/model/src/main/java/dev/typetype/android/domain/usersettings/UserSettings.kt index 0df75d27..1b02c1a6 100644 --- a/core/model/src/main/java/dev/typetype/android/domain/usersettings/UserSettings.kt +++ b/core/model/src/main/java/dev/typetype/android/domain/usersettings/UserSettings.kt @@ -37,6 +37,9 @@ data class UserSettings( val hideMembersOnlyContent: Boolean = false, val hideSubscriptionLiveStreams: Boolean = false, val supportsHideSubscriptionLiveStreams: Boolean = false, + val hideWatchedSubscriptionVideos: Boolean = false, + val watchedThresholdPercent: Int = 0, + val supportsWatchedSettings: Boolean = false, val disableWatchHistory: Boolean = false, val deArrowEnabled: Boolean = false, val deArrowTitleMode: String = "dearrow", diff --git a/core/playback/src/main/java/dev/typetype/android/playback/PlayerRequestMetadata.kt b/core/playback/src/main/java/dev/typetype/android/playback/PlayerRequestMetadata.kt index ffc54265..bffea0c9 100644 --- a/core/playback/src/main/java/dev/typetype/android/playback/PlayerRequestMetadata.kt +++ b/core/playback/src/main/java/dev/typetype/android/playback/PlayerRequestMetadata.kt @@ -64,6 +64,7 @@ fun PlayableSource.toRequestMetadata( (sabrSession?.startTimeMs ?: resumePositionMillis).coerceAtLeast(0L), ) putBoolean(MergedStreamMediaKeys.EXTRA_IS_LIVE_CONTENT, isLiveContent) + putBoolean(MergedStreamMediaKeys.EXTRA_HOLD_START_POSITION, stream?.holdsStartPosition == true) putBoolean( MergedStreamMediaKeys.EXTRA_AUDIO_ONLY_PREFER_ORIGINAL, preferOriginalAudio, diff --git a/core/playback/src/main/java/dev/typetype/android/playback/ResolvedMediaItem.kt b/core/playback/src/main/java/dev/typetype/android/playback/ResolvedMediaItem.kt index befaf1be..2f3b13cf 100644 --- a/core/playback/src/main/java/dev/typetype/android/playback/ResolvedMediaItem.kt +++ b/core/playback/src/main/java/dev/typetype/android/playback/ResolvedMediaItem.kt @@ -36,6 +36,19 @@ fun buildResolvedMediaItem( ), ) .apply { source.mimeType?.let(::setMimeType) } + .apply { stream.liveTargetOffsetMillis?.let { setLiveConfiguration(lowLatencyLive(it)) } } .setSubtitleConfigurations(subtitles.toSubtitleConfigurations()) .build() } + +// Twitch announces a 6 s target duration for 2 s segments, so the offset is set in milliseconds; the player may speed +// up a little to settle there, like the web player's low latency mode. +private fun lowLatencyLive(targetMillis: Long): MediaItem.LiveConfiguration = MediaItem.LiveConfiguration.Builder() + .setTargetOffsetMs(targetMillis) + .setMaxOffsetMs(targetMillis + LOW_LATENCY_MAX_EXTRA_MS) + .setMinPlaybackSpeed(1f) + .setMaxPlaybackSpeed(LOW_LATENCY_MAX_SPEED) + .build() + +private const val LOW_LATENCY_MAX_EXTRA_MS = 6_000L +private const val LOW_LATENCY_MAX_SPEED = 1.1f diff --git a/core/playback/src/main/java/dev/typetype/android/services/MergedStreamMediaKeys.kt b/core/playback/src/main/java/dev/typetype/android/services/MergedStreamMediaKeys.kt index 0df40629..2ebfee75 100644 --- a/core/playback/src/main/java/dev/typetype/android/services/MergedStreamMediaKeys.kt +++ b/core/playback/src/main/java/dev/typetype/android/services/MergedStreamMediaKeys.kt @@ -34,6 +34,7 @@ object MergedStreamMediaKeys { const val EXTRA_ACCOUNT_ID = "typetype.account_id" const val EXTRA_SERVER_BASE_URL = "typetype.server_base_url" const val EXTRA_RESUME_POSITION_MILLIS = "typetype.resume_position_millis" + const val EXTRA_HOLD_START_POSITION = "typetype.hold_start_position" const val EXTRA_IS_LIVE_CONTENT = "typetype.is_live_content" const val EXTRA_VIDEO_TITLE = "typetype.video_title" const val EXTRA_VIDEO_THUMBNAIL = "typetype.video_thumbnail" diff --git a/core/playback/src/main/java/dev/typetype/android/services/PlaybackService.kt b/core/playback/src/main/java/dev/typetype/android/services/PlaybackService.kt index 74bd7792..e0a9e2ec 100644 --- a/core/playback/src/main/java/dev/typetype/android/services/PlaybackService.kt +++ b/core/playback/src/main/java/dev/typetype/android/services/PlaybackService.kt @@ -100,6 +100,7 @@ class PlaybackService : MediaSessionService() { ) val audioOnlyDefaultPolicy = AudioOnlyDefaultPolicy() player.addListener(audioOnlyDefaultPolicy) + player.addListener(RecordingStartHolder(player)) audioOnlyPlaybackBridge = playbackBridge playbackResumeRecorder = PlaybackResumeRecorder( player, diff --git a/core/playback/src/main/java/dev/typetype/android/services/RecordingStartHolder.kt b/core/playback/src/main/java/dev/typetype/android/services/RecordingStartHolder.kt new file mode 100644 index 00000000..b8ee50fc --- /dev/null +++ b/core/playback/src/main/java/dev/typetype/android/services/RecordingStartHolder.kt @@ -0,0 +1,26 @@ +package dev.typetype.android.services + +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.common.Timeline + +// Media3 moves a growing playlist to its live edge once the playlist is loaded, whatever start position it was given. +// A Twitch recording opened from its start, or from a saved position, seeks back there once its timeline is known. +internal class RecordingStartHolder(private val player: Player) : Player.Listener { + private var heldMediaId: String? = null + + override fun onTimelineChanged(timeline: Timeline, reason: Int) { + val item = player.currentMediaItem ?: return + val extras = item.requestMetadata.extras ?: return + if (!extras.getBoolean(MergedStreamMediaKeys.EXTRA_HOLD_START_POSITION) || item.mediaId == heldMediaId) return + if (timeline.isEmpty) return + val window = timeline.getWindow(player.currentMediaItemIndex, Timeline.Window()) + if (window.isPlaceholder || !window.isDynamic) return + heldMediaId = item.mediaId + player.seekTo(extras.resumePositionMillis() ?: 0L) + } + + override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { + if (mediaItem?.mediaId != heldMediaId) heldMediaId = null + } +} diff --git a/core/resources/src/main/res/drawable/ic_live.xml b/core/resources/src/main/res/drawable/ic_live.xml new file mode 100644 index 00000000..9eb2ca2d --- /dev/null +++ b/core/resources/src/main/res/drawable/ic_live.xml @@ -0,0 +1,9 @@ + + + diff --git a/core/resources/src/main/res/values/strings.xml b/core/resources/src/main/res/values/strings.xml index 91628585..103527fd 100644 --- a/core/resources/src/main/res/values/strings.xml +++ b/core/resources/src/main/res/values/strings.xml @@ -2,6 +2,7 @@ TypeType %1$s views + %1$s watching Premieres %1$s Views hidden by provider Welcome aboard @@ -82,6 +83,18 @@ Shorts Subscriptions Library + Live + Live now on Twitch + Twitch lives could not be loaded + Videos + Clips + Nothing here yet + Search Twitch channels + Live now + All + Followed channels live + Follow + Following Couldn\'t load Shorts Couldn\'t load more Shorts No Shorts are available yet. @@ -276,6 +289,12 @@ Hide videos that need a channel membership Hide subscription live streams Remove live and upcoming streams from subscriptions + Hide watched videos in Subscriptions + Videos you have watched no longer show in your subscriptions feed + Count as watched + How much of a video you need to watch before it shows as watched + Last minute (default) + %1$d%% Content settings Couldn\'t update content settings Red @@ -556,9 +575,16 @@ Switch instance or account Add an instance Linked accounts - Sign in to YouTube or BiliBili through your instance + Sign in to YouTube, BiliBili or Twitch through your instance YouTube BiliBili + Twitch + Connect Twitch + Open twitch.tv/activate and enter this code + Open Twitch + Connected as %1$s + The code expired. Start again for a new one. + Twitch could not be reached Connected Needs to sign in again Not connected @@ -607,7 +633,17 @@ Couldn\'t switch account Couldn\'t forget account Live chat + Chat replay + Start over + The chat replay is not available for this video No messages yet + Pinned · %1$s + %1$s, %2$d%% + Hide + Send a message + Send + Twitch refused the message + Vote for %1$s Connecting… Live Reconnecting… @@ -1059,6 +1095,9 @@ Nothing from the family list yet No family-list results. Try a channel you already trust. Trending + Home page layout + As usual + By category Recommended Recommendations Choose the algorithm, its settings, your interests and the data it reads @@ -1456,6 +1495,7 @@ Go back Your session expired. Open accounts to sign in again or start a new guest session. Couldn\'t load this video + The stream has ended. Something went wrong Failed to load stream. This instance needs a connected YouTube session to play this video. @@ -1767,4 +1807,12 @@ Turn off new video notifications Disable battery optimization for reliable notification delivery. Battery settings + + %1$s follower + %1$s followers + + + %1$d vote + %1$d votes + diff --git a/core/ui/src/main/java/dev/typetype/android/core/ui/components/RelatedVideoCard.kt b/core/ui/src/main/java/dev/typetype/android/core/ui/components/RelatedVideoCard.kt index 76624679..fd4c5bca 100644 --- a/core/ui/src/main/java/dev/typetype/android/core/ui/components/RelatedVideoCard.kt +++ b/core/ui/src/main/java/dev/typetype/android/core/ui/components/RelatedVideoCard.kt @@ -179,6 +179,7 @@ private fun Video.metadataText(): String { val scheduledAt = releaseTimeMillis()?.takeIf { it > nowMillis } val badge = badgeStatusAt(nowMillis) val views = when { + viewCount >= 0L && badge == VideoBadgeStatus.Live -> stringResource(R.string.video_watching_short, formatRelatedViews(viewCount)) viewCount >= 0L -> stringResource(R.string.video_views_short, formatRelatedViews(viewCount)) scheduledAt != null && (badge == VideoBadgeStatus.Premiere || badge == VideoBadgeStatus.Upcoming) -> diff --git a/core/ui/src/main/java/dev/typetype/android/core/ui/components/VideoCard.kt b/core/ui/src/main/java/dev/typetype/android/core/ui/components/VideoCard.kt index 0094ce2c..9c5664fb 100644 --- a/core/ui/src/main/java/dev/typetype/android/core/ui/components/VideoCard.kt +++ b/core/ui/src/main/java/dev/typetype/android/core/ui/components/VideoCard.kt @@ -216,6 +216,7 @@ private fun Video.metadataText(): String? { val scheduledAt = releaseTimeMillis()?.takeIf { it > nowMillis } val badge = badgeStatusAt(nowMillis) val views = when { + viewCount >= 0L && badge == VideoBadgeStatus.Live -> stringResource(R.string.video_watching_short, formatViews(viewCount)) viewCount >= 0L -> stringResource( R.string.video_views_short, formatViews(viewCount), diff --git a/core/ui/src/main/java/dev/typetype/android/core/ui/navigation/Routes.kt b/core/ui/src/main/java/dev/typetype/android/core/ui/navigation/Routes.kt index 1c707c32..b55e5334 100644 --- a/core/ui/src/main/java/dev/typetype/android/core/ui/navigation/Routes.kt +++ b/core/ui/src/main/java/dev/typetype/android/core/ui/navigation/Routes.kt @@ -32,6 +32,12 @@ data object SubscriptionsRoute @Serializable data object LibraryRoute +@Serializable +data object LiveRoute + +@Serializable +data class TwitchChannelRoute(val login: String) + @Serializable data class LibraryLandingRoute(val tab: String) diff --git a/feature/home/src/androidTest/java/dev/typetype/android/feature/home/HomeLayoutTest.kt b/feature/home/src/androidTest/java/dev/typetype/android/feature/home/HomeLayoutTest.kt new file mode 100644 index 00000000..36b8265b --- /dev/null +++ b/feature/home/src/androidTest/java/dev/typetype/android/feature/home/HomeLayoutTest.kt @@ -0,0 +1,110 @@ +package dev.typetype.android.feature.home + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import dev.typetype.android.core.ui.components.LocalAnimatedStatePlayback +import dev.typetype.android.core.ui.theme.TypeTypeTheme +import dev.typetype.android.domain.feed.HomeRecommendationRow +import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.preferences.HomeLayout +import dev.typetype.android.feature.menu.VideoMenuScope +import java.util.concurrent.atomic.AtomicReference +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test + +class HomeLayoutTest { + @get:Rule + val composeRule = createComposeRule() + + @Test + fun rowsShowTheirCategoryTitles() { + show(HomeLayout.Rows) + + composeRule.onNodeWithText("By category").assertIsSelected() + composeRule.onNodeWithText("Space row").assertIsDisplayed() + composeRule.onNodeWithText("First video").assertIsDisplayed() + } + + @Test + fun gridShowsTheVideosWithoutCategoryTitles() { + show(HomeLayout.Grid) + + composeRule.onNodeWithText("As usual").assertIsSelected() + composeRule.onNodeWithText("Space row").assertDoesNotExist() + composeRule.onNodeWithText("First video").assertIsDisplayed() + } + + @Test + fun choosingALayoutSendsIt() { + val chosen = AtomicReference() + show(HomeLayout.Rows, onAction = chosen::set) + + composeRule.onNodeWithText("As usual").performClick() + + assertEquals(HomeAction.SetLayout(HomeLayout.Grid), chosen.get()) + } + + private fun show(layout: HomeLayout, onAction: (HomeAction) -> Unit = {}) { + val state = HomeState( + videos = listOf(video("first", "First video")), + layout = layout, + recommender = HomeRecommenderState( + algorithm = "typetype", + rows = listOf( + HomeRecommendationRow( + id = "space", + title = "Space row", + reason = "topic", + reasonRef = null, + videoUrls = listOf("https://video.example/first"), + ), + ), + ), + ) + composeRule.setContent { + CompositionLocalProvider(LocalAnimatedStatePlayback provides false) { + TypeTypeTheme { + HomeContent( + state = state, + menuScope = VideoMenuScope( + watchedUrls = emptySet(), + blockedVideoUrls = emptySet(), + blockedChannelUrls = emptySet(), + blockedKeywords = emptySet(), + favorites = emptySet(), + watchLater = emptySet(), + onAction = { _, _ -> }, + ), + onPlayVideo = {}, + onOpenChannel = {}, + onRetry = {}, + onLoadMore = {}, + onAction = onAction, + ) + } + } + } + } + + private fun video(id: String, title: String) = Video( + id = id, + url = "https://video.example/$id", + title = title, + thumbnailUrl = "", + uploaderName = "Channel", + uploaderUrl = "https://channel.example/channel", + uploaderAvatarUrl = "", + uploaderVerified = false, + durationSeconds = 180L, + isLive = false, + viewCount = 1L, + uploadedAtMillis = 1L, + isShortFormContent = false, + shortDescription = null, + ) +} diff --git a/feature/home/src/main/java/dev/typetype/android/feature/home/HomeAction.kt b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeAction.kt index e0241670..ae2cf1f4 100644 --- a/feature/home/src/main/java/dev/typetype/android/feature/home/HomeAction.kt +++ b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeAction.kt @@ -1,6 +1,7 @@ package dev.typetype.android.feature.home import dev.typetype.android.domain.feed.Video +import dev.typetype.android.domain.preferences.HomeLayout import dev.typetype.android.domain.recommendations.PageRefusalReason import dev.typetype.android.domain.recommendations.VideoRefusalReason @@ -15,4 +16,5 @@ sealed interface HomeAction { data class RatePage(val good: Boolean) : HomeAction data class ChoosePageReason(val reason: PageRefusalReason) : HomeAction data class SendPageVerdict(val comment: String) : HomeAction + data class SetLayout(val layout: HomeLayout) : HomeAction } diff --git a/feature/home/src/main/java/dev/typetype/android/feature/home/HomeLayoutToggle.kt b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeLayoutToggle.kt new file mode 100644 index 00000000..8a7c64d0 --- /dev/null +++ b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeLayoutToggle.kt @@ -0,0 +1,38 @@ +package dev.typetype.android.feature.home + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import dev.typetype.android.R +import dev.typetype.android.domain.preferences.HomeLayout + +@Composable +internal fun HomeLayoutToggle(layout: HomeLayout, onLayout: (HomeLayout) -> Unit) { + val label = stringResource(R.string.home_layout_label) + val options = listOf( + HomeLayout.Grid to stringResource(R.string.home_layout_grid), + HomeLayout.Rows to stringResource(R.string.home_layout_rows), + ) + Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + SingleChoiceSegmentedButtonRow(modifier = Modifier.semantics { contentDescription = label }) { + options.forEachIndexed { index, (value, text) -> + SegmentedButton( + selected = layout == value, + onClick = { onLayout(value) }, + shape = SegmentedButtonDefaults.itemShape(index = index, count = options.size), + ) { + Text(text) + } + } + } + } +} diff --git a/feature/home/src/main/java/dev/typetype/android/feature/home/HomeRecommenderGrid.kt b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeRecommenderGrid.kt index 49251412..ca80f83d 100644 --- a/feature/home/src/main/java/dev/typetype/android/feature/home/HomeRecommenderGrid.kt +++ b/feature/home/src/main/java/dev/typetype/android/feature/home/HomeRecommenderGrid.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyGridScope +import androidx.compose.foundation.lazy.grid.items as gridItems import androidx.compose.foundation.lazy.items import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @@ -37,6 +38,7 @@ internal fun LazyGridScope.recommendedRows( onPlayVideo = onPlayVideo, onOpenChannel = onOpenChannel, onAction = onAction, + modifier = Modifier.width(ROW_CARD_WIDTH), ) } } @@ -45,6 +47,26 @@ internal fun LazyGridScope.recommendedRows( } } +internal fun LazyGridScope.recommendedGrid( + recommender: HomeRecommenderState, + videos: List