Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Add YouTube Music as an alternative streaming backend
Lelonio1475b7cd75fc
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex c5e41d5..ea7855c 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -125,6 +125,8 @@ android {}compileOptions {+ // Required by the vendored :innertube module, which reads java.time.+ isCoreLibraryDesugaringEnabled = truesourceCompatibility = JavaVersion.VERSION_17targetCompatibility = JavaVersion.VERSION_17}@@ -185,12 +187,16 @@ dependencies {implementation(libs.okhttp.logging)implementation(libs.retrofit)implementation(libs.retrofit.serialization)+ implementation(libs.newpipe.extractor)+ implementation(project(":innertube"))implementation(libs.coil.compose)implementation(libs.androidx.palette)implementation(libs.androidx.navigation.compose)implementation(libs.backdrop)implementation(libs.kyant.shapes)implementation(libs.phosphor)++ coreLibraryDesugaring(libs.desugaring)}/** Pinned so a build is not at the mercy of upstream's next commit. */diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 90ac75c..19c0873 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -30,6 +30,8 @@android:name=".ui.MainActivity"android:exported="true"android:launchMode="singleTask"+ android:supportsPictureInPicture="true"+ android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation|keyboardHidden"android:windowSoftInputMode="adjustResize"><intent-filter><action android:name="android.intent.action.MAIN" />diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.ktindex 5d134e1..5376f0c 100644--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt@@ -54,4 +54,39 @@ class SquareApplication : Application() {/** The user's saved speed / pitch / reverb combinations. */val effectPresets: EffectPresetStore by lazy { EffectPresetStore(this) }++ /**+ * The Spotify source, behind the common backend interface.+ *+ * A single instance because it owns the AudioTrack the native sink writes+ * into, and a second one would be a second sink for the same engine.+ */+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)+ val spotifyBackend: dev.lelonio.square.backend.SpotifyBackend by lazy {+ dev.lelonio.square.backend.SpotifyBackend(this)+ }++ /** The Google session YouTube Music reads a personal library with. */+ val youtubeAccount: dev.lelonio.square.backend.youtube.YouTubeAccount by lazy {+ dev.lelonio.square.backend.youtube.YouTubeAccount(this)+ }++ /** YouTube Music; see [dev.lelonio.square.backend.youtube.YouTubeBackend]. */+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)+ val youtubeBackend: dev.lelonio.square.backend.youtube.YouTubeBackend by lazy {+ dev.lelonio.square.backend.youtube.YouTubeBackend(youtubeAccount)+ }++ /**+ * Whichever of the two the user picked.+ *+ * Read afresh each time rather than held: the setting can change while the+ * app is running, and a cached backend would keep answering as the old one.+ */+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)+ val activeBackend: dev.lelonio.square.backend.MusicBackend+ get() = when (preferences.backend.value) {+ dev.lelonio.square.backend.BackendId.SPOTIFY -> spotifyBackend+ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC -> youtubeBackend+ }}diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.ktnew file mode 100644index 0000000..c6b133f--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt@@ -0,0 +1,142 @@+package dev.lelonio.square.backend++import androidx.media3.common.Player+import dev.lelonio.square.data.CatalogPlaylist+import dev.lelonio.square.data.CatalogTrack+import dev.lelonio.square.data.SearchResults+import kotlinx.coroutines.flow.StateFlow++/** Which backend supplies catalogue and playback. */+enum class BackendId { SPOTIFY, YOUTUBE_MUSIC }++/** Where a [MusicBackend] stands with its own account/session. */+sealed interface BackendAuthState {+ data object LoggedOut : BackendAuthState+ data object Connecting : BackendAuthState+ data class LoggedIn(val displayName: String, val avatarUrl: String? = null) : BackendAuthState+ data class Failed(val message: String) : BackendAuthState+}++/**+ * What each kind of search result is called, in the app's language.+ *+ * Passed in rather than resolved by the backend: a backend has no context to+ * read resources from, and the strings are the UI's business anyway.+ */+data class SearchLabels(+ val artist: String,+ val album: String,+ val playlist: String,+)++/**+ * One shelf of a backend's home page.+ *+ * Either tracks or things to open, never both — that is how the services+ * themselves build a row, and a row that mixed the two would have no single+ * answer to what tapping it does.+ */+data class HomeRow(+ val title: String,+ val tracks: List<CatalogTrack> = emptyList(),+ /** Playlists, albums and artists alike: all of them open a track list. */+ val items: List<CatalogPlaylist> = emptyList(),+) {+ val isEmpty: Boolean get() = tracks.isEmpty() && items.isEmpty()+}++/**+ * A source of music: catalogue reads plus a [Player] that can play what the+ * catalogue points at.+ *+ * Every method mirrors something the UI already asks Spotify for directly, so+ * wrapping the existing code behind this changes who is asked, not what is+ * done. A backend that cannot answer something (YouTube Music has no Spotify+ * Connect device list, for instance) returns the empty value rather than+ * throwing: no screen should have to know which backend is active to stay+ * usable.+ */+interface MusicBackend {++ val id: BackendId+ val authState: StateFlow<BackendAuthState>++ /** True once catalogue calls and playback can be expected to work. */+ val isReady: Boolean++ suspend fun refreshAuth()+ suspend fun logOut()++ suspend fun search(query: String, labels: SearchLabels): SearchResults++ /** The signed-in account's own playlists; empty when logged out or unsupported. */+ suspend fun playlists(): List<CatalogPlaylist>++ /**+ * The backend's own home page, as it chooses to lay it out.+ *+ * Rows rather than named sections this app invents, because YouTube Music's+ * home really is a list of shelves with its own titles — "Listen again",+ * "Mixed for you", a chart — and picking a fixed set of them here would+ * throw away most of the page and mislabel the rest.+ *+ * Empty by default: a backend whose home is assembled from the account's+ * own data elsewhere has no use for it.+ */+ suspend fun homeRows(): List<HomeRow> = emptyList()++ /** Tracks of a playlist, album, or artist URI this backend owns. */+ suspend fun tracksOf(uri: String): List<CatalogTrack>++ /**+ * The words to a track, or null when nobody has them.+ *+ * Given the track's details rather than just its URI because not every+ * backend looks lyrics up by identity — the YouTube one matches on title,+ * artist and length against an outside database.+ */+ suspend fun lyrics(uri: String, title: String, artist: String, durationMs: Long): dev.lelonio.square.data.Lyrics? = null++ /**+ * Whether the account can be asked to make and change playlists.+ *+ * False when signed out, and on Spotify also when the user has not+ * registered their own application: the playback session's client id cannot+ * write. See `WebApiAccount`.+ */+ val canEditPlaylists: Boolean get() = false++ /** Creates an empty playlist and returns it, ready to be opened. */+ suspend fun createPlaylist(name: String): CatalogPlaylist =+ throw UnsupportedOperationException()++ suspend fun renamePlaylist(uri: String, name: String): Unit =+ throw UnsupportedOperationException()++ /** Removes it from the account's library. */+ suspend fun deletePlaylist(uri: String): Unit =+ throw UnsupportedOperationException()++ /** Whether this backend's catalogue owns the given URI. */+ fun owns(uri: String): Boolean++ /**+ * Builds the [Player] this backend plays through.+ *+ * Called once by `PlaybackService` for the selected backend; the caller owns+ * the player from there — releasing it, and attaching it to the session.+ */+ fun createPlayer(host: PlaybackHost): Player+}++/**+ * What a backend's player needs from the service hosting it.+ *+ * Kept narrow on purpose: a player reaching back into `PlaybackService` would+ * couple every backend to Spotify's queue-saving and engine-restart logic, none+ * of which applies to a backend that has no native engine.+ */+interface PlaybackHost {+ val context: android.content.Context+ val looper: android.os.Looper+}diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.ktnew file mode 100644index 0000000..72bfde4--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt@@ -0,0 +1,194 @@+package dev.lelonio.square.backend++import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import dev.lelonio.square.SquareApplication+import dev.lelonio.square.data.Catalog+import dev.lelonio.square.data.CatalogPlaylist+import dev.lelonio.square.data.CatalogTrack+import dev.lelonio.square.data.PlaylistDetailsDto+import dev.lelonio.square.data.SearchResults+import dev.lelonio.square.data.toCatalogTrack+import dev.lelonio.square.data.toResults+import dev.lelonio.square.nativecore.NativeBridge+import dev.lelonio.square.playback.AudioOutput+import dev.lelonio.square.playback.LibrespotPlayer+import dev.lelonio.square.playback.PlayQueue+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * The existing Spotify path, behind [MusicBackend].+ *+ * Nothing here is new: the catalogue calls are the ones the UI already made+ * against [Catalog] and the Web API, and [createPlayer] builds the same+ * [LibrespotPlayer] `PlaybackService` built inline. The engine's *lifetime* is+ * deliberately still the service's — starting it needs a token, a language, a+ * bitrate and a restart path for each, none of which a backend should own.+ */+@UnstableApi+class SpotifyBackend(private val container: SquareApplication) : MusicBackend {++ override val id = BackendId.SPOTIFY++ private val _authState = MutableStateFlow<BackendAuthState>(+ if (container.tokenStore.isLoggedIn) BackendAuthState.Connecting else BackendAuthState.LoggedOut,+ )+ override val authState: StateFlow<BackendAuthState> = _authState.asStateFlow()++ /**+ * Logged in *and* the access point has answered.+ *+ * Both halves matter: a stored token with no engine behind it yet is a+ * session every catalogue call would fail against.+ */+ override val isReady: Boolean+ get() = container.tokenStore.isLoggedIn && NativeBridge.isConnected++ override suspend fun refreshAuth() {+ if (!container.tokenStore.isLoggedIn) {+ _authState.value = BackendAuthState.LoggedOut+ return+ }+ _authState.value = runCatching { Catalog.username() }+ .fold(+ onSuccess = { BackendAuthState.LoggedIn(it) },+ onFailure = { BackendAuthState.Failed(it.message ?: it::class.java.simpleName) },+ )+ }++ override suspend fun logOut() {+ container.tokenStore.clear()+ _authState.value = BackendAuthState.LoggedOut+ }++ /**+ * Search goes through the user's own registered application; see+ * [dev.lelonio.square.auth.WebApiAccount] for why it cannot use the+ * playback session's client id.+ */+ override suspend fun search(query: String, labels: SearchLabels): SearchResults {+ if (!container.webApi.isReady) return SearchResults()+ return container.api.search(query.trim()).toResults(+ artistLabel = labels.artist,+ albumLabel = labels.album,+ playlistLabel = labels.playlist,+ )+ }++ /** The access point first, the Web API when `rootlist` fails; see MainViewModel. */+ override suspend fun playlists(): List<CatalogPlaylist> =+ runCatching { Catalog.playlists() }+ .recoverCatching {+ check(container.webApi.isReady) { it.message ?: "rootlist non disponibile" }+ container.api.playlists(limit = WEB_API_PAGE).items.map { dto ->+ CatalogPlaylist(+ uri = dto.uri,+ name = dto.name,+ artworkUrl = dto.images.firstOrNull()?.url,+ )+ }+ }+ .getOrThrow()++ /**+ * A whole playlist, album or artist, resolved in one go.+ *+ * The detail screen does not call this: it publishes each page as it lands+ * and needs the loop itself. This is for callers that just want the list.+ */+ override suspend fun tracksOf(uri: String): List<CatalogTrack> = when {+ uri.startsWith("spotify:artist:") -> {+ check(container.webApi.isReady) { "un artista richiede la tua applicazione Spotify" }+ container.api.artistTopTracks(uri.substringAfterLast(':')).tracks+ .map { it.toCatalogTrack() }+ }++ container.webApi.isReady && uri.startsWith("spotify:playlist:") ->+ webApiPlaylistTracks(uri.substringAfterLast(':'))++ else -> Catalog.tracks(Catalog.contextTrackUris(uri))+ }++ private suspend fun webApiPlaylistTracks(id: String): List<CatalogTrack> {+ val loaded = mutableListOf<CatalogTrack>()+ var offset = 0+ while (true) {+ val page = container.api.playlistTracks(id, limit = WEB_API_PAGE, offset = offset)+ // Episodes and delisted tracks arrive as a null track, and an+ // unplayable one is something the engine could only skip.+ loaded += page.items.mapNotNull { item ->+ item.track+ ?.takeIf { it.isPlayable != false && it.uri.startsWith("spotify:track:") }+ ?.toCatalogTrack(item.addedAt)+ }+ offset += page.items.size+ if (page.items.isEmpty() || offset >= page.total) return loaded+ }+ }++ /** Spotify's own, which the access point serves; see [Catalog.lyrics]. */+ override suspend fun lyrics(+ uri: String,+ title: String,+ artist: String,+ durationMs: Long,+ ) = Catalog.lyrics(uri)++ override val canEditPlaylists: Boolean+ get() = container.tokenStore.isLoggedIn && container.webApi.isReady++ override suspend fun createPlaylist(name: String): CatalogPlaylist {+ // The account's own id: Spotify creates a playlist under a user rather+ // than under "me", even though the token already says who that is.+ val userId = container.api.me().id+ val created = container.api.createPlaylist(userId, PlaylistDetailsDto(name))+ return CatalogPlaylist(+ uri = created.uri,+ name = created.name,+ artworkUrl = created.images.firstOrNull()?.url,+ )+ }++ override suspend fun renamePlaylist(uri: String, name: String) {+ container.api.updatePlaylistDetails(uri.substringAfterLast(':'), PlaylistDetailsDto(name))+ }++ override suspend fun deletePlaylist(uri: String) {+ container.api.unfollowPlaylist(uri.substringAfterLast(':'))+ }++ override fun owns(uri: String) = uri.startsWith("spotify:")++ /**+ * The queue behind the player built by [createPlayer].+ *+ * Exposed because only the queue knows the pre-shuffle order and the+ * permutation on top of it, which is what the service writes to disk; the+ * Media3 timeline carries just the current sequence.+ */+ lateinit var queue: PlayQueue+ private set++ /** Owns the AudioTrack the native sink writes into. */+ val audioOutput = AudioOutput()++ override fun createPlayer(host: PlaybackHost): Player {+ queue = PlayQueue()+ return LibrespotPlayer(+ host.context,+ host.looper,+ queue,+ audioOutput::setSpeedAndPitch,+ audioOutput::fadeOutThen,+ audioOutput::fadeIn,+ audioOutput::setPlaybackActive,+ )+ }++ private companion object {+ /** The Web API's own maximum page size for playlist tracks. */+ const val WEB_API_PAGE = 100+ }+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/LrcLib.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/LrcLib.ktnew file mode 100644index 0000000..df27aca--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/LrcLib.kt@@ -0,0 +1,120 @@+package dev.lelonio.square.backend.youtube++import dev.lelonio.square.data.LyricLine+import dev.lelonio.square.data.Lyrics+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request+import org.json.JSONObject++/**+ * Lyrics from LrcLib, for tracks YouTube has none for.+ *+ * YouTube Music does carry lyrics, but only for accounts with a Premium+ * subscription and only through a browse endpoint that answers nothing without+ * one. LrcLib is an open, unauthenticated database of synced lyrics built for+ * exactly this, so it is what this backend asks — and it means the lyrics work+ * whether or not anyone has signed in.+ *+ * A miss is the ordinary case for a lot of the catalogue, so everything here+ * answers null rather than raising.+ */+object LrcLib {++ private val http = OkHttpClient()++ /**+ * @param durationMs used to tell versions apart — a single, an album cut and+ * a live take share a title and an artist, and the length is what+ * distinguishes them. LrcLib matches it within a couple of seconds.+ */+ suspend fun lyrics(title: String, artist: String, durationMs: Long): Lyrics? =+ withContext(Dispatchers.IO) {+ val cleaned = title.cleanedTitle()+ val body = get(url(cleaned, artist, durationMs))+ // Retry without the duration before giving up: YouTube's own+ // duration includes any silence at the end of the upload, so an+ // exact-length match misses tracks LrcLib really does have.+ ?: get(url(cleaned, artist, durationMs = null))+ ?: return@withContext null++ val json = runCatching { JSONObject(body) }.getOrNull() ?: return@withContext null++ json.optString("syncedLyrics").takeIf { it.isNotBlank() }?.let { synced ->+ return@withContext parseLrc(synced)+ }+ json.optString("plainLyrics").takeIf { it.isNotBlank() }?.let { plain ->+ return@withContext Lyrics(+ lines = plain.lines()+ .filter { it.isNotBlank() }+ .map { LyricLine(startTimeMs = null, text = it.trim()) },+ synced = false,+ )+ }+ null+ }++ private fun url(title: String, artist: String, durationMs: Long?): String = buildString {+ append("https://lrclib.net/api/get?track_name=")+ append(java.net.URLEncoder.encode(title, "UTF-8"))+ append("&artist_name=")+ append(java.net.URLEncoder.encode(artist, "UTF-8"))+ if (durationMs != null && durationMs > 0) {+ append("&duration=").append(durationMs / 1000)+ }+ }++ /** Null on anything but a 200, which includes LrcLib's 404 for "no match". */+ private fun get(url: String): String? = runCatching {+ val request = Request.Builder()+ .url(url)+ // LrcLib asks clients to identify themselves.+ .header("User-Agent", USER_AGENT)+ .build()+ http.newCall(request).execute().use { response ->+ if (!response.isSuccessful) null else response.body?.string()+ }+ }.getOrNull()++ /**+ * Trims what YouTube titles carry and song titles do not.+ *+ * Uploads are named for a video — "(Official Video)", "[4K Remaster]",+ * "(Lyrics)" — and searching a lyrics database for any of that finds+ * nothing.+ */+ private fun String.cleanedTitle(): String =+ replace(NOISE, "").replace(WHITESPACE, " ").trim()++ private val NOISE = Regex(+ "\\((?:official|lyric|audio|video|visualizer|hd|4k|mv|m/v)[^)]*\\)" ++ "|\\[[^\\]]*(?:official|lyric|audio|video|remaster|hd|4k)[^\\]]*\\]",+ RegexOption.IGNORE_CASE,+ )+ private val WHITESPACE = Regex("\\s+")++ /**+ * `[mm:ss.xx] words` per line.+ *+ * Lines with no words are kept as timed blanks rather than dropped: they are+ * the instrumental gaps, and without them the view holds the previous line+ * highlighted through a stretch where nothing is being sung.+ */+ private fun parseLrc(raw: String): Lyrics? {+ val lines = raw.lines().mapNotNull { line ->+ val match = LRC_LINE.find(line) ?: return@mapNotNull null+ val (minutes, seconds, fraction, text) = match.destructured+ val startMs = minutes.toLong() * 60_000 ++ seconds.toLong() * 1_000 ++ // Two digits are hundredths, three are milliseconds.+ fraction.padEnd(3, '0').take(3).toLong()+ LyricLine(startTimeMs = startMs, text = text.trim())+ }+ return lines.takeIf { it.isNotEmpty() }?.let { Lyrics(it, synced = true) }+ }++ private val LRC_LINE = Regex("\\[(\\d{1,2}):(\\d{2})[.:](\\d{2,3})\\](.*)")++ private const val USER_AGENT = "Square (https://github.com/lelonio/square)"+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/NewPipeDownloader.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/NewPipeDownloader.ktnew file mode 100644index 0000000..1755163--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/NewPipeDownloader.kt@@ -0,0 +1,76 @@+package dev.lelonio.square.backend.youtube++import okhttp3.OkHttpClient+import okhttp3.RequestBody.Companion.toRequestBody+import org.schabi.newpipe.extractor.downloader.Downloader+import org.schabi.newpipe.extractor.downloader.Request+import org.schabi.newpipe.extractor.downloader.Response+import org.schabi.newpipe.extractor.exceptions.ReCaptchaException+import java.util.concurrent.TimeUnit++/**+ * The HTTP client NewPipeExtractor asks for.+ *+ * The extractor ships no networking of its own on purpose, so this is the one+ * piece that has to exist here. It is the app's own OkHttp rather than a second+ * client: connection pooling across the catalogue and the media requests is+ * most of what makes browsing feel immediate.+ */+class NewPipeDownloader(private val http: OkHttpClient) : Downloader() {++ override fun execute(request: Request): Response {+ val builder = okhttp3.Request.Builder()+ .method(+ request.httpMethod(),+ request.dataToSend()?.toRequestBody(),+ )+ .url(request.url())+ // YouTube serves a consent interstitial instead of content to+ // clients it thinks are in the EU and have not answered it. The+ // extractor expects the cookie to be set for it.+ .addHeader("User-Agent", USER_AGENT)++ request.headers().forEach { (name, values) ->+ builder.removeHeader(name)+ values.forEach { builder.addHeader(name, it) }+ }++ http.newCall(builder.build()).execute().use { response ->+ // 429 is YouTube asking for a captcha. Distinguished because it is+ // the one failure a retry cannot fix and the UI has to explain.+ if (response.code == HTTP_TOO_MANY_REQUESTS) {+ throw ReCaptchaException("reCaptcha challenge requested", request.url())+ }+ val body = response.body?.string()+ return Response(+ response.code,+ response.message,+ response.headers.toMultimap(),+ body,+ response.request.url.toString(),+ )+ }+ }++ companion object {+ private const val HTTP_TOO_MANY_REQUESTS = 429++ /**+ * A desktop browser's.+ *+ * InnerTube answers a mobile or unknown agent with a different, smaller+ * response shape than the extractor is written against.+ */+ private const val USER_AGENT =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " ++ "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"++ fun create(): NewPipeDownloader = NewPipeDownloader(+ OkHttpClient.Builder()+ .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .build(),+ )++ private const val READ_TIMEOUT_SECONDS = 30L+ }+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/Thumbnails.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/Thumbnails.ktnew file mode 100644index 0000000..546a82a--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/Thumbnails.kt@@ -0,0 +1,47 @@+package dev.lelonio.square.backend.youtube++/**+ * Asks Google's image host for a cover at a usable size.+ *+ * The URLs YouTube hands out carry the size in the path — `=w60-h60` and+ * similar — and what it hands out by default is a thumbnail meant for a list+ * row on a phone. Handed to a full-screen player it is upscaled, which is what+ * made every cover look soft.+ *+ * Rewriting the size is the whole fix: the same URL with `=w544-h544` comes+ * back sharp. Both hosts are matched because YouTube moved album art from+ * `lh3` to `yt3` and a pattern that only knows the old one silently does+ * nothing on the new.+ *+ * Adapted from Metrolist (GPL-3.0), which worked this out first.+ */+fun String.atSize(width: Int, height: Int = width): String {+ GOOGLE_USER_CONTENT.matchEntire(this)?.groupValues?.let {+ return "${substringBefore("=w")}=w$width-h$height-p-l90-rj"+ }+ // The other shape Google uses, for channel and artist pictures.+ if (GGPHT.matches(this)) return "$this-s$width"+ // Video thumbnails carry no size to rewrite: the size *is* the file name,+ // and the one YouTube hands out is `hqdefault` at 480x360. `sddefault` is+ // the largest one every upload is guaranteed to have — `maxresdefault`+ // exists only for videos uploaded above 720p and 404s for the rest.+ YTIMG.matchEntire(this)?.groupValues?.let { (_, id) ->+ return "https://i.ytimg.com/vi/$id/sddefault.jpg"+ }+ return this+}++private val GOOGLE_USER_CONTENT =+ Regex("https://(?:lh3|yt3)\\.googleusercontent\\.com/.*=w(\\d+)-h(\\d+).*")++private val GGPHT = Regex("https://yt3\\.ggpht\\.com/.*=s(\\d+)")++private val YTIMG = Regex("https://i\\.ytimg\\.com/vi/([^/]+)/.*")++/**+ * What a cover is asked for at, when it is going to fill a tile or a player.+ *+ * Sized for the player rather than the tiles: it is the same URL either way, and+ * the one place a soft cover shows is the full-screen one.+ */+const val COVER_SIZE = 720diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.ktnew file mode 100644index 0000000..37db256--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeAccount.kt@@ -0,0 +1,84 @@+package dev.lelonio.square.backend.youtube++import android.content.Context+import androidx.security.crypto.EncryptedSharedPreferences+import androidx.security.crypto.MasterKey+import com.metrolist.innertube.YouTube+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * The signed-in Google account, for the YouTube Music backend.+ *+ * There is no OAuth here, and that is not a shortcut: YouTube Music has no+ * public API and issues no tokens to third parties. What `music.youtube.com`+ * itself uses is a session cookie plus a `SAPISIDHASH` header derived from it,+ * so signing in means letting the user log into Google in a web view and+ * keeping the cookie it leaves behind — see [YouTubeLoginScreen].+ *+ * Encrypted at rest like the Spotify tokens are: this cookie is full access to+ * the user's Google account, which makes it the most sensitive thing this app+ * stores.+ */+class YouTubeAccount(context: Context) {++ private val prefs = EncryptedSharedPreferences.create(+ context,+ FILE_NAME,+ MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,+ )++ /** The display name of the signed-in account, or null when signed out. */+ private val _accountName = MutableStateFlow(prefs.getString(KEY_NAME, null))+ val accountName: StateFlow<String?> = _accountName.asStateFlow()++ val isSignedIn: Boolean get() = prefs.getString(KEY_COOKIE, null) != null++ init {+ // Before anything asks the module for a page: the cookie is what turns+ // its calls from "the anonymous catalogue" into "this account's".+ applyToInnerTube()+ }++ /**+ * Hands the stored session to the InnerTube client.+ *+ * The three values travel together and are only meaningful together:+ * `visitorData` and `dataSyncId` identify which of a Google account's+ * several YouTube channels is being asked about, and a cookie without them+ * reads the wrong one.+ */+ private fun applyToInnerTube() {+ YouTube.cookie = prefs.getString(KEY_COOKIE, null)+ YouTube.visitorData = prefs.getString(KEY_VISITOR_DATA, null).orEmpty()+ YouTube.dataSyncId = prefs.getString(KEY_DATA_SYNC_ID, null).orEmpty()+ }++ fun save(cookie: String, visitorData: String, dataSyncId: String, name: String) {+ prefs.edit()+ .putString(KEY_COOKIE, cookie)+ .putString(KEY_VISITOR_DATA, visitorData)+ .putString(KEY_DATA_SYNC_ID, dataSyncId)+ .putString(KEY_NAME, name)+ .apply()+ _accountName.value = name+ applyToInnerTube()+ }++ fun signOut() {+ prefs.edit().clear().apply()+ _accountName.value = null+ applyToInnerTube()+ }++ private companion object {+ const val FILE_NAME = "square_youtube_account"+ const val KEY_COOKIE = "cookie"+ const val KEY_VISITOR_DATA = "visitor_data"+ const val KEY_DATA_SYNC_ID = "data_sync_id"+ const val KEY_NAME = "name"+ }+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.ktnew file mode 100644index 0000000..bc3692a--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt@@ -0,0 +1,286 @@+package dev.lelonio.square.backend.youtube++import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import dev.lelonio.square.backend.BackendAuthState+import dev.lelonio.square.backend.BackendId+import dev.lelonio.square.backend.MusicBackend+import dev.lelonio.square.backend.PlaybackHost+import dev.lelonio.square.backend.SearchLabels+import dev.lelonio.square.data.CatalogPlaylist+import dev.lelonio.square.data.CatalogTrack+import dev.lelonio.square.data.SearchItem+import dev.lelonio.square.data.SearchResults+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.withContext+import com.metrolist.innertube.YouTube+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import dev.lelonio.square.backend.HomeRow+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope++/**+ * YouTube Music, over two clients rather than one.+ *+ * The split is by what needs an account, not by preference. Search, trending+ * and stream URLs are public, and NewPipeExtractor reads them without any+ * credentials — which is what lets the app work before anyone has signed in,+ * and for anyone who never does. The library is the account's own, so+ * [playlists] goes through the vendored InnerTube module with the session+ * cookie attached; see [YouTubeAccount].+ *+ * The other half of this backend is [YouTubeStreamResolver], which turns one of+ * these URIs into a URL ExoPlayer can read.+ */+@UnstableApi+class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {++ override val id = BackendId.YOUTUBE_MUSIC++ private val _authState = MutableStateFlow<BackendAuthState>(+ account.accountName.value?.let(BackendAuthState::LoggedIn) ?: ANONYMOUS,+ )+ override val authState: StateFlow<BackendAuthState> = _authState.asStateFlow()++ /**+ * Always. Signing in adds the account's own library on top; it is not what+ * makes the backend usable, and search and playback work without it.+ */+ override val isReady = true++ override suspend fun refreshAuth() {+ _authState.value = account.accountName.value?.let(BackendAuthState::LoggedIn) ?: ANONYMOUS+ }++ override suspend fun logOut() {+ account.signOut()+ _authState.value = ANONYMOUS+ }++ /**+ * Songs, albums, artists and playlists, in four calls.+ *+ * InnerTube filters a search to one kind at a time, so the four rows the+ * UI shows are four requests. Run together rather than one after another:+ * serially this is the slowest thing on the screen, and they do not depend+ * on each other.+ */+ override suspend fun search(query: String, labels: SearchLabels): SearchResults =+ withContext(Dispatchers.IO) {+ val trimmed = query.trim()++ coroutineScope {+ val songs = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_SONG) }+ val albums = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_ALBUM) }+ val artists = async { searchItems(trimmed, YouTube.SearchFilter.FILTER_ARTIST) }+ val playlists = async {+ searchItems(trimmed, YouTube.SearchFilter.FILTER_COMMUNITY_PLAYLIST)+ }++ SearchResults(+ tracks = songs.await().filterIsInstance<SongItem>().map(::toCatalogTrack),+ albums = albums.await().filterIsInstance<AlbumItem>().map { album ->+ SearchItem(+ uri = "$PLAYLIST_PREFIX${album.playlistId}",+ title = album.title,+ subtitle = album.artists?.joinToString(", ") { it.name }+ ?.ifBlank { labels.album } ?: labels.album,+ artworkUrl = album.thumbnail.atSize(COVER_SIZE),+ )+ },+ artists = artists.await().filterIsInstance<ArtistItem>().map { artist ->+ SearchItem(+ uri = "$ARTIST_PREFIX${artist.id}",+ title = artist.title,+ subtitle = labels.artist,+ artworkUrl = artist.thumbnail?.atSize(COVER_SIZE),+ )+ },+ playlists = playlists.await().filterIsInstance<PlaylistItem>().map { playlist ->+ SearchItem(+ uri = "$PLAYLIST_PREFIX${playlist.id}",+ title = playlist.title,+ subtitle = labels.playlist,+ artworkUrl = playlist.thumbnail?.atSize(COVER_SIZE),+ )+ },+ )+ }+ }++ /** One filtered search, with a failure treated as "nothing of this kind". */+ private suspend fun searchItems(query: String, filter: YouTube.SearchFilter): List<YTItem> =+ YouTube.search(query, filter)+ .map { it.items }+ .getOrDefault(emptyList())++ /**+ * The account's own playlists — empty until someone has signed in.+ *+ * This is the one thing the anonymous path genuinely cannot do, and the+ * reason the InnerTube module is vendored at all: it goes out with the+ * session cookie attached, so YouTube answers with *this* account's library+ * rather than the public catalogue.+ */+ override suspend fun playlists(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {+ if (!account.isSignedIn) return@withContext emptyList()++ YouTube.library(LIKED_PLAYLISTS_BROWSE_ID)+ .getOrThrow()+ .items+ .filterIsInstance<PlaylistItem>()+ .map { item ->+ CatalogPlaylist(+ uri = "$PLAYLIST_PREFIX${item.id}",+ name = item.title,+ artworkUrl = item.thumbnail?.atSize(COVER_SIZE),+ )+ }+ }++ /**+ * YouTube Music's own home page, shelf by shelf.+ *+ * `FEmusic_home` is the page the app itself opens on, and it is the only+ * way to get what YouTube actually wants to show: signed in it is built+ * around what the account listens to, signed out it is charts and moods.+ * Either way the shelves arrive already titled, so nothing here has to+ * invent a name for them.+ */+ override suspend fun homeRows(): List<HomeRow> = withContext(Dispatchers.IO) {+ YouTube.home()+ .getOrThrow()+ .sections+ .map { section ->+ val songs = section.items.filterIsInstance<SongItem>()+ HomeRow(+ title = section.title,+ tracks = songs.map(::toCatalogTrack),+ // Everything that is not a song opens something: an album,+ // a playlist, an artist. They travel as one list because+ // the row draws them identically.+ items = section.items.filterNot { it is SongItem }+ .mapNotNull(::toCatalogPlaylist),+ )+ }+ .filterNot { it.isEmpty }+ }++ private fun toCatalogPlaylist(item: YTItem): CatalogPlaylist? {+ val uri = when (item) {+ is AlbumItem -> "$PLAYLIST_PREFIX${item.playlistId}"+ is PlaylistItem -> "$PLAYLIST_PREFIX${item.id}"+ is ArtistItem -> "$ARTIST_PREFIX${item.id}"+ else -> return null+ }+ return CatalogPlaylist(+ uri = uri,+ name = item.title,+ artworkUrl = item.thumbnail?.atSize(COVER_SIZE),+ )+ }++ private fun toCatalogTrack(item: SongItem) = CatalogTrack(+ uri = "$TRACK_PREFIX${item.id}",+ name = item.title,+ artist = item.artists.joinToString(", ") { it.name },+ album = item.album?.name.orEmpty(),+ durationMs = item.duration?.takeIf { it > 0 }?.times(1000L) ?: 0L,+ explicit = item.explicit,+ artworkUrl = item.thumbnail.atSize(COVER_SIZE),+ )++ override suspend fun tracksOf(uri: String): List<CatalogTrack> = withContext(Dispatchers.IO) {+ val id = uri.substringAfterLast(':')+ when {+ uri.startsWith(TRACK_PREFIX) -> emptyList()++ // An artist has no track list of its own, so what "open an artist"+ // means here is the same as everywhere else: their best-known+ // songs.+ uri.startsWith(ARTIST_PREFIX) ->+ YouTube.artist(id).getOrThrow()+ .sections+ .flatMap { it.items }+ .filterIsInstance<SongItem>()+ .map(::toCatalogTrack)++ else -> YouTube.playlist(id).getOrThrow()+ .songs+ .map(::toCatalogTrack)+ }+ }++ override suspend fun lyrics(+ uri: String,+ title: String,+ artist: String,+ durationMs: Long,+ ) = LrcLib.lyrics(title, artist, durationMs)++ override val canEditPlaylists: Boolean+ get() = account.isSignedIn++ override suspend fun createPlaylist(name: String): CatalogPlaylist =+ withContext(Dispatchers.IO) {+ // Blocking upstream, deliberately not wrapped in runCatching there:+ // a failure has to reach the caller, which is a screen waiting to+ // open what it just made.+ val id = YouTube.createPlaylist(name)+ CatalogPlaylist(uri = "$PLAYLIST_PREFIX$id", name = name, artworkUrl = null)+ }++ override suspend fun renamePlaylist(uri: String, name: String) {+ withContext(Dispatchers.IO) {+ YouTube.renamePlaylist(uri.substringAfterLast(':'), name).getOrThrow()+ }+ }++ override suspend fun deletePlaylist(uri: String) {+ withContext(Dispatchers.IO) {+ YouTube.deletePlaylist(uri.substringAfterLast(':')).getOrThrow()+ }+ }++ override fun owns(uri: String) = uri.startsWith(URI_SCHEME)++ override fun createPlayer(host: PlaybackHost): Player =+ YouTubePlayerFactory.create(host)++ companion object {+ const val URI_SCHEME = "ytmusic:"+ const val TRACK_PREFIX = "ytmusic:track:"+ const val PLAYLIST_PREFIX = "ytmusic:playlist:"+ const val ARTIST_PREFIX = "ytmusic:artist:"++ /** YouTube Music's own browse id for the account's playlist library. */+ private const val LIKED_PLAYLISTS_BROWSE_ID = "FEmusic_liked_playlists"++ /** The `list=` id of a playlist URL. */+ private fun playlistIdOf(url: String?): String? =+ runCatching { android.net.Uri.parse(url ?: return null) }+ .getOrNull()?.getQueryParameter("list")++ /** The id half of a `ytmusic:track:` URI, for the stream resolver. */+ fun videoIdOfUri(uri: String): String = uri.substringAfterLast(':')++ private const val PLAYLIST_URL = "https://www.youtube.com/playlist?list="++ private val ANONYMOUS = BackendAuthState.LoggedIn("YouTube Music")++ /** `https://www.youtube.com/watch?v=<id>` and its short forms. */+ private fun videoIdOf(url: String?): String? {+ val parsed = runCatching { android.net.Uri.parse(url ?: return null) }.getOrNull()+ ?: return null+ return parsed.getQueryParameter("v")+ ?: parsed.lastPathSegment?.takeIf { parsed.host?.contains("youtu.be") == true }+ }+ }+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.ktnew file mode 100644index 0000000..5614b96--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeLoginScreen.kt@@ -0,0 +1,157 @@+package dev.lelonio.square.backend.youtube++import android.annotation.SuppressLint+import android.webkit.CookieManager+import android.webkit.JavascriptInterface+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.viewinterop.AndroidView+import com.metrolist.innertube.YouTube+import kotlinx.coroutines.launch++/**+ * Signing into Google, in a web view.+ *+ * Uncomfortable and unavoidable in equal measure. YouTube Music has no public+ * API and hands out no tokens, so the only session it recognises is the one its+ * own web player uses: a Google cookie, plus the `VISITOR_DATA` and+ * `DATASYNC_ID` the page keeps in `window.yt.config_`. There is no OAuth screen+ * to send the user to instead.+ *+ * The web view therefore loads Google's real sign-in page and nothing else —+ * the credentials are typed into Google's own form, and this app never sees+ * them, only the cookie that results. That is the same arrangement every+ * third-party YouTube Music client uses, and it is worth being plain that it+ * still means holding a Google session cookie on the device.+ *+ * @param onDone called once the session has been captured, or on going back.+ */+@SuppressLint("SetJavaScriptEnabled")+@Composable+fun YouTubeLoginScreen(account: YouTubeAccount, onDone: () -> Unit) {+ val scope = rememberCoroutineScope()+ var completing by remember { mutableStateOf(false) }+ var webView: WebView? = null++ // Read out of the page rather than out of the cookie: they are not cookie+ // values at all, they live in the page's own config object, and without+ // them a Google account with several YouTube channels resolves to the+ // wrong one.+ var visitorData by remember { mutableStateOf("") }+ var dataSyncId by remember { mutableStateOf("") }++ fun complete() {+ if (completing) return+ val cookie = CookieManager.getInstance().getCookie(MUSIC_URL).orEmpty()+ // Backing out before signing in is an ordinary outcome, not a failure.+ if (cookie.isBlank()) {+ onDone()+ return+ }++ completing = true+ val capturedVisitorData = visitorData+ val capturedDataSyncId = dataSyncId++ scope.launch {+ YouTube.cookie = cookie+ YouTube.visitorData = capturedVisitorData+ YouTube.dataSyncId = capturedDataSyncId++ // The session is only worth keeping if it can actually read the+ // account. Asking now turns a cookie that will never work into a+ // login that visibly did not happen, rather than a library that is+ // mysteriously empty later.+ YouTube.accountInfo()+ .onSuccess { info ->+ webView?.apply {+ stopLoading()+ clearHistory()+ }+ account.save(+ cookie = cookie,+ visitorData = capturedVisitorData,+ dataSyncId = capturedDataSyncId,+ name = info.name,+ )+ onDone()+ }+ .onFailure { error ->+ android.util.Log.e(TAG, "youtube login failed: $error", error)+ completing = false+ onDone()+ }+ }+ }++ Box(Modifier.fillMaxSize()) {+ AndroidView(+ modifier = Modifier.fillMaxSize(),+ factory = { context ->+ WebView(context).apply {+ webViewClient = object : WebViewClient() {+ override fun onPageFinished(view: WebView, url: String?) {+ view.loadUrl(+ "javascript:Square.visitorData(window.yt.config_.VISITOR_DATA)",+ )+ view.loadUrl(+ "javascript:Square.dataSyncId(window.yt.config_.DATASYNC_ID)",+ )++ // Landing back on music.youtube.com with a cookie is+ // what "signed in" looks like: Google's flow can take+ // any number of pages — password, 2FA, account+ // picker — and this is the one state that means it+ // finished.+ val signedIn = url?.contains("music.youtube.com") == true &&+ CookieManager.getInstance().getCookie(MUSIC_URL)+ .orEmpty().isNotBlank()+ if (signedIn && !completing) complete()+ }+ }+ settings.javaScriptEnabled = true+ addJavascriptInterface(+ object {+ @JavascriptInterface+ fun visitorData(value: String?) {+ if (value != null) visitorData = value+ }++ @JavascriptInterface+ fun dataSyncId(value: String?) {+ // Two ids separated by `||`; the first is this+ // account's.+ if (value != null) dataSyncId = value.substringBefore("||")+ }+ },+ "Square",+ )+ webView = this+ loadUrl(SIGN_IN_URL)+ }+ },+ )+ }++ BackHandler {+ val view = webView+ // Google's flow is several pages deep, so back should walk it rather+ // than abandoning a sign-in halfway through.+ if (view?.canGoBack() == true) view.goBack() else complete()+ }+}++private const val TAG = "SquareYouTubeLogin"+private const val MUSIC_URL = "https://music.youtube.com"+private const val SIGN_IN_URL =+ "https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fmusic.youtube.com"diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.ktnew file mode 100644index 0000000..8f3c0fc--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt@@ -0,0 +1,182 @@+package dev.lelonio.square.backend.youtube++import androidx.media3.common.Player+import androidx.media3.common.util.UnstableApi+import androidx.media3.datasource.DataSpec+import androidx.media3.datasource.DefaultHttpDataSource+import androidx.media3.datasource.ResolvingDataSource+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.source.DefaultMediaSourceFactory+import dev.lelonio.square.backend.PlaybackHost+import org.schabi.newpipe.extractor.NewPipe+import org.schabi.newpipe.extractor.ServiceList+import org.schabi.newpipe.extractor.localization.Localization+import org.schabi.newpipe.extractor.stream.StreamInfo++/**+ * Builds the ExoPlayer the YouTube Music backend plays through.+ *+ * A real ExoPlayer, unlike the Spotify side: there is no engine to hand audio+ * to, the tracks are ordinary HTTPS files, and the queue, gapless transitions+ * and buffering are all things ExoPlayer already does properly.+ */+@UnstableApi+object YouTubePlayerFactory {++ fun create(host: PlaybackHost): Player = ExoPlayer.Builder(host.context, renderers(host))+ .setMediaSourceFactory(+ DefaultMediaSourceFactory(+ ResolvingDataSource.Factory(+ DefaultHttpDataSource.Factory(),+ YouTubeStreamResolver(),+ ),+ ),+ )+ .setHandleAudioBecomingNoisy(true)+ // Ducks and pauses for whatever else wants the speaker. The Spotify+ // path gets this from its own output; ExoPlayer will not ask for focus+ // at all unless it is told to handle it.+ .setAudioAttributes(+ androidx.media3.common.AudioAttributes.Builder()+ .setUsage(androidx.media3.common.C.USAGE_MEDIA)+ .setContentType(androidx.media3.common.C.AUDIO_CONTENT_TYPE_MUSIC)+ .build(),+ /* handleAudioFocus = */ true,+ )+ .setLooper(host.looper)+ .build()+ .apply { addAnalyticsListener(Diagnostics) }++ /** Temporary: chasing a stall where the position stops with the sink idle. */+ private object Diagnostics : androidx.media3.exoplayer.analytics.AnalyticsListener {+ override fun onAudioUnderrun(+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,+ bufferSize: Int,+ bufferSizeMs: Long,+ elapsedSinceLastFeedMs: Long,+ ) {+ android.util.Log.w(TAG, "underrun size=$bufferSize sinceFeed=${elapsedSinceLastFeedMs}ms")+ }++ override fun onPlaybackStateChanged(+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,+ state: Int,+ ) {+ android.util.Log.w(TAG, "state=$state pos=${eventTime.currentPlaybackPositionMs}")+ }++ override fun onPlayWhenReadyChanged(+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,+ playWhenReady: Boolean,+ reason: Int,+ ) {+ android.util.Log.w(TAG, "playWhenReady=$playWhenReady reason=$reason")+ }++ override fun onPlaybackParametersChanged(+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,+ parameters: androidx.media3.common.PlaybackParameters,+ ) {+ android.util.Log.w(TAG, "params speed=${parameters.speed} pitch=${parameters.pitch}")+ }++ override fun onAudioSinkError(+ eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime,+ audioSinkError: Exception,+ ) {+ android.util.Log.e(TAG, "sink error", audioSinkError)+ }++ private const val TAG = "SquareYT"+ }++ /**+ * Renderers whose audio sink resamples in software.+ *+ * ExoPlayer would otherwise hand a non-unity speed straight to `AudioTrack`,+ * and on this hardware that track stops consuming: the session stays+ * PLAYING and its buffer keeps filling while the position stands still, so+ * the sound goes and the progress bar jumps back to where it stalled.+ * Sonic — the same resampler Media3 uses when the platform cannot oblige —+ * has no such trouble, and it is what the Spotify path already effectively+ * does through its own output.+ */+ private fun renderers(host: PlaybackHost) =+ object : androidx.media3.exoplayer.DefaultRenderersFactory(host.context) {+ override fun buildAudioSink(+ context: android.content.Context,+ enableFloatOutput: Boolean,+ enableAudioTrackPlaybackParams: Boolean,+ ) = androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)+ .setEnableFloatOutput(enableFloatOutput)+ .setEnableAudioTrackPlaybackParams(false)+ .build()+ }+}++/**+ * Turns a `ytmusic:track:` URI into the URL the audio really lives at.+ *+ * Resolved at load time rather than when the queue is built, and this is the+ * whole reason for the indirection: a YouTube stream URL is signed and expires+ * within hours, so a queue holding resolved URLs would be a queue that stops+ * working while it sits there. The URI keeps its meaning; only the resolution+ * is perishable.+ *+ * Runs on ExoPlayer's loading thread, so blocking here is correct.+ */+@UnstableApi+private class YouTubeStreamResolver : ResolvingDataSource.Resolver {++ override fun resolveDataSpec(dataSpec: DataSpec): DataSpec {+ val uri = dataSpec.uri.toString()+ if (!uri.startsWith(YouTubeBackend.TRACK_PREFIX)) return dataSpec++ // NewPipe holds its downloader in a static, and every extractor reads it+ // at construction: without this the first resolve dies on "downloader is+ // null". Done here rather than at startup so a session that never plays+ // a YouTube track never builds one.+ ensureNewPipe()++ val videoId = YouTubeBackend.videoIdOfUri(uri)+ val info = StreamInfo.getInfo(ServiceList.YouTube, "$WATCH_URL$videoId")++ // With the video showing, one of YouTube's muxed streams: those are the+ // only ones carrying picture and sound in a single file, and a single+ // file is what a progressive source can play. They top out at 720p,+ // which is the price of not building a DASH manifest here.+ val url = if (YouTubeVideoMode.enabled.value) {+ info.videoStreams+ .filter { !it.content.isNullOrEmpty() }+ .maxByOrNull { it.height }+ ?.content+ } else {+ null+ }+ // Audio-only otherwise, best bitrate: a muxed stream would carry a video+ // track nobody is going to look at, over a connection that is often the+ // scarce resource. Also the fallback when a track has no muxed stream.+ ?: info.audioStreams+ .filter { !it.content.isNullOrEmpty() }+ .maxByOrNull { it.averageBitrate }+ ?.content+ ?: error("nessuna traccia audio per $videoId")++ return dataSpec.withUri(android.net.Uri.parse(url))+ }++ private companion object {+ const val WATCH_URL = "https://www.youtube.com/watch?v="++ @Volatile+ private var initialised = false++ /** Idempotent: several tracks resolve on the same thread pool. */+ @Synchronized+ fun ensureNewPipe() {+ if (initialised) return+ NewPipe.init(NewPipeDownloader.create(), Localization.DEFAULT)+ initialised = true+ }+ }+}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.ktnew file mode 100644index 0000000..77719c0--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeVideoMode.kt@@ -0,0 +1,62 @@+package dev.lelonio.square.backend.youtube++import androidx.media3.common.Player+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/**+ * Whether YouTube tracks play as video rather than as sound alone.+ *+ * Process-wide, like [dev.lelonio.square.playback.AudioEffects], and for the+ * same reason: the thing that reads it is the stream resolver, which runs inside+ * the playback service on ExoPlayer's loading thread, while the thing that sets+ * it is a button in the player. There is no session command that carries it.+ *+ * Deliberately not persisted. Video is something you turn on for one song —+ * reopening the app into it, on data, is not what anyone meant.+ */+object YouTubeVideoMode {++ private val _enabled = MutableStateFlow(false)+ val enabled: StateFlow<Boolean> = _enabled.asStateFlow()++ /**+ * Flips the mode and reloads the current track in the new one.+ *+ * The reload is the point: the stream URL is chosen when the source opens,+ * so a track already playing keeps whatever it was given until something+ * makes it open again. Stopping and preparing does that while keeping the+ * queue, and the position is put back by hand because stopping loses it.+ */+ fun toggle(player: Player) {+ _enabled.value = !_enabled.value+ val index = player.currentMediaItemIndex+ val position = player.currentPosition+ val wasPlaying = player.isPlaying+ player.stop()+ player.seekTo(index, position)+ player.prepare()+ if (wasPlaying) player.play()+ }++ private val _pictureInPicture = MutableStateFlow(false)++ /**+ * Whether the app is currently a floating window.+ *+ * The player screen draws only the picture while it is: a window that small+ * has room for the video and nothing else, and the transport controls are+ * the system's to draw there.+ */+ val pictureInPicture: StateFlow<Boolean> = _pictureInPicture.asStateFlow()++ fun setPictureInPicture(active: Boolean) {+ _pictureInPicture.value = active+ }++ /** Back to sound alone — for when the source or the track changes under it. */+ fun reset() {+ _enabled.value = false+ }+}diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.ktindex b58fb66..6c69327 100644--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt@@ -44,9 +44,51 @@ class PreferencesStore(context: Context) {prefs.edit().putBoolean(KEY_ONBOARDED, value).apply()}+ /**+ * Whether the player was open when the app was last left.+ *+ * Read straight rather than as a flow: the answer decides what the *first*+ * composed frame is, so it has to be available before anything is drawn. A+ * value that arrives a moment later is what produced the flash of the home+ * page this replaced.+ */+ fun playerWasOpen(): Boolean = prefs.getBoolean(KEY_PLAYER_OPEN, false)++ fun setPlayerOpen(value: Boolean) {+ prefs.edit().putBoolean(KEY_PLAYER_OPEN, value).apply()+ }++ private val _backend = MutableStateFlow(+ runCatching { dev.lelonio.square.backend.BackendId.valueOf(prefs.getString(KEY_BACKEND, null) ?: "") }+ .getOrDefault(dev.lelonio.square.backend.BackendId.SPOTIFY),+ )++ /** Which [dev.lelonio.square.backend.MusicBackend] the app plays through. */+ val backend: StateFlow<dev.lelonio.square.backend.BackendId> = _backend.asStateFlow()++ fun setBackend(value: dev.lelonio.square.backend.BackendId) {+ _backend.value = value+ _backendChosen.value = true+ prefs.edit().putString(KEY_BACKEND, value.name).apply()+ }++ private val _backendChosen = MutableStateFlow(prefs.contains(KEY_BACKEND))++ /**+ * Whether the user has ever picked a source.+ *+ * Separate from [backend] having a value: that one defaults to Spotify so+ * the rest of the app never has to handle "none", while this stays false+ * until the choice was actually made. It is what puts the picker in front+ * of a fresh install — and only once.+ */+ val backendChosen: StateFlow<Boolean> = _backendChosen.asStateFlow()+private companion object {const val FILE_NAME = "square_preferences"const val KEY_TRACK_SORT = "track_sort"const val KEY_ONBOARDED = "onboarded"+ const val KEY_PLAYER_OPEN = "player_open"+ const val KEY_BACKEND = "backend"}}diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.ktindex 1621d31..79ea842 100644--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt@@ -3,6 +3,7 @@ package dev.lelonio.square.dataimport kotlinx.serialization.SerialNameimport kotlinx.serialization.Serializableimport retrofit2.http.Body+import retrofit2.http.DELETEimport retrofit2.http.GETimport retrofit2.http.HTTPimport retrofit2.http.POST@@ -178,6 +179,35 @@ interface SpotifyApi {@Body request: RemoveTracksRequestDto,)+ /**+ * Creates a playlist owned by the signed-in account.+ *+ * Private by default: a playlist made from a phone in the middle of+ * listening is a working list, not a publication.+ */+ @POST("v1/users/{userId}/playlists")+ suspend fun createPlaylist(+ @Path("userId") userId: String,+ @Body request: PlaylistDetailsDto,+ ): PlaylistDto++ /** Renames one; the same endpoint changes description and visibility. */+ @PUT("v1/playlists/{id}")+ suspend fun updatePlaylistDetails(+ @Path("id") playlistId: String,+ @Body request: PlaylistDetailsDto,+ )++ /**+ * Removes a playlist from the account's library.+ *+ * Unfollowing, because that is all Spotify offers: playlists are never+ * really deleted, and for the owner unfollowing is exactly what the app's+ * own "delete" does.+ */+ @DELETE("v1/playlists/{id}/followers")+ suspend fun unfollowPlaylist(@Path("id") playlistId: String)+@GET("v1/search")suspend fun search(@Query("q") query: String,@@ -189,6 +219,13 @@ interface SpotifyApi {@Serializabledata class AddTracksRequestDto(val uris: List<String>)+/** What a playlist is created or renamed with. */+@Serializable+data class PlaylistDetailsDto(+ val name: String,+ @SerialName("public") val isPublic: Boolean = false,+)+@Serializabledata class RemoveTracksRequestDto(val tracks: List<TrackUriDto>)diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.ktindex 1f99815..d4a66fe 100644--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt@@ -39,33 +39,45 @@ class PlaybackService : MediaLibraryService() {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)private lateinit var tokens: TokenStore- private lateinit var queue: PlayQueue- private lateinit var player: LibrespotPlayerprivate var session: MediaLibrarySession? = nullprivate var engineStarted = false- /** Owns the AudioTrack the native sink writes into. */- private val audioOutput = AudioOutput()+ private lateinit var container: dev.lelonio.square.SquareApplication++ /** Whatever the active backend plays through. */+ private lateinit var player: androidx.media3.common.Player++ /**+ * The same player, when the active backend is Spotify — null otherwise.+ *+ * Everything below that reads this is genuinely Spotify's and has no+ * meaning for a backend with no native engine behind it: the saved queue's+ * shuffle order, the bitrate restart, the access-point login.+ */+ private var librespot: LibrespotPlayer? = null++ private val queue: PlayQueue? get() = librespot?.let { container.spotifyBackend.queue }++ /** Owns the AudioTrack the native sink writes into; Spotify's alone. */+ private val audioOutput get() = container.spotifyBackend.audioOutputprivate lateinit var playbackStore: PlaybackStoreprivate lateinit var quality: dev.lelonio.square.data.QualityStoreprivate var saveJob: Job? = null+ private val playbackHost = object : dev.lelonio.square.backend.PlaybackHost {+ override val context get() = this@PlaybackService+ override val looper get() = mainLooper+ }+override fun onCreate() {super.onCreate()tokens = TokenStore(this)playbackStore = PlaybackStore(this)- quality = (application as dev.lelonio.square.SquareApplication).quality- queue = PlayQueue()- player = LibrespotPlayer(- this,- mainLooper,- queue,- audioOutput::setSpeedAndPitch,- audioOutput::fadeOutThen,- audioOutput::fadeIn,- audioOutput::setPlaybackActive,- )+ container = application as dev.lelonio.square.SquareApplication+ quality = container.quality++ player = buildPlayer(container.preferences.backend.value)session = MediaLibrarySession.Builder(this, player, MediaBrowseTree(this, scope))// Without this the notification is inert to a tap: Media3 has no way// to know which activity owns the session. `SINGLE_TOP` so an app@@ -100,21 +112,6 @@ class PlaybackService : MediaLibraryService() {)AudioEffects.load(this)- // Applied straight to the output rather than waiting for the UI: the- // service can be running with no activity attached at all.- audioOutput.setSpeedAndPitch(AudioEffects.speed.value, AudioEffects.pitch.value)- player.restorePlaybackParameters(AudioEffects.speed.value, AudioEffects.pitch.value)-- NativeBridge.initContext(this)- // Before connectEngine: the sink is built as soon as playback starts and- // has nowhere to write without it.- NativeBridge.setAudioOutput(audioOutput)-- // Reverb is not part of the Player interface, so it arrives here rather- // than through the media session.- scope.launch {- AudioEffects.reverb.collect(audioOutput::setReverbAmount)- }// The bitrate is fixed when the player is built, so a change means a new// engine. Watched here rather than acted on from the settings screen:@@ -124,7 +121,111 @@ class PlaybackService : MediaLibraryService() {quality.quality.drop(1).collect { restartForQuality() }}- connectEngine()+ // Same reasoning for the source itself: swapping backends is swapping+ // the player under a live session, which only the service can do.+ scope.launch {+ container.preferences.backend.drop(1).collect(::switchBackend)+ }++ startSpotifyEngineIfActive()+ }++ /**+ * Builds the player for [backendId] and wires up whatever is specific to it.+ *+ * The Spotify half is everything the native engine needs: the sink it+ * writes into, the effects chain applied to that sink, and the JNI context.+ * The YouTube half needs none of it — ExoPlayer owns its own output — so+ * this is the one place the two genuinely differ.+ */+ private fun buildPlayer(+ backendId: dev.lelonio.square.backend.BackendId,+ ): androidx.media3.common.Player = when (backendId) {+ dev.lelonio.square.backend.BackendId.SPOTIFY -> {+ val built = container.spotifyBackend.createPlayer(playbackHost) as LibrespotPlayer+ librespot = built++ // Applied straight to the output rather than waiting for the UI: the+ // service can be running with no activity attached at all.+ audioOutput.setSpeedAndPitch(AudioEffects.speed.value, AudioEffects.pitch.value)+ built.restorePlaybackParameters(AudioEffects.speed.value, AudioEffects.pitch.value)++ NativeBridge.initContext(this)+ // Before connectEngine: the sink is built as soon as playback starts+ // and has nowhere to write without it.+ NativeBridge.setAudioOutput(audioOutput)++ // Reverb is not part of the Player interface, so it arrives here+ // rather than through the media session.+ scope.launch {+ AudioEffects.reverb.collect(audioOutput::setReverbAmount)+ }+ built+ }++ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC -> {+ librespot = null+ container.youtubeBackend.createPlayer(playbackHost).also { built ->+ built.playbackParameters = androidx.media3.common.PlaybackParameters(+ AudioEffects.speed.value,+ AudioEffects.pitch.value,+ )+ }+ }+ }++ /**+ * Swaps the player under the running session.+ *+ * The session itself is kept: rebuilding it would drop the notification and+ * every controller bound to it, and the media session API exists precisely+ * so the player behind it can be replaced.+ */+ private fun switchBackend(backendId: dev.lelonio.square.backend.BackendId) = scope.launch {+ runCatching { savePlayback() }+ saveJob?.cancel()++ if (librespot != null) {+ // Off the main thread, and this is why the switch is a coroutine at+ // all: shutting the native engine down means stopping its threads+ // and closing its session, which took long enough to hang the input+ // queue — the app was reported as not responding, and the animation+ // meant to cover the switch never got a frame to draw in.+ runCatching { withContext(Dispatchers.IO) { NativeBridge.shutdown() } }+ engineStarted = false+ }+ // Emptied before it goes: the session keeps reporting whatever the old+ // player had loaded until something replaces it, and the new source's+ // queue may legitimately be empty — which would leave the previous+ // source's track sitting in the player with the new source's controls+ // around it.+ runCatching {+ player.stop()+ player.clearMediaItems()+ }+ runCatching { player.release() }+ // Video belongs to the source that was playing it.+ dev.lelonio.square.backend.youtube.YouTubeVideoMode.reset()++ player = buildPlayer(backendId)+ session?.player = player+ startSpotifyEngineIfActive()+ }++ /**+ * Starts whatever the active backend needs before it can play.+ *+ * For Spotify that is the engine, and the queue is put back once it has+ * connected — it is the engine that holds it. A backend playing through a+ * plain player has nothing to wait for, so its queue goes back now.+ */+ private fun startSpotifyEngineIfActive() {+ if (librespot != null) {+ connectEngine()+ } else {+ restoreTimeline(container.preferences.backend.value)+ observeForSaving()+ }}/**@@ -136,12 +237,13 @@ class PlaybackService : MediaLibraryService() {* first and put back after, which is the same path a cold start takes.*/private fun restartForQuality() {+ val engine = librespot ?: returnval wasPlaying = player.playWhenReadyrunCatching { savePlayback() }runCatching { NativeBridge.shutdown() }engineStarted = false- player.clearForRestart()+ engine.clearForRestart()scope.launch {connectEngine().join()@@ -173,6 +275,9 @@ class PlaybackService : MediaLibraryService() {// side rejects a second start, and that error would look like a login// failure and clear a perfectly good session.if (engineStarted || !tokens.isLoggedIn) return@launch+ // Nothing to authenticate against while another backend is playing, and+ // starting the engine would take the audio device out from under it.+ val engine = librespot ?: return@launchengineStarted = truerunCatching {@@ -198,7 +303,7 @@ class PlaybackService : MediaLibraryService() {// URL, so the tiles came back in English.language = appLanguage(),bitrateKbps = quality.bitrateKbps(),- listener = player,+ listener = engine,)}}.onFailure { error ->@@ -235,12 +340,17 @@ class PlaybackService : MediaLibraryService() {* that would be worse than not restoring at all.*/private fun restoreQueue() {+ val engine = librespot ?: returnif (player.mediaItemCount > 0) returnval saved = playbackStore.load() ?: return+ // Spotify's own queue only. The store holds whichever source was last+ // playing, and handing librespot a queue of `ytmusic:` URIs would fill+ // the player with tracks it cannot load.+ if (saved.tracks.none { it.uri.startsWith("spotify:") }) return// One call rather than a sequence of commands: see LibrespotPlayer.restore// for why the order, position and modes have to be applied together.- player.restore(+ engine.restore(tracks = saved.tracks.map(::toQueueTrack),shuffleOrder = saved.shuffleOrder,index = saved.index,@@ -297,6 +407,11 @@ class PlaybackService : MediaLibraryService() {* the timeline exposes just the current sequence.*/private fun savePlayback() {+ // A backend with no PlayQueue behind it — the YouTube one — is saved off+ // the Media3 timeline instead. That loses the pre-shuffle order, which+ // only librespot's queue knows, so a shuffled queue comes back in the+ // order it was actually playing rather than the order it was built in.+ val queue = queue ?: return saveTimeline()if (queue.items.isEmpty()) {playbackStore.clear()return@@ -316,6 +431,100 @@ class PlaybackService : MediaLibraryService() {)}+ /**+ * The same snapshot, taken from the player's own timeline.+ *+ * Everything written here is already in the media items — the app puts the+ * track's URI, its metadata and the context it came from into each one — so+ * this is a read of what is loaded rather than a second bookkeeping of it.+ */+ private fun saveTimeline() {+ val count = player.mediaItemCount+ if (count == 0) {+ playbackStore.clear()+ return+ }+ val tracks = (0 until count).map { index ->+ val item = player.getMediaItemAt(index)+ val metadata = item.mediaMetadata+ CatalogTrack(+ uri = item.mediaId,+ name = metadata.title?.toString().orEmpty(),+ artist = metadata.artist?.toString().orEmpty(),+ durationMs = metadata.durationMs ?: 0L,+ artworkUrl = metadata.artworkUri?.toString(),+ )+ }+ val extras = player.currentMediaItem?.mediaMetadata?.extras+ playbackStore.save(+ SavedPlayback(+ tracks = tracks,+ shuffleOrder = null,+ index = player.currentMediaItemIndex,+ positionMs = player.currentPosition.coerceAtLeast(0),+ repeatMode = player.repeatMode,+ contextUri = extras?.getString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI),+ contextOrdered = extras?.getBoolean(dev.lelonio.square.ui.EXTRA_CONTEXT_ORDERED) == true,+ contextLabel = extras?.getString(dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL).orEmpty(),+ ),+ )+ }++ /**+ * Puts the last queue back into a plain [androidx.media3.common.Player].+ *+ * Paused, like the Spotify one: see [dev.lelonio.square.data.PlaybackStore].+ * A queue saved by the other backend is left alone — its URIs mean nothing+ * to this player, and loading them would fill the screen with tracks that+ * fail one after another.+ */+ private fun restoreTimeline(backendId: dev.lelonio.square.backend.BackendId) {+ if (player.mediaItemCount > 0) return+ val saved = playbackStore.load() ?: return+ val backend = when (backendId) {+ dev.lelonio.square.backend.BackendId.SPOTIFY -> container.spotifyBackend+ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC -> container.youtubeBackend+ }+ if (saved.tracks.none { backend.owns(it.uri) }) return++ player.setMediaItems(+ saved.tracks.map { track ->+ androidx.media3.common.MediaItem.Builder()+ .setMediaId(track.uri)+ .setUri(track.uri)+ .setMediaMetadata(+ androidx.media3.common.MediaMetadata.Builder()+ .setTitle(track.name)+ .setArtist(track.artist)+ .setDurationMs(track.durationMs.takeIf { it > 0 })+ .setArtworkUri(track.artworkUrl?.let(android.net.Uri::parse))+ .setExtras(+ android.os.Bundle().apply {+ saved.contextUri?.let {+ putString(dev.lelonio.square.ui.EXTRA_CONTEXT_URI, it)+ }+ putBoolean(+ dev.lelonio.square.ui.EXTRA_CONTEXT_ORDERED,+ saved.contextOrdered,+ )+ putString(+ dev.lelonio.square.ui.EXTRA_CONTEXT_LABEL,+ saved.contextLabel,+ )+ },+ )+ .build(),+ )+ .build()+ },+ saved.index.coerceIn(0, saved.tracks.lastIndex),+ saved.positionMs,+ )+ player.repeatMode = saved.repeatMode+ player.prepare()+ android.util.Log.i(TAG, "restored ${saved.tracks.size} tracks at ${saved.index}")+ }+private fun toCatalogTrack(track: PlayQueue.Track) = CatalogTrack(uri = track.uri,name = track.title,@@ -354,8 +563,12 @@ class PlaybackService : MediaLibraryService() {release()}session = null- NativeBridge.shutdown()- audioOutput.release()+ // Only if there is an engine to stop. Reaching for the Spotify backend+ // here would otherwise build its audio sink just to release it.+ if (librespot != null) {+ NativeBridge.shutdown()+ audioOutput.release()+ }super.onDestroy()}diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.ktindex 9ea78dc..422365c 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt@@ -77,6 +77,39 @@ class MainActivity : ComponentActivity() {}}+ /**+ * Shrinks into a floating window when leaving the app with a video playing.+ *+ * Only then: picture-in-picture on a music player with nothing to look at+ * would be a black rectangle covering whatever the user actually left to+ * do. The aspect ratio is the video's own, so the window is the picture+ * rather than the picture letterboxed inside a window.+ */+ override fun onUserLeaveHint() {+ super.onUserLeaveHint()+ if (!dev.lelonio.square.backend.youtube.YouTubeVideoMode.enabled.value) return+ val size = controller?.videoSize+ val width = size?.width?.takeIf { it > 0 } ?: 16+ val height = size?.height?.takeIf { it > 0 } ?: 9+ runCatching {+ enterPictureInPictureMode(+ android.app.PictureInPictureParams.Builder()+ .setAspectRatio(android.util.Rational(width, height))+ .build(),+ )+ }+ }++ override fun onPictureInPictureModeChanged(+ isInPictureInPictureMode: Boolean,+ newConfig: android.content.res.Configuration,+ ) {+ super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)+ dev.lelonio.square.backend.youtube.YouTubeVideoMode.setPictureInPicture(+ isInPictureInPictureMode,+ )+ }+override fun onNewIntent(intent: android.content.Intent) {super.onNewIntent(intent)setIntent(intent)@@ -153,14 +186,22 @@ class MainActivity : ComponentActivity() {playNext: Boolean = false,): MediaItem =MediaItem.Builder()- // The media id carries the Spotify URI; PlayQueue refuses anything else.+ // The media id carries the track's URI; PlayQueue refuses anything else..setMediaId(track.uri)+ // The same URI again, as the thing to play. The librespot player+ // ignores it and works off the media id, but ExoPlayer — which is+ // what the YouTube backend uses — plays the URI and nothing else;+ // its resolver turns a `ytmusic:` one into a real stream at load.+ .setUri(track.uri).setMediaMetadata(MediaMetadata.Builder().setTitle(track.name).setArtist(track.artist).setAlbumTitle(track.album)- .setDurationMs(track.durationMs)+ // Left unset when unknown rather than sent as zero: some of+ // YouTube's shelves carry no length, and a zero here would+ // win over the one the player works out from the stream.+ .setDurationMs(track.durationMs.takeIf { it > 0 }).setArtworkUri(track.artworkUrl?.let(android.net.Uri::parse))// Where the queue came from, carried with the item because// the engine lives in the service and this is the onlydiff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 3af8218..dfeec8d 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -6,6 +6,10 @@ import androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport dev.lelonio.square.SquareApplicationimport dev.lelonio.square.auth.SpotifyOAuth+import dev.lelonio.square.backend.BackendAuthState+import dev.lelonio.square.backend.BackendId+import dev.lelonio.square.backend.HomeRow+import dev.lelonio.square.backend.SearchLabelsimport dev.lelonio.square.Rimport dev.lelonio.square.data.Catalogimport dev.lelonio.square.data.AddTracksRequestDto@@ -29,6 +33,8 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.dropimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.stateInimport kotlinx.coroutines.launch@@ -138,6 +144,41 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val feed: StateFlow<FeedState> = _feed.asStateFlow()private var feedJob: Job? = null+ /** YouTube Music's own home page, as it laid it out; see [MusicBackend.homeRows]. */+ data class YouTubeHomeState(+ val rows: List<HomeRow> = emptyList(),+ val loading: Boolean = false,+ val error: String? = null,+ )++ private val _youtubeHome = MutableStateFlow(YouTubeHomeState())+ val youtubeHome: StateFlow<YouTubeHomeState> = _youtubeHome.asStateFlow()+ private var youtubeHomeJob: Job? = null++ /**+ * Loads it, once per sign-in state.+ *+ * Re-read after signing in rather than cached for the session: the page is+ * a different page once YouTube knows whose it is, and leaving the+ * signed-out one up would make the login look like it did nothing.+ */+ fun loadYouTubeHome(force: Boolean = false) {+ val backend = container.activeBackend+ if (backend.id != BackendId.YOUTUBE_MUSIC) return+ if (youtubeHomeJob?.isActive == true) return+ if (!force && _youtubeHome.value.rows.isNotEmpty()) return++ _youtubeHome.value = _youtubeHome.value.copy(loading = true, error = null)+ youtubeHomeJob = viewModelScope.launch {+ runCatching { backend.homeRows() }+ .onSuccess { _youtubeHome.value = YouTubeHomeState(rows = it, loading = false) }+ .onFailure {+ android.util.Log.e(TAG, "youtube home failed: ${chain(it)}", it)+ _youtubeHome.value = YouTubeHomeState(loading = false, error = describe(it))+ }+ }+ }+/*** Loads the feed, quietly.*@@ -459,7 +500,12 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val needsSetup: Boolean = false,)- private val _search = MutableStateFlow(SearchState(needsSetup = !container.webApi.isReady))+ private val _search = MutableStateFlow(+ SearchState(+ needsSetup = container.activeBackend.id == BackendId.SPOTIFY &&+ !container.webApi.isReady,+ ),+ )val search: StateFlow<SearchState> = _search.asStateFlow()private var searchJob: Job? = null@@ -470,7 +516,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {* word, mostly on prefixes nobody wanted results for.*/fun onSearchQuery(query: String) {- val ready = container.webApi.isReady+ val backend = container.activeBackend+ // Only Spotify needs a registered application to search; YouTube Music+ // is anonymous, so the setup prompt would be asking for nothing.+ val ready = backend.id != BackendId.SPOTIFY || container.webApi.isReady_search.value = _search.value.copy(query = query, needsSetup = !ready)searchJob?.cancel()@@ -482,11 +531,16 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {searchJob = viewModelScope.launch {delay(SEARCH_DEBOUNCE_MS)_search.value = _search.value.copy(loading = true, error = null)- runCatching { container.api.search(query.trim()).toResults(- artistLabel = string(R.string.artist),- albumLabel = string(R.string.album),- playlistLabel = string(R.string.playlist),- ) }+ runCatching {+ backend.search(+ query,+ SearchLabels(+ artist = string(R.string.artist),+ album = string(R.string.album),+ playlist = string(R.string.playlist),+ ),+ )+ }.onSuccess { results ->_search.value = _search.value.copy(loading = false, results = results)}@@ -602,7 +656,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {fun deleteEffectPreset(id: String) = container.effectPresets.delete(id)/** Locally recorded listening history; see [dev.lelonio.square.data.RecentStore]. */- val recent: StateFlow<List<CatalogTrack>> get() = container.recentStore.tracks+ /**+ * Recently played, filtered to the source in use.+ *+ * One list on disk, two catalogues drawing from it: a Spotify URI in the+ * YouTube page is a tile that cannot be played, and the other way round.+ * Filtered rather than kept apart so that switching back finds the history+ * still there.+ */+ val recent: StateFlow<List<CatalogTrack>> =+ combine(container.recentStore.tracks, container.preferences.backend) { tracks, _ ->+ tracks.filter { container.activeBackend.owns(it.uri) }+ }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())/** Called when a track starts, to keep the home page's history current. */fun recordPlayed(track: CatalogTrack) = viewModelScope.launch {@@ -610,7 +675,18 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}init {- if (container.tokenStore.isLoggedIn) {+ // Everything on screen belongs to one source, so a change of source+ // starts the app's data over rather than patching it: the library, the+ // feed, the search results, the open detail page and the recent list all+ // describe a catalogue that is no longer the one being used.+ viewModelScope.launch {+ container.preferences.backend.drop(1).collect { reload() }+ }++ if (container.activeBackend.id != BackendId.SPOTIFY) {+ // No engine to authenticate, so nothing to send the service.+ refresh()+ } else if (container.tokenStore.isLoggedIn) {PlaybackService.connect(app)refresh()}@@ -645,12 +721,60 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {_state.value = UiState.LoggedOut}+ /** Starts over on the newly chosen source; see the note in `init`. */+ private fun reload() {+ inFlight?.cancel()+ feedJob?.cancel()+ searchJob?.cancel()+ contextCache.clear()+ _playlist.value = PlaylistState()+ _feed.value = FeedState()+ _search.value = SearchState()+ _youtubeHome.value = YouTubeHomeState()+ _state.value = UiState.Loading+ if (container.activeBackend.id == BackendId.SPOTIFY && container.tokenStore.isLoggedIn) {+ PlaybackService.connect(getApplication())+ }+ refresh()+ if (container.activeBackend.id == BackendId.SPOTIFY) {+ // The home page's own sections, which nothing else asks for again:+ // the screen is already composed, so its one-shot load will not run+ // a second time.+ loadFeed()+ } else {+ loadYouTubeHome(force = true)+ }+ }+fun refresh(): Job {inFlight?.takeIf { it.isActive }?.let { return it }return launchRefresh().also { inFlight = it }}private fun launchRefresh() = viewModelScope.launch {+ val backend = container.activeBackend+ if (backend.id != BackendId.SPOTIFY) {+ // No access point to wait for and no Premium account to check: this+ // backend is usable at once, and signing in only adds the library.+ _state.value = UiState.Loading+ val name = (backend.authState.value as? BackendAuthState.LoggedIn)?.displayName+ runCatching { backend.playlists() }+ .onSuccess { playlists ->+ _state.value = UiState.Ready(+ displayName = name.orEmpty(),+ playlists = playlists,+ )+ }+ .onFailure {+ android.util.Log.w(TAG, "youtube library unavailable: ${describe(it)}")+ // Not a failure worth a whole error screen: the library is+ // the one part that needs an account, and everything else+ // on this backend works without one.+ _state.value = UiState.Ready(displayName = name.orEmpty(), playlists = emptyList())+ }+ return@launch+ }+if (!container.tokenStore.isLoggedIn) {_state.value = UiState.LoggedOutreturn@launch@@ -827,7 +951,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val cached = entry?.tracks.orEmpty()runCatching {- if (kind == DetailKind.ARTIST) {+ if (!playlist.uri.startsWith("spotify:")) {+ // Another backend's context. Resolved in one call rather+ // than page by page: the Spotify paths below are built+ // around the Web API's paging and the access point's+ // per-track lookups, neither of which exists here.+ val tracks = container.activeBackend.tracksOf(playlist.uri)+ _playlist.value = base.copy(tracks = tracks, loading = false)+ } else if (kind == DetailKind.ARTIST) {val (tracks, albums) = loadArtist(playlist.uri)_playlist.value = base.copy(tracks = tracks, albums = albums)} else if (cached.isNotEmpty() && isUnchanged(playlist.uri, entry?.snapshotId)) {@@ -899,6 +1030,72 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {}}+ /** Whether the active source lets the account make and change playlists. */+ val canEditPlaylists: Boolean get() = container.activeBackend.canEditPlaylists++ /**+ * Makes a playlist and puts it at the top of the library.+ *+ * Inserted locally rather than by refetching: the service takes a moment to+ * list a playlist it has just created, and a new playlist that does not+ * appear reads as the button having failed.+ */+ fun createPlaylist(name: String) = viewModelScope.launch {+ runCatching { container.activeBackend.createPlaylist(name.trim()) }+ .onSuccess { created ->+ val ready = _state.value as? UiState.Ready ?: return@onSuccess+ _state.value = ready.copy(playlists = listOf(created) + ready.playlists)+ }+ .onFailure { android.util.Log.e(TAG, "create playlist failed: ${chain(it)}", it) }+ }++ fun renamePlaylist(uri: String, name: String) = viewModelScope.launch {+ val trimmed = name.trim()+ if (trimmed.isEmpty()) return@launch+ // Renamed on screen first: this is one field on a row, the failure is+ // rare, and putting the old name back is all an undo needs to be.+ val ready = _state.value as? UiState.Ready+ val before = ready?.playlists+ if (ready != null) {+ _state.value = ready.copy(+ playlists = ready.playlists.map {+ if (it.uri == uri) it.copy(name = trimmed) else it+ },+ )+ }+ if (_playlist.value.uri == uri) {+ _playlist.value = _playlist.value.copy(name = trimmed)+ }++ runCatching { container.activeBackend.renamePlaylist(uri, trimmed) }+ .onFailure {+ android.util.Log.e(TAG, "rename playlist failed: ${chain(it)}", it)+ val current = _state.value as? UiState.Ready+ if (before != null && current != null) {+ _state.value = current.copy(playlists = before)+ }+ }+ invalidateContext(uri)+ }++ fun deletePlaylist(uri: String) = viewModelScope.launch {+ val ready = _state.value as? UiState.Ready+ val before = ready?.playlists+ if (ready != null) {+ _state.value = ready.copy(playlists = ready.playlists.filterNot { it.uri == uri })+ }++ runCatching { container.activeBackend.deletePlaylist(uri) }+ .onFailure {+ android.util.Log.e(TAG, "delete playlist failed: ${chain(it)}", it)+ val current = _state.value as? UiState.Ready+ if (before != null && current != null) {+ _state.value = current.copy(playlists = before)+ }+ }+ invalidateContext(uri)+ }+/** Drops a context from both caches so the next open re-reads it. */private fun invalidateContext(uri: String) {contextCache.remove(uri)diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex d0d3682..2b7a48b 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -8,6 +8,7 @@ import androidx.compose.animation.core.tweenimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Row@@ -30,11 +31,13 @@ import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.snapshotFlowimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValue@@ -76,6 +79,7 @@ import dev.lelonio.square.data.Catalogimport dev.lelonio.square.data.CatalogPlaylistimport dev.lelonio.square.data.CatalogTrackimport dev.lelonio.square.data.Lyrics+import dev.lelonio.square.backend.youtube.YouTubeVideoModeimport dev.lelonio.square.playback.AudioEffectsimport dev.lelonio.square.ui.glass.LiquidBottomTabimport dev.lelonio.square.ui.glass.LiquidBottomTabs@@ -91,10 +95,14 @@ import dev.lelonio.square.ui.components.TrackSheetimport dev.lelonio.square.ui.components.TrackSheetActionimport dev.lelonio.square.ui.library.openLinkimport com.adamglin.phosphoricons.regular.LinkSimple+import com.adamglin.phosphoricons.regular.PencilSimpleimport com.adamglin.phosphoricons.regular.Plusimport com.adamglin.phosphoricons.regular.Queue+import com.adamglin.phosphoricons.regular.SpotifyLogo+import com.adamglin.phosphoricons.regular.YoutubeLogoimport com.adamglin.phosphoricons.regular.Trashimport dev.lelonio.square.ui.player.MiniPlayer+import dev.lelonio.square.ui.player.PlaybackStateimport dev.lelonio.square.ui.player.MiniPlayerHeightimport dev.lelonio.square.ui.player.NowPlayingSheetimport dev.lelonio.square.ui.player.PlayerScreen@@ -103,11 +111,13 @@ import dev.lelonio.square.ui.player.rememberPlaybackStateimport dev.lelonio.square.ui.player.rememberPositionMsimport dev.lelonio.square.ui.player.rememberQueueimport dev.lelonio.square.ui.search.SearchScreen+import dev.lelonio.square.ui.onboarding.BackendChoiceScreenimport dev.lelonio.square.ui.onboarding.OnboardingScreenimport dev.lelonio.square.ui.settings.SettingsScreenimport dev.lelonio.square.ui.theme.Inkimport dev.lelonio.square.ui.theme.SquareThemeimport dev.lelonio.square.ui.theme.rememberArtworkColor+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchimport com.adamglin.PhosphorIconsimport com.adamglin.phosphoricons.fill.Play@@ -120,6 +130,9 @@ import com.adamglin.phosphoricons.regular.Houseimport com.adamglin.phosphoricons.regular.MagnifyingGlassimport com.adamglin.phosphoricons.regular.MusicNotes+/** A name being asked for: null playlist means one that does not exist yet. */+private data class NamingRequest(val playlist: CatalogPlaylist?)+/** A track menu waiting to be drawn: what it is about, and where it points. */private data class TrackMenuRequest(val track: dev.lelonio.square.data.CatalogTrack,@@ -179,11 +192,40 @@ fun SquareApp() {val state by viewModel.state.collectAsStateWithLifecycle()val playlist by viewModel.playlist.collectAsStateWithLifecycle()- val playback by rememberPlaybackState(player)+ val context = LocalContext.current++ // The session as it was left, so the player has something to draw before+ // the media controller connects. Read once, off the saved queue.+ val seed = remember(context) { savedPlaybackSeed(context) }+ val playback by rememberPlaybackState(player, seed)// Held as State, not read here: reading the position at this level would// recompose the whole app — lists included — several times a second.val positionMs = rememberPositionMs(player, playback.isPlaying)val queue by rememberQueue(player)+ val videoOn by YouTubeVideoMode.enabled.collectAsStateWithLifecycle()++ // Video keeps playing when the app leaves the foreground, surface or no+ // surface. Switching back to the audio-only stream would be tidier, but the+ // stream has to reopen to do it and that break is audible — which, for+ // someone who put the phone down to keep listening, is the one thing+ // leaving the app must not do.++ // Speed and pitch, written to the player only once the slider settles.+ //+ // A drag produces a value every frame, and each one reconfigures the audio+ // sink: on the ExoPlayer the YouTube source uses, that means a flush every+ // 8ms, which starves the output — the sound stops and the position falls+ // back to where it stalled. The wait is short enough not to be felt after+ // letting go, and the slider draws its own value meanwhile.+ val effectsScope = rememberCoroutineScope()+ var effectsJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }+ val setPlaybackParameters: (PlaybackParameters) -> Unit = { params ->+ effectsJob?.cancel()+ effectsJob = effectsScope.launch {+ kotlinx.coroutines.delay(120)+ player?.playbackParameters = params+ }+ }val accent by rememberArtworkColor(playback.artworkUrl)val recent by viewModel.recent.collectAsStateWithLifecycle()val search by viewModel.search.collectAsStateWithLifecycle()@@ -200,9 +242,17 @@ fun SquareApp(// Asked for again from the settings, after it has already been finished.var showTutorial by remember { mutableStateOf(false) }+ /** The Google sign-in web view, opened from the settings. */+ var showYouTubeLogin by remember { mutableStateOf(false) }+// The open track menu, if any. Held here because the menu is drawn above// everything the app puts over its screens.var trackMenu by remember { mutableStateOf<TrackMenuRequest?>(null) }+ // The playlist a long press opened the actions for.+ var playlistMenu by remember { mutableStateOf<CatalogPlaylist?>(null) }+ // Open when a name is being asked for; the playlist is null when the name is+ // for one that does not exist yet.+ var naming by remember { mutableStateOf<NamingRequest?>(null) }// Once, on the first composition that has a usable Web API session. The// ViewModel keeps what it fetched, so navigating away and back does not@@ -228,11 +278,49 @@ fun SquareApp(// the player it was opened from.val overlayBackdrop = rememberLayerBackdrop()+ // Where the player was left, read before anything is drawn.+ //+ // The activity is destroyed while the app sits in the background and the+ // service keeps playing, so coming back from the launcher rebuilds this+ // composition from nothing. Starting the animation at rest in the open+ // position makes the first frame the player itself; waiting for the media+ // controller to connect and *then* animating is what showed the home page+ // for a moment first.+ val preferences = remember(context) {+ (context.applicationContext as dev.lelonio.square.SquareApplication).preferences+ }++ /** False only until the source has been picked once; see BackendChoiceScreen. */+ val backendChosen by preferences.backendChosen.collectAsStateWithLifecycle()+ val backend by preferences.backend.collectAsStateWithLifecycle()+ val youtubeHome by viewModel.youtubeHome.collectAsStateWithLifecycle()++ // Once the source is YouTube Music. Keyed on the backend so switching to it+ // at runtime fills the page rather than leaving yesterday's empty one.+ LaunchedEffect(backend) { viewModel.loadYouTubeHome() }+// How far the player is open, 0 to 1. A value rather than a destination:// see NowPlayingSheet for why the player stopped being a route.- val expand = remember { Animatable(0f) }+ val expand = remember { Animatable(if (preferences.playerWasOpen()) 1f else 0f) }val scope = rememberCoroutineScope()+ // Remembered for the next launch. Written when the animation settles rather+ // than on every frame of the drag.+ LaunchedEffect(Unit) {+ snapshotFlow { expand.isRunning to expand.value }+ .collect { (running, value) ->+ if (!running) preferences.setPlayerOpen(value > 0.5f)+ }+ }++ // Nothing to be open onto: the queue was cleared, or the saved session did+ // not survive. Closed without animating, so it is never seen.+ LaunchedEffect(player, playback.hasItem) {+ if (player != null && !playback.hasItem && expand.value > 0f) {+ expand.snapTo(0f)+ }+ }+// Opened from outside — a tap on the media notification.//// Held as a pending request rather than acted on immediately: the media@@ -282,10 +370,14 @@ fun SquareApp(// Fetched per track, like the lyrics. Most tracks have none, so a null is an// ordinary answer and the player falls back to the cover.- LaunchedEffect(playback.mediaId) {+ // Canvas is Spotify's own, served by its access point: on another source+ // there is nobody to ask.+ LaunchedEffect(playback.mediaId, backend) {val uri = playback.mediaIdcanvas = null- if (uri != null) canvas = Catalog.canvas(uri)+ if (uri != null && backend == dev.lelonio.square.backend.BackendId.SPOTIFY) {+ canvas = Catalog.canvas(uri)+ }}var lyrics by remember { mutableStateOf<Lyrics?>(null) }@@ -298,14 +390,22 @@ fun SquareApp(lyrics = nullif (uri == null) return@LaunchedEffectlyricsLoading = true- lyrics = runCatching { Catalog.lyrics(uri) }.getOrNull()+ lyrics = runCatching {+ (context.applicationContext as dev.lelonio.square.SquareApplication)+ .activeBackend+ .lyrics(+ uri = uri,+ title = playback.title,+ artist = playback.artist,+ durationMs = playback.durationMs,+ )+ }.getOrNull()lyricsLoading = false}// The language the app is read in. Changing it re-creates the activity,// which is the only way a Compose tree already built out of one set of// resources can be rebuilt out of another.- val context = LocalContext.currentval languageStore = remember(context) {(context.applicationContext as dev.lelonio.square.SquareApplication).language}@@ -322,8 +422,30 @@ fun SquareApp(// Read once, up here: these travel with a play as plain text, and the rows// that start one are not composables of their own.val playAgainLabel = stringResource(R.string.play_again)+ val trendingLabel = stringResource(R.string.trending_now)val searchLabel = stringResource(R.string.search)+ val inPip by YouTubeVideoMode.pictureInPicture.collectAsStateWithLifecycle()++ // In a floating window the app is the picture and nothing else.+ //+ // Drawing the whole interface into a window that size would put a home page,+ // a tab bar and a player's worth of controls into a thumbnail, none of it+ // legible and none of it reachable — the system owns the gestures there.+ if (inPip) {+ SquareTheme(seed = accent) {+ Box(+ Modifier+ .fillMaxSize()+ .background(Color.Black),+ contentAlignment = Alignment.Center,+ ) {+ player?.let { dev.lelonio.square.ui.player.VideoSurface(it) }+ }+ }+ return+ }+SquareTheme(seed = accent) {// Material's default content colour is black, and it used to arrive from// the Surface that wrapped this tree. That Surface is gone — it painted@@ -336,6 +458,33 @@ fun SquareApp(val currentEntry by navController.currentBackStackEntryAsState()val route = currentEntry?.destination?.route+ // Back to the home page when the source changes: an open+ // playlist, a search or a detail page all belong to the+ // catalogue that was just swapped out.+ var lastBackend by remember { mutableStateOf(backend) }+ // Held up over the switch, so the page changing catalogue+ // underneath is something that happens behind a curtain rather+ // than a screen half of one source and half of the other.+ var switching by remember { mutableStateOf(false) }+ LaunchedEffect(backend) {+ if (backend != lastBackend) {+ lastBackend = backend+ switching = true+ navController.popBackStack(Routes.HOME, inclusive = false)+ // Held until the new source has actually answered, so+ // what appears behind it is a page rather than a page+ // being built — with a floor, so the splash is never a+ // flash, and a ceiling, because a cold session can take+ // longer than anyone will stare at a logo.+ kotlinx.coroutines.withTimeoutOrNull(3_000) {+ kotlinx.coroutines.delay(600)+ snapshotFlow { state }+ .first { it !is MainViewModel.UiState.Loading }+ }+ switching = false+ }+ }+val statusBar = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()val navBar = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()@@ -444,6 +593,12 @@ fun SquareApp(navController.navigate(Routes.PLAYLIST)},backdrop = artBackdrop,+ youtubeMode =+ backend == dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC,+ youtubeHome = youtubeHome,+ onPlayTrending = { tracks, index ->+ onPlay(tracks, index, null, false, trendingLabel)+ },onOpenSettings = { navController.navigate(Routes.SETTINGS) },)}@@ -461,6 +616,14 @@ fun SquareApp(onPlay(tracks, index, null, false, searchLabel)},onEnqueue = onEnqueue,+ onTrackMenu = { track ->+ trackMenu = TrackMenuRequest(+ track = track,+ // Nothing to take a search result out+ // of: it belongs to no playlist here.+ removable = false,+ )+ },onOpenContext = { item ->viewModel.openContext(item.uri, item.title, item.artworkUrl)navController.navigate(Routes.PLAYLIST)@@ -478,6 +641,9 @@ fun SquareApp(onLogOut = viewModel::logOut,onOpenPlaylist = { navController.openPlaylist(viewModel, it) },playlistOrder = playlistOrder,+ canEdit = viewModel.canEditPlaylists,+ onCreatePlaylist = { naming = NamingRequest(null) },+ onPlaylistMenu = { playlistMenu = it },backdrop = artBackdrop,)}@@ -497,6 +663,7 @@ fun SquareApp(language = language,onLanguage = setLanguage,onBack = { navController.popBackStack() },+ onYouTubeSignIn = { showYouTubeLogin = true },)}@@ -550,8 +717,13 @@ fun SquareApp(track = track,// Only a playlist can have// something taken out of it.+ // Taking a track out goes through+ // the Spotify Web API, so only a+ // Spotify playlist can offer it.removable = playlist.kind ==- MainViewModel.DetailKind.PLAYLIST,+ MainViewModel.DetailKind.PLAYLIST &&+ backend ==+ dev.lelonio.square.backend.BackendId.SPOTIFY,)},storedSort = trackSort,@@ -639,12 +811,14 @@ fun SquareApp(// PlaybackParameters carries both; changing one// has to carry the other through unchanged.onSpeed = {- player?.playbackParameters =- PlaybackParameters(it, playback.pitch)+ setPlaybackParameters(+ PlaybackParameters(it, playback.pitch),+ )},onPitch = {- player?.playbackParameters =- PlaybackParameters(playback.speed, it)+ setPlaybackParameters(+ PlaybackParameters(playback.speed, it),+ )},onReverb = AudioEffects::setReverb,presets = presets,@@ -666,6 +840,8 @@ fun SquareApp(canvas = canvas,devices = devices,onOpenDevices = viewModel::openDevices,+ connectAvailable =+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY,onCloseDevices = viewModel::closeDevices,onRefreshDevices = viewModel::refreshDevices,onSelectDevice = { viewModel.transferPlayback(it) },@@ -678,6 +854,16 @@ fun SquareApp(},addToPlaylist = addToPlaylist,onPickPlaylist = viewModel::addToPlaylist,+ playlistEditAvailable =+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY,+ onWatchVideo = player+ ?.takeIf {+ playback.mediaId+ ?.startsWith("ytmusic:track:") == true+ }+ ?.let { { YouTubeVideoMode.toggle(it) } },+ videoOn = videoOn,+ videoPlayer = player,)},)@@ -689,10 +875,69 @@ fun SquareApp(// Above the tab bar and the now-playing bar, which is the whole// reason it lives here instead of in the screen that asked for// it.- val menu = trackMenu+ var lastPlaylistMenu by remember { mutableStateOf<CatalogPlaylist?>(null) }+ LaunchedEffect(playlistMenu) { playlistMenu?.let { lastPlaylistMenu = it } }+ val shownPlaylist = playlistMenu ?: lastPlaylistMenu+ TrackSheet(+ visible = playlistMenu != null,+ title = shownPlaylist?.name.orEmpty(),+ subtitle = stringResource(R.string.playlist),+ artworkUrl = shownPlaylist?.artworkUrl,+ backdrop = overlayBackdrop,+ onDismiss = { playlistMenu = null },+ ) {+ if (shownPlaylist != null) {+ TrackSheetAction(+ stringResource(R.string.rename),+ PhosphorIcons.Regular.PencilSimple,+ ) {+ naming = NamingRequest(shownPlaylist)+ playlistMenu = null+ }+ TrackSheetAction(+ stringResource(R.string.delete),+ PhosphorIcons.Regular.Trash,+ destructive = true,+ ) {+ viewModel.deletePlaylist(shownPlaylist.uri)+ playlistMenu = null+ }+ }+ }++ naming?.let { request ->+ dev.lelonio.square.ui.components.NameDialog(+ title = stringResource(+ if (request.playlist == null) R.string.new_playlist else R.string.rename,+ ),+ initial = request.playlist?.name.orEmpty(),+ confirmLabel = stringResource(+ if (request.playlist == null) R.string.create else R.string.save,+ ),+ onConfirm = { name ->+ val playlist = request.playlist+ if (playlist == null) {+ viewModel.createPlaylist(name)+ } else {+ viewModel.renamePlaylist(playlist.uri, name)+ }+ naming = null+ },+ onDismiss = { naming = null },+ )+ }++ // Held one beat longer than the state that opened it: the+ // sheet slides out over a couple of hundred milliseconds, and+ // reading the track straight off `trackMenu` emptied the title,+ // the artist and every action the instant it was dismissed —+ // the sheet was seen leaving with nothing in it.+ var lastMenu by remember { mutableStateOf<TrackMenuRequest?>(null) }+ LaunchedEffect(trackMenu) { trackMenu?.let { lastMenu = it } }+ val menu = trackMenu ?: lastMenuval clipboard = androidx.compose.ui.platform.LocalClipboardManager.currentTrackSheet(- visible = menu != null,+ visible = trackMenu != null,title = menu?.track?.name.orEmpty(),subtitle = menu?.track?.artist.orEmpty(),artworkUrl = menu?.track?.artworkUrl,@@ -708,9 +953,13 @@ fun SquareApp(trackMenu = nullonEnqueue(menu.track)}- TrackSheetAction(stringResource(R.string.add_to_playlist), PhosphorIcons.Regular.Plus) {- trackMenu = null- viewModel.openAddToPlaylist(menu.track.uri, menu.track.name)+ // Writing to a playlist is the Spotify Web API's; on+ // another source the entry would only ever fail.+ if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY) {+ TrackSheetAction(stringResource(R.string.add_to_playlist), PhosphorIcons.Regular.Plus) {+ trackMenu = null+ viewModel.openAddToPlaylist(menu.track.uri, menu.track.name)+ }}TrackSheetAction(stringResource(R.string.copy_link), PhosphorIcons.Regular.LinkSimple) {trackMenu = null@@ -739,10 +988,109 @@ fun SquareApp(onDismiss = viewModel::closeAddToPlaylist,)+ // The curtain. Over the whole app, under nothing.+ androidx.compose.animation.AnimatedVisibility(+ visible = switching,+ enter = androidx.compose.animation.fadeIn(tween(180)),+ exit = androidx.compose.animation.fadeOut(tween(420)),+ modifier = Modifier.zIndex(20f),+ ) {+ Box(+ Modifier+ .fillMaxSize()+ // A colour of its own: the theme's background is+ // transparent, because every page in this app is+ // drawn over the blurred artwork. A curtain has to+ // be opaque or it is not a curtain.+ .background(Color(0xFF0A0A0A)),+ contentAlignment = Alignment.Center,+ ) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ dev.lelonio.square.ui.components.AppIcon(84.dp)+ dev.lelonio.square.ui.components.SquareWordmark(height = 28.dp)+ // Which source is being opened, named and marked:+ // the whole point of the wait is that the app is+ // becoming a different one, and a bare spinner says+ // nothing about that.+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ Icon(+ when (backend) {+ dev.lelonio.square.backend.BackendId.SPOTIFY ->+ PhosphorIcons.Regular.SpotifyLogo+ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC ->+ PhosphorIcons.Regular.YoutubeLogo+ },+ contentDescription = null,+ tint = Ink,+ modifier = Modifier.size(20.dp),+ )+ Text(+ stringResource(+ when (backend) {+ dev.lelonio.square.backend.BackendId.SPOTIFY ->+ R.string.backend_spotify+ dev.lelonio.square.backend.BackendId.YOUTUBE_MUSIC ->+ R.string.backend_youtube+ },+ ),+ style = MaterialTheme.typography.titleMedium,+ color = Ink,+ )+ }+ }+ }+ }+// Above everything, bars and player included: until it is done// there is nothing underneath worth reaching, and on a fresh// install most of what is underneath does not work yet.- if (!onboarded || showTutorial) {+ //+ // Above the tutorial too, and asked first: everything the+ // tutorial explains is Spotify's setup, so the source has to be+ // settled before any of it is worth walking through.+ // Over everything, like the tutorial: it is Google's own sign-in+ // page and half-covering it would be the wrong thing to do with+ // a page someone is typing a password into.+ if (showYouTubeLogin) {+ val account = remember(context) {+ (context.applicationContext as dev.lelonio.square.SquareApplication)+ .youtubeAccount+ }+ Box(+ Modifier+ .fillMaxSize()+ .background(androidx.compose.ui.graphics.Color(0xFF101012)),+ ) {+ dev.lelonio.square.backend.youtube.YouTubeLoginScreen(+ account = account,+ onDone = {+ showYouTubeLogin = false+ // The library is the whole point of signing in,+ // and it was read as the signed-out account.+ viewModel.refresh()+ },+ )+ }+ }++ if (!backendChosen) {+ BackendChoiceScreen(onChoose = preferences::setBackend)+ } else if (+ // Every step of it is Spotify's setup — the Premium+ // account, the login, the registered application — so on+ // YouTube Music it would be five screens of instructions+ // for something the user just chose not to use. Still+ // reachable from the settings, which is where someone who+ // means to switch to Spotify would go.+ showTutorial ||+ (!onboarded && backend == dev.lelonio.square.backend.BackendId.SPOTIFY)+ ) {OnboardingScreen(state = state,webApi = webApi,@@ -866,12 +1214,16 @@ private fun BottomBar(// 40% fill that made the bar a solid slab beside the other glass.accentColor = Ink,containerColor = GlassFilm,+ indicatorVisible = routeIndex >= 0,) {BottomItem(stringResource(R.string.home),PhosphorIcons.Fill.House,PhosphorIcons.Regular.House,- selected == 0,+ // Nothing is lit while the page on screen is not one of these+ // two: search is a destination of its own, and leaving Home+ // filled behind it said the app was somewhere it was not.+ routeIndex >= 0 && selected == 0,) {onSelect(Routes.HOME)}@@ -879,7 +1231,7 @@ private fun BottomBar(stringResource(R.string.library),PhosphorIcons.Fill.MusicNotes,PhosphorIcons.Regular.MusicNotes,- selected == 1,+ routeIndex >= 0 && selected == 1,) { onSelect(Routes.LIBRARY) }}}@@ -1004,3 +1356,28 @@ private fun Player.cycleRepeatMode() {else -> Player.REPEAT_MODE_OFF}}++/**+ * The playing track as the last session left it, or null when there was none.+ *+ * The saved index points into the *current* order while the list is kept in the+ * pre-shuffle one, so the permutation has to be applied to find the track that+ * was actually playing.+ */+private fun savedPlaybackSeed(context: android.content.Context): PlaybackState? {+ val saved = dev.lelonio.square.data.PlaybackStore(context).load() ?: return null+ val position = saved.shuffleOrder?.getOrNull(saved.index) ?: saved.index+ val track = saved.tracks.getOrNull(position) ?: return null+ return PlaybackState(+ hasItem = true,+ mediaId = track.uri,+ title = track.name,+ artist = track.artist,+ artworkUrl = track.artworkUrl,+ durationMs = track.durationMs,+ // Not "paused": what it is doing is unknown until the controller+ // answers, and a play button that flips to pause a moment later reads+ // as the app having ignored a tap.+ isBuffering = true,+ )+}diff --git a/app/src/main/java/dev/lelonio/square/ui/components/NameDialog.kt b/app/src/main/java/dev/lelonio/square/ui/components/NameDialog.ktnew file mode 100644index 0000000..c8e8538--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/components/NameDialog.kt@@ -0,0 +1,124 @@+package dev.lelonio.square.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import dev.lelonio.square.R+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDim++/**+ * Asks for one line of text — a playlist's name, on the way in or on the way to+ * being changed.+ *+ * Its own dialog rather than a sheet: this is a question with an answer, and+ * the keyboard has to come up over whatever is behind it. Built out of the+ * app's own surfaces for the same reason every other control is.+ */+@Composable+fun NameDialog(+ title: String,+ initial: String,+ confirmLabel: String,+ onConfirm: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ var text by remember(initial) { mutableStateOf(initial) }+ val shape = RoundedCornerShape(24.dp)++ Dialog(onDismissRequest = onDismiss) {+ Column(+ Modifier+ .fillMaxWidth()+ .clip(shape)+ .background(DialogFill)+ .padding(22.dp),+ ) {+ Text(title, style = MaterialTheme.typography.titleMedium, color = Ink)++ Box(+ Modifier+ .padding(top = 18.dp)+ .fillMaxWidth()+ .clip(RoundedCornerShape(14.dp))+ .background(FieldFill)+ .padding(horizontal = 14.dp, vertical = 12.dp),+ ) {+ if (text.isEmpty()) {+ Text(+ stringResource(R.string.playlist_name),+ style = MaterialTheme.typography.bodyLarge,+ color = InkDim,+ )+ }+ BasicTextField(+ value = text,+ onValueChange = { text = it },+ singleLine = true,+ textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink),+ cursorBrush = SolidColor(Ink),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ modifier = Modifier.fillMaxWidth(),+ )+ }++ Row(+ Modifier+ .padding(top = 18.dp)+ .fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),+ ) {+ DialogAction(stringResource(R.string.cancel), InkDim, onDismiss)+ // Nothing to create or save while the field is empty, and a+ // playlist called nothing is not something either service will+ // take anyway.+ DialogAction(+ confirmLabel,+ if (text.isBlank()) InkDim else Ink,+ ) { if (text.isNotBlank()) onConfirm(text) }+ }+ }+ }+}++@Composable+private fun DialogAction(label: String, color: Color, onClick: () -> Unit) {+ Text(+ label,+ style = MaterialTheme.typography.bodyLarge,+ color = color,+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .clickable(onClick = onClick)+ .padding(horizontal = 16.dp, vertical = 8.dp),+ )+}++/** Opaque: a dialog floats over its own scrim, with no artwork to refract. */+private val DialogFill = Color(0xFF1B1B1B)++private val FieldFill = Color.White.copy(alpha = 0.08f)diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.ktindex f52ceeb..29faab7 100644--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt@@ -13,6 +13,8 @@ package dev.lelonio.square.ui.glassimport androidx.compose.animation.core.Animatableimport androidx.compose.animation.core.EaseOutimport androidx.compose.animation.core.spring+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tweenimport androidx.compose.foundation.isSystemInDarkThemeimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.BoxWithConstraints@@ -89,6 +91,13 @@ fun LiquidBottomTabs(// leave a hard horizontal seam across the glass. Keep it below half the// height.lensDepth: Dp = 24f.dp,+ // LOCAL CHANGE: hides the moving capsule without moving it.+ //+ // The bar always has a selected index — it is what the indicator is drawn+ // at — but the app has screens that are none of the tabs, and on those the+ // indicator claimed the app was somewhere it was not. Faded rather than+ // removed, so it comes back where it left and the drag target stays alive.+ indicatorVisible: Boolean = true,content: @Composable RowScope.() -> Unit) {val isLightTheme = !isSystemInDarkTheme()@@ -258,10 +267,17 @@ fun LiquidBottomTabs()}+ val indicatorAlpha by animateFloatAsState(+ targetValue = if (indicatorVisible) 1f else 0f,+ animationSpec = tween(220),+ label = "indicatorAlpha",+ )+Box(Modifier.padding(horizontal = 4f.dp).graphicsLayer {+ alpha = indicatorAlphatranslationX =if (isLtr) dampedDragAnimation.value * tabWidth + panelOffsetelse size.width - (dampedDragAnimation.value + 1f) * tabWidth + panelOffsetdiff --git a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.ktindex 69a7e63..0dd8a6a 100644--- a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt@@ -54,6 +54,15 @@ import androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.lerpimport com.kyant.backdrop.Backdrop+import com.adamglin.PhosphorIcons+import com.adamglin.phosphoricons.Regular+import com.adamglin.phosphoricons.regular.SpotifyLogo+import com.adamglin.phosphoricons.regular.YoutubeLogo+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.material3.Iconimport dev.lelonio.square.Rimport dev.lelonio.square.data.CatalogPlaylistimport dev.lelonio.square.data.CatalogTrack@@ -118,7 +127,33 @@ fun HomeScreen(onOpenSettings: () -> Unit,/** The layer the glass on this page refracts; see the note in SquareApp. */backdrop: Backdrop,+ /**+ * True when the active source is YouTube Music.+ *+ * [state] describes the *Spotify* session, so on YouTube it is permanently+ * `LoggedOut` and this page would offer a login for an account the user+ * chose not to use. There is no account to log into here, so the page shows+ * what it genuinely has instead.+ */+ youtubeMode: Boolean = false,+ youtubeHome: MainViewModel.YouTubeHomeState = MainViewModel.YouTubeHomeState(),+ onPlayTrending: (List<CatalogTrack>, Int) -> Unit = { _, _ -> },) {+ if (youtubeMode) {+ YouTubeHome(+ contentPadding = contentPadding,+ home = youtubeHome,+ recent = recent,+ accountName = (state as? MainViewModel.UiState.Ready)?.displayName.orEmpty(),+ backdrop = backdrop,+ onPlayRecent = onPlayRecent,+ onPlayTrending = onPlayTrending,+ onOpenPlaylist = onOpenPlaylist,+ onOpenSettings = onOpenSettings,+ )+ return+ }+when (state) {MainViewModel.UiState.LoggedOut -> Centered {AppIcon(84.dp)@@ -191,6 +226,8 @@ fun HomeScreen(Header(name = state.displayName,avatarUrl = state.avatarUrl,+ service = R.string.backend_spotify,+ serviceIcon = PhosphorIcons.Regular.SpotifyLogo,collapse = { collapse },// The chip that is lit is the one that was tapped. It used// to follow whichever section the scroll had reached, which@@ -248,6 +285,18 @@ fun HomeScreen(// First on the page, and deliberately: what the account is// playing this month is the one row that is different every// time it is opened.+ // Every feed section keeps its place while it is still being+ // fetched. The account's playlists and its recent tracks are+ // held on the device and draw at once; everything else is a Web+ // API round trip a second or two behind, and without a+ // placeholder the page arrived in two halves and shifted under+ // whatever was being read.+ if (showForYou && feed.topTracks.isEmpty() && feed.loading) {+ item(contentType = "skeleton") {+ SkeletonSection(tileWidth = 152.dp, tileHeight = 152.dp)+ }+ }+if (showForYou && feed.topTracks.isNotEmpty()) {item(contentType = Feed.FOR_YOU.name) { Heading(stringResource(R.string.on_repeat)) }item(contentType = Feed.FOR_YOU.name) {@@ -257,6 +306,12 @@ fun HomeScreen(}}+ if (showForYou && feed.jumpBackIn.isEmpty() && feed.loading) {+ item(contentType = "skeleton") {+ SkeletonSection(tileWidth = 152.dp, tileHeight = 152.dp)+ }+ }+if (showForYou && feed.jumpBackIn.isNotEmpty()) {item(contentType = Feed.FOR_YOU.name) { Heading(stringResource(R.string.jump_back_in)) }item(contentType = Feed.FOR_YOU.name) {@@ -278,6 +333,12 @@ fun HomeScreen(}}+ if (showReleases && feed.newReleases.isEmpty() && feed.loading) {+ item(contentType = "skeleton") {+ SkeletonSection(tileWidth = 0.dp, tileHeight = 200.dp, card = true)+ }+ }+if (showReleases && feed.newReleases.isNotEmpty()) {item(contentType = Feed.RELEASES.name) { Heading(stringResource(R.string.feed_releases)) }// Cards rather than another row of thumbnails. A carousel@@ -305,6 +366,12 @@ fun HomeScreen(}}+ if (showArtists && feed.topArtists.isEmpty() && feed.loading) {+ item(contentType = "skeleton") {+ SkeletonSection(tileWidth = 120.dp, tileHeight = 120.dp, round = true)+ }+ }+if (showArtists && feed.topArtists.isNotEmpty()) {item(contentType = Feed.ARTISTS.name) { Heading(stringResource(R.string.listening_artists)) }item(contentType = Feed.ARTISTS.name) {@@ -358,8 +425,13 @@ fun HomeScreen(*/@Composableprivate fun Header(+ modifier: Modifier = Modifier,name: String,avatarUrl: String?,+ /** Which service the page is showing: see the note on the line it draws. */+ @StringRes service: Int,+ /** Its mark, so the source is recognisable before the line is read. */+ serviceIcon: androidx.compose.ui.graphics.vector.ImageVector,/*** How far collapsed, as a lambda rather than a value.*@@ -377,9 +449,17 @@ private fun Header(topPadding: Dp,onFilter: (Feed) -> Unit,onOpenSettings: () -> Unit,+ /**+ * False on a page with no feed to filter.+ *+ * The chips are the one part of this header that is Spotify's: they pick+ * between sections built out of that account's data, and YouTube's page is+ * whatever shelves the service itself sent.+ */+ showFilters: Boolean = true,) {Column(- Modifier+ modifier.fillMaxWidth()// Seats the header on the page instead of leaving it floating over// whatever the list has scrolled underneath it.@@ -407,30 +487,19 @@ private fun Header(verticalAlignment = Alignment.CenterVertically,) {Column(Modifier.weight(1f)) {- // What survives the collapse, along with the account picture.+ // The account, and which service it is an account for.//- // The account name is the greeting; the mark is what page you- // are on. Once the header is a bar, a bar carrying only a first- // name says nothing about where you are, so it is the name that- // leaves and the app that stays. It grows a little on the way- // in, since by then it is the only title on screen.- AppLockup(- iconSize = 26.dp,- nameHeight = 15.dp,- modifier = Modifier.graphicsLayer {- val scale = 1f + 0.1f * collapse()- scaleX = scale- scaleY = scale- transformOrigin = TransformOrigin(0f, 0.5f)- },- )- // Height goes with the alpha. Fading it alone would leave the- // bar the same size with a blank line in it.- Text(- name,- style = MaterialTheme.typography.displayLarge,- maxLines = 1,- overflow = TextOverflow.Ellipsis,+ // Small and above rather than large and below, which is where+ // the name used to be: whose account it is changes nothing about+ // the page, while *which service* changes everything on it — the+ // catalogue, the playlists, what the player can do — and that+ // was nowhere on screen. Together they read as one line of+ // provenance over the app's own name.+ //+ // Height goes with the alpha, so the collapsed header is a bar+ // rather than a bar with a blank line in it.+ Row(+ verticalAlignment = Alignment.CenterVertically,modifier = Modifier.layout { measurable, constraints ->val placeable = measurable.measure(constraints)@@ -440,10 +509,44 @@ private fun Header(.graphicsLayer {clip = truealpha = (1f - collapse() * 1.6f).coerceIn(0f, 1f)- // Anchored to the mark above it rather than sliding- // up from wherever it was.transformOrigin = TransformOrigin(0f, 0f)},+ ) {+ Icon(+ serviceIcon,+ contentDescription = stringResource(service),+ tint = InkDim,+ modifier = Modifier+ .padding(end = 6.dp)+ .size(15.dp),+ )+ Text(+ listOfNotNull(+ stringResource(service),+ name.takeIf { it.isNotBlank() },+ ).joinToString(" · "),+ style = MaterialTheme.typography.labelLarge,+ color = InkDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ // The app's own name, at the size the account name used to be.+ // It is what the page is, and unlike the account it is worth+ // reading at a glance; it shrinks a little as the header+ // collapses rather than leaving, because a bar with nothing in+ // it says nothing about where you are.+ AppLockup(+ iconSize = 34.dp,+ nameHeight = 22.dp,+ modifier = Modifier+ .padding(top = 4.dp)+ .graphicsLayer {+ val scale = 1f - 0.22f * collapse()+ scaleX = scale+ scaleY = scale+ transformOrigin = TransformOrigin(0f, 0.5f)+ },)}@@ -473,7 +576,9 @@ private fun Header()}- FilterRow(highlighted, backdrop, onFilter)+ // The chips carry the header's bottom margin with them; without them+ // the list would start against the app's own name.+ if (showFilters) FilterRow(highlighted, backdrop, onFilter) else Spacer(Modifier.height(16.dp))}}@@ -677,6 +782,65 @@ private fun TrackTile(track: CatalogTrack, onClick: () -> Unit) {}/** A row of tracks that play where they are tapped. */+/**+ * A section's shape, before the section has arrived.+ *+ * Deliberately still — no shimmer. A sweep across half the page draws the eye+ * to the part of it that has nothing to look at, and these are gone within a+ * second or two anyway. What they are for is the layout: holding the space+ * means the rows that land later land in the place they already occupied.+ */+@Composable+private fun SkeletonSection(+ tileWidth: Dp,+ tileHeight: Dp,+ round: Boolean = false,+ card: Boolean = false,+) {+ val fill = Ink.copy(alpha = 0.07f)+ Column(Modifier.padding(top = 22.dp)) {+ // Stands in for the heading.+ Box(+ Modifier+ .padding(horizontal = 20.dp)+ .width(140.dp)+ .height(20.dp)+ .clip(RoundedCornerShape(6.dp))+ .background(fill),+ )+ if (card) {+ Box(+ Modifier+ .padding(horizontal = 20.dp, vertical = 14.dp)+ .fillMaxWidth()+ .height(tileHeight)+ .clip(RoundedCornerShape(28.dp))+ .background(fill),+ )+ } else {+ Row(+ Modifier+ .padding(start = 20.dp, top = 14.dp)+ .fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ repeat(SKELETON_TILES) {+ Box(+ Modifier+ .width(tileWidth)+ .height(tileHeight)+ .clip(if (round) CircleShape else RoundedCornerShape(18.dp))+ .background(fill),+ )+ }+ }+ }+ }+}++/** Enough to reach the edge of the screen, which is all a placeholder row is. */+private const val SKELETON_TILES = 3+@Composableprivate fun TrackRow(tracks: List<CatalogTrack>, onPlay: (Int) -> Unit) {LazyRow(@@ -763,6 +927,188 @@ private fun GlassAction(label: String, backdrop: Backdrop, onClick: () -> Unit)}}+/**+ * The home page when the source is YouTube Music.+ *+ * Deliberately thin, and honestly so. Everything the Spotify home page is made+ * of — the playlists, the top artists, what the account played on other+ * devices — is an account's own data, and this backend is anonymous: there is+ * no account to have any of it. What does exist is what was played here, which+ * is kept on the device and works the same for both sources.+ *+ * So it shows that, and otherwise points at search rather than filling the+ * screen with rows invented to look busy.+ */+@Composable+private fun YouTubeHome(+ contentPadding: PaddingValues,+ home: MainViewModel.YouTubeHomeState,+ recent: List<CatalogTrack>,+ accountName: String,+ backdrop: Backdrop,+ onPlayRecent: (List<CatalogTrack>, Int) -> Unit,+ onPlayTrending: (List<CatalogTrack>, Int) -> Unit,+ onOpenPlaylist: (CatalogPlaylist) -> Unit,+ onOpenSettings: () -> Unit,+) {+ val empty = home.rows.isEmpty() && recent.isEmpty()+ if (empty) {+ Box(Modifier.fillMaxSize()) {+ Centered {+ if (home.loading) {+ CircularProgressIndicator(color = Ink, strokeWidth = 2.dp)+ } else {+ AppIcon(84.dp)+ SquareWordmark(height = 28.dp)+ Text(+ stringResource(R.string.youtube_home_empty),+ style = MaterialTheme.typography.bodyMedium,+ color = InkDim,+ textAlign = TextAlign.Center,+ modifier = Modifier.padding(horizontal = 40.dp),+ )+ }+ }+ // Over the empty state rather than above it: the settings are the+ // one thing still worth reaching from a page with nothing on it,+ // and signing in is done from there.+ YouTubeHeader(+ accountName = accountName,+ topPadding = contentPadding.calculateTopPadding(),+ backdrop = backdrop,+ // Nothing scrolls under it here, so it stays as it opens.+ collapse = { 0f },+ onOpenSettings = onOpenSettings,+ )+ }+ return+ }++ val listState = rememberLazyListState()+ // The same collapse the Spotify page has, read the same way; see the note+ // there. The header is a sibling of the list rather than its first item+ // precisely so it can shrink while the list scrolls under it.+ val collapse by remember {+ derivedStateOf {+ if (listState.firstVisibleItemIndex > 0) 1f+ else (listState.firstVisibleItemScrollOffset / COLLAPSE_DISTANCE_PX)+ .coerceIn(0f, 1f)+ }+ }++ Column(Modifier.fillMaxSize()) {+ YouTubeHeader(+ accountName = accountName,+ topPadding = contentPadding.calculateTopPadding(),+ backdrop = backdrop,+ collapse = { collapse },+ onOpenSettings = onOpenSettings,+ )++ LazyColumn(+ // The same fade the Spotify list has: the rows dissolve into the+ // header rather than ending against it. See the note there for why+ // the mask needs a layer of its own.+ modifier = Modifier+ .fillMaxSize()+ .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)+ .drawWithContent {+ drawContent()+ drawRect(+ brush = Brush.verticalGradient(+ 0f to Color.Transparent,+ FADE_FRACTION to Color.Black,+ ),+ blendMode = BlendMode.DstIn,+ )+ },+ state = listState,+ // The header owns the top of the page; what is left is the room the+ // player bar needs at the bottom.+ contentPadding = PaddingValues(+ bottom = contentPadding.calculateBottomPadding(),+ ),+ ) {+ // Whatever shelves YouTube sent, in its own order and under its own+ // titles. Not reshaped into a fixed set of rows: the page is different+ // signed in and signed out, and it changes on its own besides.+ home.rows.forEach { row ->+ item(key = "head-${row.title}") { Heading(row.title) }++ if (row.tracks.isNotEmpty()) {+ item(key = "tracks-${row.title}") {+ TrackRow(row.tracks) { index -> onPlayTrending(row.tracks, index) }+ }+ }++ if (row.items.isNotEmpty()) {+ item(key = "items-${row.title}") {+ LazyRow(+ contentPadding = PaddingValues(horizontal = 20.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ modifier = Modifier.padding(top = 14.dp),+ ) {+ items(row.items, key = { it.uri }) { entry ->+ PlaylistTile(entry) { onOpenPlaylist(entry) }+ }+ }+ }+ }+ }++ // Last: the rows above change on their own, this one only changes+ // because the user did something.+ if (recent.isNotEmpty()) {+ item(key = "recent-head") { Heading(stringResource(R.string.play_again)) }+ item(key = "recent") {+ LazyRow(+ contentPadding = PaddingValues(horizontal = 20.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ modifier = Modifier.padding(top = 14.dp),+ ) {+ itemsIndexed(recent, key = { _, track -> track.uri }) { index, track ->+ TrackTile(track) { onPlayRecent(recent, index) }+ }+ }+ }+ }+ }+ }+}++/**+ * The YouTube page's header.+ *+ * Far plainer than [Header]: that one carries the feed's filter chips and a+ * collapse driven by the scroll, and neither has anything to act on here —+ * there are no feed sections to filter. What it must keep is the way into the+ * settings, because that is the only one there is; the app has no settings tab.+ */+@Composable+private fun YouTubeHeader(+ accountName: String,+ topPadding: Dp,+ backdrop: Backdrop,+ collapse: () -> Float,+ onOpenSettings: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Header(+ modifier = modifier,+ name = accountName,+ avatarUrl = null,+ service = R.string.backend_youtube,+ serviceIcon = PhosphorIcons.Regular.YoutubeLogo,+ collapse = collapse,+ highlighted = Feed.entries.first(),+ backdrop = backdrop,+ topPadding = topPadding,+ onFilter = {},+ onOpenSettings = onOpenSettings,+ showFilters = false,+ )+}+@Composableprivate fun Centered(content: @Composable () -> Unit) {Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.ktindex fcefcc5..a82252f 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt@@ -2,6 +2,7 @@ package dev.lelonio.square.ui.libraryimport androidx.annotation.StringResimport androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -50,6 +51,7 @@ import dev.lelonio.square.ui.theme.softShadowimport com.adamglin.PhosphorIconsimport com.adamglin.phosphoricons.Regularimport com.adamglin.phosphoricons.regular.ListBullets+import com.adamglin.phosphoricons.regular.Plusimport com.adamglin.phosphoricons.regular.SquaresFour/** How the playlists are arranged. */@@ -81,6 +83,11 @@ fun LibraryScreen(onOpenPlaylist: (CatalogPlaylist) -> Unit,/** URIs most recently opened first; see PlaylistOrderStore. */playlistOrder: List<String>,+ /** False when the source cannot be written to; see MusicBackend. */+ canEdit: Boolean = false,+ onCreatePlaylist: () -> Unit = {},+ /** Long press: rename and delete live in a sheet, like a track's actions. */+ onPlaylistMenu: (CatalogPlaylist) -> Unit = {},backdrop: Backdrop,) {when (state) {@@ -139,6 +146,8 @@ fun LibraryScreen(topPadding = contentPadding.calculateTopPadding(),onLayout = { layout = it },onOrder = { order = it },+ canEdit = canEdit,+ onCreatePlaylist = onCreatePlaylist,)val listPadding = PaddingValues(@@ -157,7 +166,15 @@ fun LibraryScreen(modifier = Modifier.fillMaxSize(),) {items(playlists, key = { it.uri }) { playlist ->- GridTile(playlist) { onOpenPlaylist(playlist) }+ GridTile(+ playlist,+ onClick = { onOpenPlaylist(playlist) },+ onLongClick = if (canEdit) {+ { onPlaylistMenu(playlist) }+ } else {+ null+ },+ )}}@@ -167,7 +184,15 @@ fun LibraryScreen(modifier = Modifier.fillMaxSize(),) {items(playlists, key = { it.uri }) { playlist ->- ListRow(playlist) { onOpenPlaylist(playlist) }+ ListRow(+ playlist,+ onClick = { onOpenPlaylist(playlist) },+ onLongClick = if (canEdit) {+ { onPlaylistMenu(playlist) }+ } else {+ null+ },+ )}}}@@ -185,6 +210,8 @@ private fun Header(topPadding: Dp,onLayout: (Layout) -> Unit,onOrder: (Order) -> Unit,+ canEdit: Boolean,+ onCreatePlaylist: () -> Unit,) {Column(Modifier@@ -206,6 +233,30 @@ private fun Header()}+ // Only where a playlist can actually be made: on a source with no+ // account signed in, a plus that always failed would be worse than+ // no plus at all.+ if (canEdit) {+ LiquidButton(+ onClick = onCreatePlaylist,+ backdrop = backdrop,+ modifier = Modifier+ .padding(end = 8.dp)+ .size(42.dp),+ contentHeight = 42.dp,+ contentPadding = 0.dp,+ blurRadius = 8.dp,+ surfaceColor = GlassFilm,+ ) {+ Icon(+ PhosphorIcons.Regular.Plus,+ contentDescription = stringResource(R.string.new_playlist),+ tint = Ink,+ modifier = Modifier.size(20.dp),+ )+ }+ }+// One button that swaps between the two arrangements rather than a// pair of them: with two options, a toggle showing the *other* one// is both smaller and unambiguous.@@ -259,8 +310,14 @@ private fun Header(}@Composable-private fun GridTile(playlist: CatalogPlaylist, onClick: () -> Unit) {- Column(Modifier.clickable(onClick = onClick)) {+private fun GridTile(+ playlist: CatalogPlaylist,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)?,+) {+ Column(+ Modifier.combinedClickable(onClick = onClick, onLongClick = onLongClick),+ ) {Artwork(url = playlist.artworkUrl,title = playlist.name,@@ -282,12 +339,16 @@ private fun GridTile(playlist: CatalogPlaylist, onClick: () -> Unit) {}@Composable-private fun ListRow(playlist: CatalogPlaylist, onClick: () -> Unit) {+private fun ListRow(+ playlist: CatalogPlaylist,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)?,+) {Row(Modifier.fillMaxWidth().clip(RoundedCornerShape(16.dp))- .clickable(onClick = onClick)+ .combinedClickable(onClick = onClick, onLongClick = onLongClick).padding(vertical = 8.dp),verticalAlignment = Alignment.CenterVertically,) {diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.ktindex 312384c..57addba 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt@@ -963,9 +963,20 @@ private fun TrackRow(* app to do. No "go to album" — the track model carries the album's name for* display and not its URI, so the entry would be there and not work.*/-/** The web address for a track URI, which is what a share expects. */-fun CatalogTrack.openLink(): String =- "https://open.spotify.com/track/" + uri.substringAfterLast(':')+/**+ * The web address for a track URI, which is what a share expects.+ *+ * Whichever service the track came from: sharing a YouTube track as a Spotify+ * link would point at something that is not the same recording, or at nothing.+ */+fun CatalogTrack.openLink(): String {+ val id = uri.substringAfterLast(':')+ return if (uri.startsWith("ytmusic:")) {+ "https://music.youtube.com/watch?v=$id"+ } else {+ "https://open.spotify.com/track/$id"+ }+}@Composableprivate fun StatusBox(content: @Composable () -> Unit) {diff --git a/app/src/main/java/dev/lelonio/square/ui/onboarding/BackendChoiceScreen.kt b/app/src/main/java/dev/lelonio/square/ui/onboarding/BackendChoiceScreen.ktnew file mode 100644index 0000000..02a4474--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/onboarding/BackendChoiceScreen.kt@@ -0,0 +1,139 @@+package dev.lelonio.square.ui.onboarding++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBars+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import dev.lelonio.square.R+import dev.lelonio.square.backend.BackendId+import dev.lelonio.square.ui.components.SquareWordmark+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDim++/**+ * The first question a fresh install asks: where the music comes from.+ *+ * Ahead of the tutorial, and that order is the point. The whole setup the+ * tutorial walks through — the Spotify login, the registered Web API+ * application, the redirect URI — exists only for Spotify. Asking someone to+ * do all of it and *then* telling them there was another option that needs none+ * of it would be asking them to redo the decision after paying for it.+ *+ * Shown once. Changing the answer later lives in the settings, where a choice+ * that restarts playback belongs.+ */+@Composable+fun BackendChoiceScreen(onChoose: (BackendId) -> Unit) {+ val statusBar = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()+ val navBar = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()++ Box(+ Modifier+ .fillMaxSize()+ // Opaque, like the tutorial it precedes: there is nothing behind+ // this worth showing through, and glass over an unconfigured home+ // page would be showing the user the problem, not the choice.+ .background(Color(0xFF101012))+ .clickable(interactionSource = null, indication = null) {},+ ) {+ Column(+ Modifier+ .fillMaxSize()+ .padding(top = statusBar + 24.dp, bottom = navBar + 24.dp)+ .padding(horizontal = 24.dp),+ verticalArrangement = Arrangement.Center,+ ) {+ SquareWordmark(height = 22.dp, modifier = Modifier.padding(bottom = 28.dp))++ Text(+ stringResource(R.string.backend_choice_title),+ style = MaterialTheme.typography.displayLarge,+ color = Ink,+ )+ Spacer(Modifier.height(10.dp))+ Text(+ stringResource(R.string.backend_choice_subtitle),+ style = MaterialTheme.typography.bodyMedium,+ color = InkDim,+ )++ Spacer(Modifier.height(32.dp))++ SourceCard(+ title = stringResource(R.string.backend_spotify),+ description = stringResource(R.string.backend_choice_spotify_note),+ onClick = { onChoose(BackendId.SPOTIFY) },+ )+ Spacer(Modifier.height(14.dp))+ SourceCard(+ title = stringResource(R.string.backend_youtube),+ description = stringResource(R.string.backend_choice_youtube_note),+ onClick = { onChoose(BackendId.YOUTUBE_MUSIC) },+ )++ Spacer(Modifier.height(24.dp))+ Text(+ stringResource(R.string.backend_choice_changeable),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ modifier = Modifier.fillMaxWidth(),+ )+ }+ }+}++/**+ * One of the two answers.+ *+ * A card rather than a radio row: this is the only thing on screen and there is+ * no "confirm" — tapping one *is* the answer, so each needs enough room to say+ * what picking it means before it is picked.+ */+@Composable+private fun SourceCard(title: String, description: String, onClick: () -> Unit) {+ val shape = RoundedCornerShape(20.dp)+ Column(+ Modifier+ .fillMaxWidth()+ .clip(shape)+ .background(Color(0xFF1A1A1E))+ .border(1.dp, Color(0x1AFFFFFF), shape)+ .clickable(onClick = onClick)+ .padding(horizontal = 20.dp, vertical = 18.dp),+ ) {+ Text(+ title,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.Bold,+ color = Ink,+ )+ Spacer(Modifier.height(6.dp))+ Text(+ description,+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ )+ }+}diff --git a/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt b/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.ktindex 9bfbd8e..28f4c92 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/MiniPlayer.kt@@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.LinearProgressIndicator@@ -215,17 +216,27 @@ fun MiniPlayer(contentPadding = 0.dp,modifier = Modifier.size(42.dp),) {- Crossfade(- state.isPlaying,- animationSpec = tween(180),- label = "playPause",- ) { playing ->- Icon(- imageVector = if (playing) PhosphorIcons.Fill.Pause else PhosphorIcons.Fill.Play,- contentDescription = if (playing) stringResource(R.string.pause) else stringResource(R.string.play),- tint = MiniPlayerInk,- modifier = Modifier.size(20.dp),- )+ // Same ring as the player's; see the note there.+ Box(contentAlignment = Alignment.Center) {+ if (state.isBuffering) {+ CircularProgressIndicator(+ color = MiniPlayerInk.copy(alpha = 0.5f),+ strokeWidth = 1.5.dp,+ modifier = Modifier.size(30.dp),+ )+ }+ Crossfade(+ state.isPlaying,+ animationSpec = tween(180),+ label = "playPause",+ ) { playing ->+ Icon(+ imageVector = if (playing) PhosphorIcons.Fill.Pause else PhosphorIcons.Fill.Play,+ contentDescription = if (playing) stringResource(R.string.pause) else stringResource(R.string.play),+ tint = MiniPlayerInk,+ modifier = Modifier.size(20.dp),+ )+ }}}}diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.ktindex ec7d5e5..8e3d8ee 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerPanel.kt@@ -439,6 +439,17 @@ private fun EffectSlider(onChange: (Float) -> Unit,onReset: () -> Unit,) {+ // What the thumb shows while the player has not caught up yet.+ //+ // The player is told the new value only once the drag settles — writing it+ // every frame starves the audio output — so between the two the slider has+ // to speak for itself, or it springs back under the finger.+ var dragged by remember { mutableStateOf<Float?>(null) }+ val shown = dragged ?: value+ LaunchedEffect(value) {+ if (dragged != null && kotlin.math.abs(value - dragged!!) < 0.0005f) dragged = null+ }+Column(Modifier.padding(top = 6.dp)) {Row(verticalAlignment = Alignment.CenterVertically) {Text(@@ -462,8 +473,11 @@ private fun EffectSlider()}LiquidSlider(- value = { value },- onValueChange = onChange,+ value = { shown },+ onValueChange = {+ dragged = it+ onChange(it)+ },valueRange = range,// The smallest step worth animating to. Below this the thumb chases// values the ear cannot tell apart.diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.ktindex 7e235f7..fefca37 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerScreen.kt@@ -33,6 +33,7 @@ import androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.systemBarsPaddingimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.LocalContentColor@@ -40,11 +41,16 @@ import androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.animation.animateColorAsState+import androidx.compose.foundation.Canvas+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.Stateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.mutableFloatStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -84,6 +90,7 @@ import com.adamglin.phosphoricons.regular.CaretDownimport com.adamglin.phosphoricons.regular.Devicesimport com.adamglin.phosphoricons.regular.Plusimport com.adamglin.phosphoricons.regular.Queue+import com.adamglin.phosphoricons.regular.YoutubeLogoimport com.adamglin.phosphoricons.regular.Repeatimport com.adamglin.phosphoricons.regular.RepeatOnceimport com.adamglin.phosphoricons.regular.Shuffle@@ -117,7 +124,7 @@ private const val PAUSED_DIM = 0.55f* back here as a full-bleed backdrop.*//** What occupies the middle of the player. */-private enum class Stage { COVER, LYRICS, EFFECTS, QUEUE, DEVICES, ADD_TO_PLAYLIST, CANVAS }+private enum class Stage { COVER, LYRICS, EFFECTS, QUEUE, DEVICES, ADD_TO_PLAYLIST, CANVAS, VIDEO }@UnstableApi@Composable@@ -172,6 +179,33 @@ fun PlayerScreen(/** The playlist picker's state, shown in the panel rather than as a sheet. */addToPlaylist: MainViewModel.AddToPlaylistState,onPickPlaylist: (dev.lelonio.square.data.CatalogPlaylist) -> Unit,+ /**+ * False when the source has no writable playlists.+ *+ * Adding a track to a playlist goes through the Spotify Web API; on another+ * source the button could only open a picker that fails on every choice.+ */+ playlistEditAvailable: Boolean = true,+ /**+ * Turns the current track's video on or off, or null when it has none.+ *+ * The same track either way — the source reopens on the muxed stream, which+ * carries the picture along with the sound — so the queue, the position and+ * everything else stay as they were.+ */+ onWatchVideo: (() -> Unit)? = null,+ /** Showing the picture right now. */+ videoOn: Boolean = false,+ /** The player to hang the video surface off; null when there is no video. */+ videoPlayer: Player? = null,+ /**+ * False when the source is not Spotify.+ *+ * Connect is Spotify's own protocol for handing playback to another+ * speaker; on any other source the button would open a list that can only+ * ever be empty, so it is not drawn at all.+ */+ connectAvailable: Boolean = true,) {var panel by remember { mutableStateOf(PlayerPanel.NONE) }@@ -211,6 +245,13 @@ fun PlayerScreen(label = "canvasBlur",)+ // The video's own light, sampled by the stage below and spread over the+ // whole screen from here — the way an ambient television lights the wall+ // behind it rather than just its own frame. Null whenever no video is+ // showing, which is what puts the ordinary backdrop back.+ var ambient by remember { mutableStateOf<AmbientEdges?>(null) }+ LaunchedEffect(videoOn) { if (!videoOn) ambient = null }+Box(Modifier.fillMaxSize()) {Box(Modifier@@ -233,6 +274,12 @@ fun PlayerScreen(}.layerBackdrop(canvasBackdrop),) {+ // Inside the recorded layer, and that is the point: the glass above+ // samples this backdrop, so light drawn here is light the buttons+ // and the panels refract. Drawn outside it they sat on top of the+ // colour without ever picking any of it up.+ AmbientLight(ambient)+// Held at zero until the first frame, then faded up. Without this// the clip's own surface appears the instant it decodes, which next// to a cover crossfading out reads as two separate events.@@ -347,6 +394,9 @@ fun PlayerScreen(PlayerPanel.DEVICES}},+ connectAvailable = connectAvailable,+ onWatchVideo = onWatchVideo,+ videoOn = videoOn,)// Everything sits at the bottom, as in the reference: the@@ -388,12 +438,20 @@ fun PlayerScreen(PlayerPanel.QUEUE -> Stage.QUEUEPlayerPanel.DEVICES -> Stage.DEVICESPlayerPanel.ADD_TO_PLAYLIST -> Stage.ADD_TO_PLAYLIST- PlayerPanel.NONE ->- if (canvas == null || !canvasReady) {- Stage.COVER- } else {- Stage.CANVAS- }+ PlayerPanel.NONE -> when {+ // Not while the player is travelling: a+ // TextureView inside a layer being scaled+ // and faded loses its surface for the length+ // of the animation and leaves a black+ // rectangle sliding down the screen. The+ // cover stands in for those few hundred+ // milliseconds — the same trick the Canvas+ // above uses, and for the same reason.+ videoOn && videoPlayer != null &&+ LocalGlassEnabled.current -> Stage.VIDEO+ canvas == null || !canvasReady -> Stage.COVER+ else -> Stage.CANVAS+ }},animationSpec = tween(320),label = "stage",@@ -414,6 +472,23 @@ fun PlayerScreen()}+ // The picture in the cover's place rather than+ // behind the glass like a Canvas: this one is+ // the thing being watched, so it gets the slot+ // and keeps its own shape inside it.+ Stage.VIDEO -> Box(+ Modifier.fillMaxSize(),+ contentAlignment = Alignment.Center,+ ) {+ // Nullable even in this stage: the crossfade+ // keeps drawing the one it is leaving, and+ // the controller it holds is gone the moment+ // the activity stops.+ videoPlayer?.let {+ VideoStage(it) { ambient = it }+ }+ }+Stage.LYRICS -> LyricsStage(lyrics = lyrics,loading = lyricsLoading,@@ -539,6 +614,7 @@ fun PlayerScreen(modifier = Modifier.size(20.dp),)}+ if (playlistEditAvailable) {Spacer(Modifier.size(8.dp))RoundGlassButton(backdrop = glassBackdrop,@@ -559,6 +635,7 @@ fun PlayerScreen(modifier = Modifier.size(20.dp),)}+ }}}@@ -618,6 +695,162 @@ fun PlayerScreen(}}+/**+ * The video, on a surface the player draws straight into.+ *+ * A `SurfaceView` rather than a `TextureView`: the player writes to it without+ * the frame ever passing through the view hierarchy, which is what keeps a+ * 720p stream from costing anything on the UI thread. The surface is handed+ * back on the way out, or the player would go on rendering into a dead one.+ */+@Composable+private fun VideoStage(player: Player, onAmbient: (AmbientEdges) -> Unit) {+ val context = androidx.compose.ui.platform.LocalContext.current+ // A TextureView rather than the SurfaceView the floating window uses: only+ // a texture can be read back, and reading the picture back is the whole+ // ambient effect — the glow is the video's own colour, not a guess made+ // from the cover.+ val texture = remember(context) { android.view.TextureView(context) }+ DisposableEffect(player, texture) {+ player.setVideoTextureView(texture)+ onDispose { player.clearVideoTextureView(texture) }+ }++ val report by rememberUpdatedState(onAmbient)+ LaunchedEffect(texture, player) {+ while (true) {+ // Slowly, off a thumbnail. Reading the whole picture back at frame+ // rate would cost far more than it shows, and a glow that tracked+ // every cut would strobe: this is meant to be light in the room, and+ // light in a room does not flicker.+ kotlinx.coroutines.delay(AMBIENT_INTERVAL_MS)+ if (!texture.isAvailable) continue+ val frame = runCatching {+ texture.getBitmap(AMBIENT_SAMPLE, AMBIENT_SAMPLE)+ }.getOrNull() ?: continue+ report(frame.edges())+ frame.recycle()+ }+ }++ androidx.compose.ui.viewinterop.AndroidView(+ factory = { texture },+ modifier = Modifier+ .fillMaxWidth()+ .aspectRatio(16f / 9f)+ .clip(RoundedCornerShape(18.dp)),+ )+}++/**+ * The sampled colour, over the whole screen.+ *+ * Each corner eased into its new value over seconds rather than frames: the+ * point is the colour of the scene, and a scene lasts. Drawn under everything,+ * so the glass above it refracts the light the same way it refracts artwork.+ */+@Composable+private fun AmbientLight(edges: AmbientEdges?) {+ val topLeft by animateColorAsState(+ edges?.topLeft ?: Color.Transparent, tween(AMBIENT_FADE_MS), label = "tl",+ )+ val topRight by animateColorAsState(+ edges?.topRight ?: Color.Transparent, tween(AMBIENT_FADE_MS), label = "tr",+ )+ val bottomLeft by animateColorAsState(+ edges?.bottomLeft ?: Color.Transparent, tween(AMBIENT_FADE_MS), label = "bl",+ )+ val bottomRight by animateColorAsState(+ edges?.bottomRight ?: Color.Transparent, tween(AMBIENT_FADE_MS), label = "br",+ )++ Canvas(Modifier.fillMaxSize()) {+ // One soft glow per corner rather than two bands across the screen.+ //+ // Bands meet along a line, and a line is exactly what light does not+ // have: the first version left a visible seam across the middle of the+ // screen. Radial gradients reaching past each other have no edge to+ // show, which is also what the lamps behind an ambient television+ // actually do.+ val radius = size.maxDimension * 0.9f+ listOf(+ topLeft to androidx.compose.ui.geometry.Offset(0f, 0f),+ topRight to androidx.compose.ui.geometry.Offset(size.width, 0f),+ bottomLeft to androidx.compose.ui.geometry.Offset(0f, size.height),+ bottomRight to androidx.compose.ui.geometry.Offset(size.width, size.height),+ ).forEach { (color, center) ->+ drawRect(+ Brush.radialGradient(+ listOf(color, color.copy(alpha = 0f)),+ center = center,+ radius = radius,+ ),+ )+ }+ }+}++/** The colour of each corner of a frame, which is what the glow is made of. */+private data class AmbientEdges(+ val topLeft: Color,+ val topRight: Color,+ val bottomLeft: Color,+ val bottomRight: Color,+)++/**+ * Averages each quadrant of the thumbnail.+ *+ * Quadrants rather than single pixels: one pixel of a dark scene with a bright+ * speck in it would swing the whole glow, and the average is what a wall+ * actually reflects.+ */+private fun android.graphics.Bitmap.edges(): AmbientEdges {+ val half = AMBIENT_SAMPLE / 2+ fun quadrant(x0: Int, y0: Int): Color {+ var r = 0L+ var g = 0L+ var b = 0L+ for (x in x0 until x0 + half) {+ for (y in y0 until y0 + half) {+ val pixel = getPixel(x, y)+ r += android.graphics.Color.red(pixel)+ g += android.graphics.Color.green(pixel)+ b += android.graphics.Color.blue(pixel)+ }+ }+ val count = (half * half).toFloat()+ return Color(r / count / 255f, g / count / 255f, b / count / 255f)+ }+ return AmbientEdges(+ topLeft = quadrant(0, 0),+ topRight = quadrant(half, 0),+ bottomLeft = quadrant(0, half),+ bottomRight = quadrant(half, half),+ )+}++/** How often the picture is read back, in milliseconds. */+private const val AMBIENT_INTERVAL_MS = 900L++/** How long a colour takes to become the next one. */+private const val AMBIENT_FADE_MS = 2500++/** Side of the thumbnail each sample is taken from. */+private const val AMBIENT_SAMPLE = 16++/** The surface itself, shared with the floating window; see [VideoStage]. */+@Composable+fun VideoSurface(player: Player, modifier: Modifier = Modifier) {+ val context = androidx.compose.ui.platform.LocalContext.current+ val surface = remember(context) { android.view.SurfaceView(context) }+ DisposableEffect(player, surface) {+ player.setVideoSurfaceView(surface)+ onDispose { player.clearVideoSurfaceView(surface) }+ }+ androidx.compose.ui.viewinterop.AndroidView(factory = { surface }, modifier = modifier)+}+@Composableprivate fun TopBar(backdrop: Backdrop,@@ -626,6 +859,10 @@ private fun TopBar(source: String,onCollapse: () -> Unit,onOpenDevices: () -> Unit,+ connectAvailable: Boolean,+ /** Null when the track has no video to watch. */+ onWatchVideo: (() -> Unit)?,+ videoOn: Boolean,) {Row(Modifier@@ -666,12 +903,28 @@ private fun TopBar(// Connect gets the permanent slot rather than hiding behind "more":// moving playback to another speaker is the thing you reach for while// the player is open, and the queue already has its own tab below.- GlassButton(backdrop, onClick = onOpenDevices) {- Icon(- PhosphorIcons.Regular.Devices,- contentDescription = stringResource(R.string.devices),- tint = panelTint(panel == PlayerPanel.DEVICES),- )+ // Every YouTube Music track is a video underneath, and switching to it+ // is the thing this app cannot do itself — so it hands the track over+ // at the position it had reached rather than pretending otherwise.+ if (onWatchVideo != null) {+ GlassButton(backdrop, onClick = onWatchVideo) {+ Icon(+ PhosphorIcons.Regular.YoutubeLogo,+ contentDescription = stringResource(R.string.watch_video),+ // Lit while the video is on, like every other button here+ // that opens something: it is a switch, not a one-way trip.+ tint = panelTint(videoOn),+ )+ }+ }+ if (connectAvailable) {+ GlassButton(backdrop, onClick = onOpenDevices) {+ Icon(+ PhosphorIcons.Regular.Devices,+ contentDescription = stringResource(R.string.devices),+ tint = panelTint(panel == PlayerPanel.DEVICES),+ )+ }}}@@ -838,16 +1091,34 @@ private fun Controls(}RoundGlassButton(backdrop = backdrop, size = 76.dp, onClick = onTogglePlay) {- Crossfade(- state.isPlaying,- animationSpec = tween(180),- label = "playPause",- ) { playing ->- Icon(- imageVector = if (playing) PhosphorIcons.Fill.Pause else PhosphorIcons.Fill.Play,- contentDescription = stringResource(if (playing) R.string.pause else R.string.play),- modifier = Modifier.size(34.dp),- )+ // A ring around the icon while the track is still being fetched.+ //+ // Worth its place here and nowhere else: a YouTube track has to have+ // its stream resolved before a single byte can be read, which takes+ // long enough that a tap on play looks like it did nothing at all.+ // Around the button rather than in place of it, so the control stays+ // where it is and stays pressable.+ // A Box, because the button lays its content out in a row and the+ // ring belongs *around* the icon rather than beside it.+ Box(contentAlignment = Alignment.Center) {+ if (state.isBuffering) {+ CircularProgressIndicator(+ color = LocalContentColor.current.copy(alpha = 0.5f),+ strokeWidth = 2.dp,+ modifier = Modifier.size(52.dp),+ )+ }+ Crossfade(+ state.isPlaying,+ animationSpec = tween(180),+ label = "playPause",+ ) { playing ->+ Icon(+ imageVector = if (playing) PhosphorIcons.Fill.Pause else PhosphorIcons.Fill.Play,+ contentDescription = stringResource(if (playing) R.string.pause else R.string.play),+ modifier = Modifier.size(34.dp),+ )+ }}}diff --git a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.ktindex a5557a3..3caeb7c 100644--- a/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt+++ b/app/src/main/java/dev/lelonio/square/ui/player/PlayerState.kt@@ -50,14 +50,31 @@ data class PlaybackState(/** Mirrors the slow-changing part of a [Player] into Compose state. */@Composable-fun rememberPlaybackState(player: Player?): State<PlaybackState> {- val state = remember { mutableStateOf(PlaybackState()) }+fun rememberPlaybackState(+ player: Player?,+ /**+ * What to report until the media controller connects.+ *+ * Connecting takes a few hundred milliseconds, and the whole player is left+ * uncomposed while there is no item, so without this the app came back from+ * the launcher showing the home page underneath until the controller+ * landed. Read from the saved session, which already holds the track.+ */+ seed: PlaybackState? = null,+): State<PlaybackState> {+ val state = remember { mutableStateOf(seed ?: PlaybackState()) }+ // Whether a live player has ever answered. Once one has, the saved session+ // is out of date by definition — going back to it when the controller drops+ // is what made the player flash the previous track on the way back into the+ // app.+ val seenLive = remember { mutableStateOf(false) }DisposableEffect(player) {if (player == null) {- state.value = PlaybackState()+ if (!seenLive.value) state.value = seed ?: PlaybackState()return@DisposableEffect onDispose {}}+ seenLive.value = truefun snapshot() {val metadata = player.mediaMetadatadiff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.ktindex 4372402..e10ae86 100644--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt@@ -1,7 +1,9 @@package dev.lelonio.square.ui.searchimport androidx.annotation.StringRes+import androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.PaddingValues@@ -13,45 +15,65 @@ import androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyRowimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Icon-import androidx.compose.material3.IconButtonimport androidx.compose.material3.MaterialTheme-import androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Text-import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipimport androidx.compose.ui.res.stringResource-import androidx.compose.ui.platform.LocalClipboardManager-import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp+import com.kyant.backdrop.Backdropimport dev.lelonio.square.Rimport dev.lelonio.square.data.CatalogTrackimport dev.lelonio.square.data.SearchItemimport dev.lelonio.square.ui.MainViewModelimport dev.lelonio.square.ui.components.Artwork-import com.kyant.backdrop.Backdropimport dev.lelonio.square.ui.components.SwipeToQueueimport dev.lelonio.square.ui.glass.LiquidButton+import dev.lelonio.square.ui.player.GlassFilmimport dev.lelonio.square.ui.settings.WebApiSetup+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDimimport com.adamglin.PhosphorIconsimport com.adamglin.phosphoricons.Fillimport com.adamglin.phosphoricons.Regularimport com.adamglin.phosphoricons.fill.MagnifyingGlass+import com.adamglin.phosphoricons.regular.DotsThreeimport com.adamglin.phosphoricons.regular.X+/** Which kind of result the page is showing. */+private enum class Kind(@StringRes val label: Int) {+ ALL(R.string.feed_all),+ TRACKS(R.string.tracks),+ ARTISTS(R.string.artists),+ ALBUMS(R.string.albums),+ PLAYLISTS(R.string.playlists),+}+/*** Search across tracks, artists, albums and playlists.*- * Tracks come first and get the most room: looking for a song is what this box- * is mostly used for, and putting artists above them would make the common case- * the one that needs scrolling.+ * The page opens on the best of each kind rather than on every track the+ * service returned: a search is answered by the first few rows or not at all,+ * and the twenty below them only ever made the artist you were actually after+ * something to scroll past. The chips are how you ask for the rest, and they+ * are the same control the home page uses for the same purpose.*/@Composablefun SearchScreen(@@ -64,79 +86,63 @@ fun SearchScreen(onConnectWebApi: () -> Unit,onPlayTrack: (List<CatalogTrack>, Int) -> Unit,onEnqueue: (CatalogTrack) -> Unit,+ /** Opens the same track sheet the library rows open. */+ onTrackMenu: (CatalogTrack) -> Unit,onOpenContext: (SearchItem) -> Unit,backdrop: Backdrop,) {+ var kind by remember { mutableStateOf(Kind.ALL) }+ // A new search answers a new question, so the page goes back to showing all+ // of the answer rather than staying filtered to what the last one was about.+ val query = state.query+ remember(query) { kind = Kind.ALL }+LazyColumn(Modifier.fillMaxSize(), contentPadding = contentPadding) {item(contentType = "field") {- Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 36.dp, bottom = 10.dp)) {+ Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 36.dp)) {Text(stringResource(R.string.search), style = MaterialTheme.typography.displayLarge)- OutlinedTextField(+ SearchField(+ query = state.query,enabled = !state.needsSetup,- value = state.query,- onValueChange = onQueryChange,- placeholder = { Text(stringResource(R.string.search_placeholder)) },- singleLine = true,- leadingIcon = { Icon(PhosphorIcons.Fill.MagnifyingGlass, contentDescription = null) },- trailingIcon = {- if (state.query.isNotEmpty()) {- IconButton(onClick = { onQueryChange("") }) {- Icon(PhosphorIcons.Regular.X, contentDescription = stringResource(R.string.clear))- }- }- },- shape = RoundedCornerShape(16.dp),- modifier = Modifier- .fillMaxWidth()- .padding(top = 16.dp),+ backdrop = backdrop,+ onQueryChange = onQueryChange,)}}+ if (!state.results.isEmpty && !state.loading) {+ item(contentType = "chips") {+ KindRow(kind, backdrop) { kind = it }+ }+ }+when {state.needsSetup -> item(contentType = "setup") {WebApiSetup(webApi, backdrop, onClientIdChange, onConnectWebApi)}state.loading -> item(contentType = "status") {- StatusBox { CircularProgressIndicator(strokeWidth = 2.dp) }+ StatusBox { CircularProgressIndicator(color = Ink, strokeWidth = 2.dp) }}state.error != null -> item(contentType = "status") {- StatusBox {- Text(- state.error,- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- textAlign = TextAlign.Center,- )- }+ StatusBox { Message(state.error) }}state.query.isBlank() -> item(contentType = "status") {- StatusBox {- Text(- stringResource(R.string.search_prompt),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }+ StatusBox { Message(stringResource(R.string.search_prompt)) }}state.results.isEmpty -> item(contentType = "status") {- StatusBox {- Text(- stringResource(R.string.no_results_for, state.query),- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- textAlign = TextAlign.Center,- )- }+ StatusBox { Message(stringResource(R.string.no_results_for, state.query)) }}else -> {+ val all = kind == Kind.ALLval tracks = state.results.tracks- if (tracks.isNotEmpty()) {+ .let { if (all) it.take(TOP_RESULTS) else it }++ if ((all || kind == Kind.TRACKS) && tracks.isNotEmpty()) {item(contentType = "section") { SectionTitle(stringResource(R.string.tracks)) }items(count = tracks.size,@@ -152,14 +158,124 @@ fun SearchScreen(highlighted = track.uri == nowPlayingUri,round = false,onClick = { onPlayTrack(tracks, index) },+ // Only tracks have one: an artist row opens a+ // page, and there is nothing to queue, add or+ // share about it that the page does not do+ // better.+ onMenu = { onTrackMenu(track) },)}}}- section(R.string.artists, state.results.artists, round = true, onOpenContext)- section(R.string.albums, state.results.albums, round = false, onOpenContext)- section(R.string.playlists, state.results.playlists, round = false, onOpenContext)+ if (all || kind == Kind.ARTISTS) {+ section(R.string.artists, state.results.artists, all, round = true, onOpenContext)+ }+ if (all || kind == Kind.ALBUMS) {+ section(R.string.albums, state.results.albums, all, round = false, onOpenContext)+ }+ if (all || kind == Kind.PLAYLISTS) {+ section(R.string.playlists, state.results.playlists, all, round = false, onOpenContext)+ }++ item(contentType = "tail") { Box(Modifier.height(24.dp)) }+ }+ }+ }+}++/**+ * The query box, in the app's own glass rather than Material's outline.+ *+ * Built from [BasicTextField] because an `OutlinedTextField` carries a label, a+ * container colour and a border that belong to a design this app does not use —+ * every other control on the page is a pane of glass over the artwork.+ */+@Composable+private fun SearchField(+ query: String,+ enabled: Boolean,+ backdrop: Backdrop,+ onQueryChange: (String) -> Unit,+) {+ LiquidButton(+ onClick = {},+ backdrop = backdrop,+ surfaceColor = GlassFilm,+ contentHeight = 52.dp,+ contentPadding = 18.dp,+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 16.dp),+ ) {+ Icon(+ PhosphorIcons.Fill.MagnifyingGlass,+ contentDescription = null,+ tint = InkDim,+ modifier = Modifier.size(18.dp),+ )+ Box(+ Modifier+ .padding(start = 12.dp)+ .weight(1f),+ contentAlignment = Alignment.CenterStart,+ ) {+ if (query.isEmpty()) {+ Text(+ stringResource(R.string.search_placeholder),+ style = MaterialTheme.typography.bodyLarge,+ color = InkDim,+ maxLines = 1,+ )+ }+ BasicTextField(+ value = query,+ onValueChange = onQueryChange,+ enabled = enabled,+ singleLine = true,+ textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink),+ cursorBrush = SolidColor(Ink),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ modifier = Modifier.fillMaxWidth(),+ )+ }+ if (query.isNotEmpty()) {+ Icon(+ PhosphorIcons.Regular.X,+ contentDescription = stringResource(R.string.clear),+ tint = InkDim,+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .clickable { onQueryChange("") }+ .size(20.dp),+ )+ }+ }+}++/** The same chips the home page filters with; see the note there. */+@Composable+private fun KindRow(selected: Kind, backdrop: Backdrop, onSelect: (Kind) -> Unit) {+ LazyRow(+ contentPadding = PaddingValues(horizontal = 20.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.padding(top = 16.dp, bottom = 4.dp),+ ) {+ items(Kind.entries.toList(), key = { it.name }) { entry ->+ val isSelected = entry == selected+ LiquidButton(+ onClick = { onSelect(entry) },+ backdrop = backdrop,+ contentHeight = 38.dp,+ contentPadding = 18.dp,+ blurRadius = 8.dp,+ surfaceColor = if (isSelected) SelectedFilm else GlassFilm,+ ) {+ Text(+ stringResource(entry.label),+ style = MaterialTheme.typography.bodyMedium,+ color = if (isSelected) Ink else InkDim,+ )}}}@@ -168,17 +284,20 @@ fun SearchScreen(private fun LazyListScope.section(@StringRes title: Int,items: List<SearchItem>,+ /** True on the combined page, where each kind shows only its best few. */+ trimmed: Boolean,round: Boolean,onOpen: (SearchItem) -> Unit,) {if (items.isEmpty()) return+ val shown = if (trimmed) items.take(TOP_RESULTS) else itemsitem(contentType = "section") { SectionTitle(stringResource(title)) }items(- count = items.size,- key = { "$title-${items[it].uri}" },+ count = shown.size,+ key = { "$title-${shown[it].uri}" },contentType = { "result" },) { index ->- val item = items[index]+ val item = shown[index]ResultRow(title = item.title,subtitle = item.subtitle,@@ -186,6 +305,7 @@ private fun LazyListScope.section(highlighted = false,round = round,onClick = { onOpen(item) },+ onMenu = null,)}}@@ -195,7 +315,7 @@ private fun SectionTitle(text: String) {Text(text.uppercase(),style = MaterialTheme.typography.labelLarge,- color = MaterialTheme.colorScheme.primary,+ color = InkDim,modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 22.dp, bottom = 6.dp),)}@@ -208,12 +328,13 @@ private fun ResultRow(highlighted: Boolean,round: Boolean,onClick: () -> Unit,+ onMenu: (() -> Unit)?,) {Row(Modifier.fillMaxWidth().clickable(onClick = onClick)- .padding(horizontal = 24.dp, vertical = 8.dp),+ .padding(start = 24.dp, end = 12.dp, top = 8.dp, bottom = 8.dp),verticalAlignment = Alignment.CenterVertically,) {Artwork(@@ -233,25 +354,43 @@ private fun ResultRow(Text(title,style = MaterialTheme.typography.titleMedium,- color = if (highlighted) {- MaterialTheme.colorScheme.primary- } else {- MaterialTheme.colorScheme.onSurface- },+ color = if (highlighted) MaterialTheme.colorScheme.primary else Ink,maxLines = 1,overflow = TextOverflow.Ellipsis,)Text(subtitle,style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,+ color = InkDim,maxLines = 1,overflow = TextOverflow.Ellipsis,)}+ if (onMenu != null) {+ Icon(+ PhosphorIcons.Regular.DotsThree,+ contentDescription = stringResource(R.string.more),+ tint = InkDim,+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .clickable(onClick = onMenu)+ .padding(10.dp)+ .size(20.dp),+ )+ }}}+@Composable+private fun Message(text: String) {+ Text(+ text,+ style = MaterialTheme.typography.bodyMedium,+ color = InkDim,+ textAlign = TextAlign.Center,+ )+}+@Composableprivate fun StatusBox(content: @Composable () -> Unit) {Box(@@ -262,3 +401,9 @@ private fun StatusBox(content: @Composable () -> Unit) {contentAlignment = Alignment.Center,) { content() }}++/** The chip that is lit, filled a little harder than the rest; see the home page. */+private val SelectedFilm = androidx.compose.ui.graphics.Color.White.copy(alpha = 0.26f)++/** How many of each kind the combined page shows before the chips take over. */+private const val TOP_RESULTS = 4diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.ktindex fb8d5f8..0e8d036 100644--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt@@ -50,6 +50,7 @@ import com.kyant.backdrop.Backdropimport dev.lelonio.square.BuildConfigimport dev.lelonio.square.Rimport dev.lelonio.square.data.AppLanguages+import dev.lelonio.square.backend.BackendIdimport dev.lelonio.square.data.Qualityimport dev.lelonio.square.ui.MainViewModelimport dev.lelonio.square.ui.components.Artwork@@ -88,8 +89,24 @@ fun SettingsScreen(language: String,onLanguage: (String) -> Unit,onBack: () -> Unit,+ /** Opens the Google sign-in web view; see YouTubeLoginScreen. */+ onYouTubeSignIn: () -> Unit = {},) {val ready = state as? MainViewModel.UiState.Ready+ val context = LocalContext.current+ val app = remember(context) {+ context.applicationContext as dev.lelonio.square.SquareApplication+ }+ /**+ * Spotify's own settings are hidden while another source is playing.+ *+ * Not disabled — removed. The account, the registered Web API application,+ * the Connect device and the tutorial that explains all three describe a+ * service the app is not currently using, and leaving them on screen makes+ * the two sources look like one confused one.+ */+ val spotifyActive by app.preferences.backend.collectAsStateWithLifecycle()+ val showSpotify = spotifyActive == BackendId.SPOTIFYLazyColumn(Modifier.fillMaxSize(),@@ -116,7 +133,7 @@ fun SettingsScreen(}}- item("account") {+ if (showSpotify) item("account") {Section(stringResource(R.string.account)) {Row(Modifier@@ -161,7 +178,7 @@ fun SettingsScreen(}}- item("webapi") {+ if (showSpotify) item("webapi") {Section(stringResource(R.string.web_api)) {if (webApi.connected) {InfoRow(stringResource(R.string.application), stringResource(R.string.connected))@@ -181,7 +198,7 @@ fun SettingsScreen(}}- item("tutorial") {+ if (showSpotify) item("tutorial") {Section(stringResource(R.string.guide)) {ActionRow(stringResource(R.string.see_setup_again), destructive = false) {onShowTutorial()@@ -189,7 +206,16 @@ fun SettingsScreen(}}- item("quality") {+ item("backend") {+ BackendSection()+ }++ item("youtube-account") {+ YouTubeAccountSection(onSignIn = onYouTubeSignIn)+ }++ // The bitrate is librespot's; ExoPlayer takes what YouTube serves.+ if (showSpotify) item("quality") {QualitySection()}@@ -291,6 +317,110 @@ fun SettingsScreen(* fourth: this client is served Ogg Vorbis at 320 kbps and below, never a* lossless file, so a "lossless" row would be a promise nothing can keep.*/+/**+ * Which service the app plays from.+ *+ * The two are not equivalent and the note says so rather than letting the user+ * find out: Spotify is the account's own library, its playlists and its Connect+ * devices, while YouTube Music here is anonymous — the catalogue and search+ * work, an account's own library does not exist to read.+ *+ * Changing it restarts playback, so it is a setting rather than a switch in the+ * player.+ */+@Composable+private fun BackendSection() {+ val context = LocalContext.current+ val store = remember(context) {+ (context.applicationContext as dev.lelonio.square.SquareApplication).preferences+ }+ val chosen by store.backend.collectAsStateWithLifecycle()++ Section(stringResource(R.string.backend)) {+ BackendId.entries.forEachIndexed { index, backend ->+ if (index > 0) RowDivider()+ ChoiceRow(+ label = stringResource(+ when (backend) {+ BackendId.SPOTIFY -> R.string.backend_spotify+ BackendId.YOUTUBE_MUSIC -> R.string.backend_youtube+ },+ ),+ selected = backend == chosen,+ ) { store.setBackend(backend) }+ }+ RowDivider()+ Text(+ stringResource(R.string.backend_note),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),+ )+ }+}++/**+ * The Google account YouTube Music reads a library with.+ *+ * Only shown while that backend is the active one: on Spotify it would be an+ * account for a service the app is not currently playing from.+ *+ * Signing in is optional and the section says so. Search and playback work+ * without it; what it adds is the user's own playlists.+ */+@Composable+private fun YouTubeAccountSection(onSignIn: () -> Unit) {+ val context = LocalContext.current+ val app = remember(context) {+ context.applicationContext as dev.lelonio.square.SquareApplication+ }+ val backend by app.preferences.backend.collectAsStateWithLifecycle()+ if (backend != BackendId.YOUTUBE_MUSIC) return++ val account = remember(app) { app.youtubeAccount }+ val name by account.accountName.collectAsStateWithLifecycle()+ val scope = rememberCoroutineScope()++ Section(stringResource(R.string.youtube_account)) {+ if (name == null) {+ ChoiceRow(+ label = stringResource(R.string.youtube_sign_in),+ selected = false,+ onClick = onSignIn,+ )+ RowDivider()+ Text(+ stringResource(R.string.youtube_sign_in_note),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),+ )+ } else {+ Row(+ Modifier+ .fillMaxWidth()+ .padding(horizontal = 18.dp, vertical = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ name.orEmpty(),+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.weight(1f),+ overflow = TextOverflow.Ellipsis,+ maxLines = 1,+ )+ }+ RowDivider()+ ChoiceRow(+ label = stringResource(R.string.youtube_sign_out),+ selected = false,+ ) {+ scope.launch { app.youtubeBackend.logOut() }+ }+ }+ }+}+@Composableprivate fun QualitySection() {val context = LocalContext.currentdiff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex 5d2e66c..9f12629 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -33,6 +33,7 @@<string name="off">Aus</string><string name="queue">Warteschlange</string><string name="lyrics">Songtext</string>+ <string name="watch_video">Video ansehen</string><string name="effects">Effekte</string><string name="cover">Cover</string><string name="devices">Geräte</string>@@ -177,6 +178,22 @@<string name="update_needs_permission">Installation erlauben — tippen</string><string name="update_failed">Gerade nicht — zum Wiederholen tippen</string><string name="quality">Audioqualität</string>+ <string name="backend">Quelle</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">Spotify spielt dein eigenes Konto: dessen Bibliothek, Playlists und Geräte. YouTube Music ist hier anonym — Suche und Wiedergabe funktionieren, eine Kontobibliothek nicht. Diese Änderung startet die Wiedergabe neu.</string>+ <string name="backend_choice_title">Woher möchtest du hören?</string>+ <string name="backend_choice_subtitle">Die andere Quelle lässt sich später in den Einstellungen wählen.</string>+ <string name="backend_choice_spotify_note">Dein eigenes Konto: deine Bibliothek, deine Playlists, deine Connect-Geräte. Erfordert Anmeldung und etwas Einrichtung.</string>+ <string name="backend_choice_youtube_note">Der ganze Katalog, sofort durchsuchbar und abspielbar. Kein Konto, also auch keine eigene Bibliothek.</string>+ <string name="backend_choice_changeable">Jederzeit in den Einstellungen änderbar.</string>+ <string name="youtube_home_empty">Suche etwas, um loszuhören. Was du abspielst, erscheint hier.</string>+ <string name="trending_now">Trends</string>+ <string name="popular_playlists">Beliebte Playlists</string>+ <string name="youtube_account">YouTube-Konto</string>+ <string name="youtube_sign_in">Mit Google anmelden</string>+ <string name="youtube_sign_in_note">Optional. Suche und Wiedergabe gehen auch ohne; die Anmeldung ergänzt deine eigenen Playlists.</string>+ <string name="youtube_sign_out">Abmelden</string><string name="quality_auto">Automatisch</string><string name="quality_high">Hoch</string><string name="quality_medium">Mittel</string>@@ -184,4 +201,9 @@<string name="quality_auto_note">Volle Qualität im WLAN, eine Stufe darunter bei getakteten Verbindungen.</string><string name="quality_restarts">Beim Ändern wird der laufende Titel neu geladen.</string><string name="premium_required">Square braucht Spotify Premium. Ein kostenloses Konto kann sich anmelden, aber Spotify streamt nicht an einen Client wie diesen.</string>+ <string name="new_playlist">Neue Playlist</string>+ <string name="rename">Umbenennen</string>+ <string name="delete">Löschen</string>+ <string name="playlist_name">Name der Playlist</string>+ <string name="create">Erstellen</string></resources>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex 3b1ed64..ba3ee48 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -33,6 +33,7 @@<string name="off">Off</string><string name="queue">Cola</string><string name="lyrics">Letra</string>+ <string name="watch_video">Ver el vídeo</string><string name="effects">Efectos</string><string name="cover">Portada</string><string name="devices">Dispositivos</string>@@ -177,6 +178,22 @@<string name="update_needs_permission">Permite la instalación — toca</string><string name="update_failed">Ahora no — toca para reintentar</string><string name="quality">Calidad de audio</string>+ <string name="backend">Fuente</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">Spotify reproduce tu cuenta: su biblioteca, sus listas, sus dispositivos. YouTube Music aquí es anónimo: la búsqueda y la reproducción funcionan, la biblioteca de una cuenta no. Cambiarlo reinicia la reproducción.</string>+ <string name="backend_choice_title">¿Desde dónde quieres escuchar?</string>+ <string name="backend_choice_subtitle">Puedes elegir la otra más adelante, en los ajustes.</string>+ <string name="backend_choice_spotify_note">Tu cuenta: tu biblioteca, tus listas, tus dispositivos Connect. Requiere iniciar sesión y algo de configuración.</string>+ <string name="backend_choice_youtube_note">Todo el catálogo, buscable y reproducible al instante. Sin cuenta, así que no hay una biblioteca tuya que leer.</string>+ <string name="backend_choice_changeable">Se puede cambiar en cualquier momento en los ajustes.</string>+ <string name="youtube_home_empty">Busca algo para empezar a escuchar. Lo que reproduzcas aparecerá aquí.</string>+ <string name="trending_now">Tendencias</string>+ <string name="popular_playlists">Listas populares</string>+ <string name="youtube_account">Cuenta de YouTube</string>+ <string name="youtube_sign_in">Iniciar sesión con Google</string>+ <string name="youtube_sign_in_note">Opcional. La búsqueda y la reproducción funcionan sin ello; al iniciar sesión se añaden tus listas.</string>+ <string name="youtube_sign_out">Cerrar sesión</string><string name="quality_auto">Automática</string><string name="quality_high">Alta</string><string name="quality_medium">Media</string>@@ -184,4 +201,9 @@<string name="quality_auto_note">Calidad plena con wi-fi, un paso menos con datos medidos.</string><string name="quality_restarts">Al cambiarla, la canción en curso se vuelve a cargar.</string><string name="premium_required">Square necesita Spotify Premium. Una cuenta gratuita puede entrar, pero Spotify no transmite a un cliente como este.</string>+ <string name="new_playlist">Nueva lista</string>+ <string name="rename">Renombrar</string>+ <string name="delete">Eliminar</string>+ <string name="playlist_name">Nombre de la lista</string>+ <string name="create">Crear</string></resources>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 410cf03..668b699 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -33,6 +33,7 @@<string name="off">Off</string><string name="queue">File d\'attente</string><string name="lyrics">Paroles</string>+ <string name="watch_video">Regarder la vidéo</string><string name="effects">Effets</string><string name="cover">Pochette</string><string name="devices">Appareils</string>@@ -177,6 +178,22 @@<string name="update_needs_permission">Autorisez l\'installation — touchez</string><string name="update_failed">Pas maintenant — touchez pour réessayer</string><string name="quality">Qualité audio</string>+ <string name="backend">Source</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">Spotify lit votre compte : sa bibliothèque, ses playlists, ses appareils. YouTube Music est ici anonyme — la recherche et la lecture fonctionnent, la bibliothèque d\'un compte non. Changer ceci redémarre la lecture.</string>+ <string name="backend_choice_title">D\'où voulez-vous écouter ?</string>+ <string name="backend_choice_subtitle">Vous pourrez choisir l\'autre plus tard, dans les réglages.</string>+ <string name="backend_choice_spotify_note">Votre compte : votre bibliothèque, vos playlists, vos appareils Connect. Nécessite une connexion et un peu de configuration.</string>+ <string name="backend_choice_youtube_note">Tout le catalogue, cherchable et lisible immédiatement. Pas de compte, donc pas de bibliothèque personnelle à lire.</string>+ <string name="backend_choice_changeable">Modifiable à tout moment dans les réglages.</string>+ <string name="youtube_home_empty">Cherchez quelque chose pour commencer à écouter. Ce que vous lisez apparaîtra ici.</string>+ <string name="trending_now">Tendances</string>+ <string name="popular_playlists">Playlists populaires</string>+ <string name="youtube_account">Compte YouTube</string>+ <string name="youtube_sign_in">Se connecter avec Google</string>+ <string name="youtube_sign_in_note">Facultatif. La recherche et la lecture fonctionnent sans ; la connexion ajoute vos playlists.</string>+ <string name="youtube_sign_out">Se déconnecter</string><string name="quality_auto">Automatique</string><string name="quality_high">Haute</string><string name="quality_medium">Moyenne</string>@@ -184,4 +201,9 @@<string name="quality_auto_note">Qualité maximale en wi-fi, un cran en dessous sur une connexion facturée.</string><string name="quality_restarts">La changer recharge le titre en cours.</string><string name="premium_required">Square demande Spotify Premium. Un compte gratuit peut se connecter, mais Spotify ne diffuse pas vers un client comme celui-ci.</string>+ <string name="new_playlist">Nouvelle playlist</string>+ <string name="rename">Renommer</string>+ <string name="delete">Supprimer</string>+ <string name="playlist_name">Nom de la playlist</string>+ <string name="create">Créer</string></resources>diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex 42f8031..0948460 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -34,6 +34,7 @@<string name="off">Off</string><string name="queue">Coda</string><string name="lyrics">Testo</string>+ <string name="watch_video">Guarda il video</string><string name="effects">Effetti</string><string name="cover">Copertina</string><string name="devices">Dispositivi</string>@@ -178,6 +179,22 @@<string name="update_needs_permission">Consenti l\'installazione — tocca</string><string name="update_failed">Non adesso — tocca per riprovare</string><string name="quality">Qualità audio</string>+ <string name="backend">Sorgente</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">Spotify riproduce il tuo account: la sua libreria, le sue playlist, i suoi dispositivi. YouTube Music qui è anonimo — ricerca e riproduzione funzionano, la libreria di un account no. Cambiarlo riavvia la riproduzione.</string>+ <string name="backend_choice_title">Da dove vuoi ascoltare?</string>+ <string name="backend_choice_subtitle">Puoi scegliere l\'altra più avanti, nelle impostazioni.</string>+ <string name="backend_choice_spotify_note">Il tuo account: la tua libreria, le tue playlist, i tuoi dispositivi Connect. Richiede l\'accesso e un po\' di configurazione.</string>+ <string name="backend_choice_youtube_note">Tutto il catalogo, subito cercabile e riproducibile. Nessun account, quindi non c\'è una libreria tua da leggere.</string>+ <string name="backend_choice_changeable">Si può cambiare in qualsiasi momento nelle impostazioni.</string>+ <string name="youtube_home_empty">Cerca qualcosa per iniziare ad ascoltare. Quello che riproduci compare qui.</string>+ <string name="trending_now">Tendenze</string>+ <string name="popular_playlists">Playlist popolari</string>+ <string name="youtube_account">Account YouTube</string>+ <string name="youtube_sign_in">Accedi con Google</string>+ <string name="youtube_sign_in_note">Facoltativo. Ricerca e riproduzione funzionano anche senza; accedendo si aggiungono le tue playlist.</string>+ <string name="youtube_sign_out">Esci</string><string name="quality_auto">Automatica</string><string name="quality_high">Alta</string><string name="quality_medium">Media</string>@@ -185,4 +202,9 @@<string name="quality_auto_note">Qualità piena sul wi-fi, un gradino sotto con la rete a consumo.</string><string name="quality_restarts">Cambiandola, la canzone in corso viene ricaricata.</string><string name="premium_required">Square richiede Spotify Premium. Un account free riesce ad accedere, ma Spotify non trasmette a un client come questo.</string>+ <string name="new_playlist">Nuova playlist</string>+ <string name="rename">Rinomina</string>+ <string name="delete">Elimina</string>+ <string name="playlist_name">Nome della playlist</string>+ <string name="create">Crea</string></resources>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex ced5bfe..94dd326 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -33,6 +33,7 @@<string name="off">Off</string><string name="queue">Fila</string><string name="lyrics">Letra</string>+ <string name="watch_video">Ver o vídeo</string><string name="effects">Efeitos</string><string name="cover">Capa</string><string name="devices">Dispositivos</string>@@ -177,6 +178,22 @@<string name="update_needs_permission">Permite a instalação — toca</string><string name="update_failed">Agora não — toca para tentar de novo</string><string name="quality">Qualidade de áudio</string>+ <string name="backend">Fonte</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">O Spotify reproduz a tua conta: a sua biblioteca, as suas playlists, os seus dispositivos. O YouTube Music aqui é anónimo — a pesquisa e a reprodução funcionam, a biblioteca de uma conta não. Mudar isto reinicia a reprodução.</string>+ <string name="backend_choice_title">De onde queres ouvir?</string>+ <string name="backend_choice_subtitle">Podes escolher a outra mais tarde, nas definições.</string>+ <string name="backend_choice_spotify_note">A tua conta: a tua biblioteca, as tuas playlists, os teus dispositivos Connect. Requer início de sessão e alguma configuração.</string>+ <string name="backend_choice_youtube_note">Todo o catálogo, pesquisável e reproduzível de imediato. Sem conta, por isso não há biblioteca tua para ler.</string>+ <string name="backend_choice_changeable">Pode ser alterado a qualquer momento nas definições.</string>+ <string name="youtube_home_empty">Pesquisa algo para começares a ouvir. O que reproduzires aparece aqui.</string>+ <string name="trending_now">Tendências</string>+ <string name="popular_playlists">Playlists populares</string>+ <string name="youtube_account">Conta YouTube</string>+ <string name="youtube_sign_in">Iniciar sessão com Google</string>+ <string name="youtube_sign_in_note">Opcional. A pesquisa e a reprodução funcionam sem isto; iniciar sessão acrescenta as tuas playlists.</string>+ <string name="youtube_sign_out">Terminar sessão</string><string name="quality_auto">Automática</string><string name="quality_high">Alta</string><string name="quality_medium">Média</string>@@ -184,4 +201,9 @@<string name="quality_auto_note">Qualidade máxima no wi-fi, um degrau abaixo em ligação tarifada.</string><string name="quality_restarts">Ao mudá-la, a faixa em curso é recarregada.</string><string name="premium_required">O Square precisa de Spotify Premium. Uma conta gratuita consegue entrar, mas o Spotify não transmite para um cliente como este.</string>+ <string name="new_playlist">Nova playlist</string>+ <string name="rename">Renomear</string>+ <string name="delete">Eliminar</string>+ <string name="playlist_name">Nome da playlist</string>+ <string name="create">Criar</string></resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex d404016..46a198f 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -44,6 +44,7 @@<string name="off">Off</string><string name="queue">Queue</string><string name="lyrics">Lyrics</string>+ <string name="watch_video">Watch the video</string><string name="effects">Effects</string><string name="cover">Cover</string><string name="devices">Devices</string>@@ -198,6 +199,22 @@<string name="update_needs_permission">Allow installing — tap</string><string name="update_failed">Not now — tap to retry</string><string name="quality">Audio quality</string>+ <string name="backend">Source</string>+ <string name="backend_spotify">Spotify</string>+ <string name="backend_youtube">YouTube Music</string>+ <string name="backend_note">Spotify plays your own account: its library, its playlists, its devices. YouTube Music is anonymous here — search and playback work, an account library does not. Changing this restarts playback.</string>+ <string name="backend_choice_title">Where do you want to listen from?</string>+ <string name="backend_choice_subtitle">You can pick the other one later, in the settings.</string>+ <string name="backend_choice_spotify_note">Your own account: your library, your playlists, your Connect devices. Needs a login and a bit of setup.</string>+ <string name="backend_choice_youtube_note">The whole catalogue, searchable and playable straight away. No account, so there is no library of your own to read.</string>+ <string name="backend_choice_changeable">This can be changed at any time in the settings.</string>+ <string name="youtube_home_empty">Search for something to start listening. What you play shows up here.</string>+ <string name="trending_now">Trending now</string>+ <string name="popular_playlists">Popular playlists</string>+ <string name="youtube_account">YouTube account</string>+ <string name="youtube_sign_in">Sign in with Google</string>+ <string name="youtube_sign_in_note">Optional. Search and playback work without it; signing in adds your own playlists.</string>+ <string name="youtube_sign_out">Sign out</string><string name="quality_auto">Automatic</string><string name="quality_high">High</string><string name="quality_medium">Medium</string>@@ -205,4 +222,9 @@<string name="quality_auto_note">Full quality on wi-fi, one step down on a metered connection.</string><string name="quality_restarts">Changing this reloads what is playing.</string><string name="premium_required">Square needs Spotify Premium. A free account can sign in, but Spotify does not stream to a client like this one.</string>+ <string name="new_playlist">New playlist</string>+ <string name="rename">Rename</string>+ <string name="delete">Delete</string>+ <string name="playlist_name">Playlist name</string>+ <string name="create">Create</string></resources>diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 5c1bce1..1593e80 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -8,6 +8,7 @@ lifecycle = "2.8.7"okhttp = "4.12.0"retrofit = "2.11.0"serialization = "1.7.3"+ktor = "3.5.2"[libraries]androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.15.0" }@@ -26,7 +27,8 @@ compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview"media3-common = { module = "androidx.media3:media3-common", version.ref = "media3" }media3-session = { module = "androidx.media3:media3-session", version.ref = "media3" }-# Plays the Canvas clip only. Audio still comes from the librespot engine.+# The Canvas clip, and every note of the YouTube Music backend. Spotify audio+# still comes from the librespot engine instead.media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3" }media3-ui = { module = "androidx.media3:media3-ui", version.ref = "media3" }@@ -39,6 +41,28 @@ okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor", version.retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }retrofit-serialization = { module = "com.squareup.retrofit2:converter-kotlinx-serialization", version.ref = "retrofit" }+# YouTube Music's catalogue and stream URLs (GPL-3.0). InnerTube is not a+# documented API, so this is reverse engineering someone else already maintains+# — the alternative is carrying the signature-cipher chase in this repo.+#+# Keep it current. YouTube breaks extraction deliberately and often: v0.24.6+# still searched fine but every stream answered "The page needs to be reloaded",+# which is what a version a few months stale looks like from here.+newpipe-extractor = { module = "com.github.TeamNewPipe:NewPipeExtractor", version = "v0.26.4" }++ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }+ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }+ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }+ktor-client-encoding = { module = "io.ktor:ktor-client-encoding", version.ref = "ktor" }+ktor-serialization-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }+brotli = { module = "org.brotli:dec", version = "0.1.2" }+timber = { module = "com.jakewharton.timber:timber", version = "5.0.1" }+desugaring = { module = "com.android.tools:desugar_jdk_libs_nio", version = "2.1.5" }+# Metrolist's fork of NewPipeExtractor, which its innertube module is written+# against. Kept alongside the upstream extractor rather than replacing it: the+# anonymous path already works and is what runs when nobody is signed in.+metrolist-extractor = { module = "com.github.MetrolistGroup:MetrolistExtractor", version = "3cd3341" }+coil-compose = { module = "io.coil-kt:coil-compose", version = "2.7.0" }androidx-palette = { module = "androidx.palette:palette-ktx", version = "1.0.0" }androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version = "2.8.5" }diff --git a/innertube/.gitignore b/innertube/.gitignorenew file mode 100644index 0000000..42afabf--- /dev/null+++ b/innertube/.gitignore@@ -0,0 +1 @@+/build\ No newline at end of filediff --git a/innertube/README.md b/innertube/README.mdnew file mode 100644index 0000000..e72cd26--- /dev/null+++ b/innertube/README.md@@ -0,0 +1,60 @@+# innertube++Vendored from **Metrolist** — <https://github.com/mostafaalagamy/Metrolist> —+licensed GPL-3.0, the same licence this project carries. Copyright remains with+the Metrolist project and its contributors; see that repository's git history.++## What it is++A client for YouTube's private InnerTube API: the one `music.youtube.com`+itself talks to. It is what makes a *signed-in* YouTube Music experience+possible — the account's own library, its playlists, its home page, its+listening history — none of which an anonymous client can read.++## Why it is vendored rather than depended on++Metrolist does not publish this module to any repository. Copying it is the only+way to use it.++## Why the package is still `com.metrolist.innertube`++Deliberately not renamed. YouTube changes InnerTube's shape without warning and+upstream is where those repairs land first; keeping the package identical is+what makes it possible to diff against upstream and pull a fix in, rather than+re-deriving it here.++The corollary: **treat this directory as read-only.** Anything this app needs+that the module does not do belongs in `app/`, in+`dev.lelonio.square.backend.youtube`, not in edits made here — an edit made here+is an edit that has to be re-applied by hand every time upstream is pulled.++## Local changes++Kept to the minimum, and listed here because each one has to be re-applied by+hand whenever this module is refreshed from upstream.++**`build.gradle.kts`**++- Java 17 and `jvmTarget` 17, matching the rest of this project (upstream is 21).+- the Kotlin Android plugin declared via this project's own version catalog.+- a `dev` build type, because the app has one and a library with no matching+ variant cannot be resolved against it.+- **NewPipeExtractor upstream instead of Metrolist's fork.** The fork is built+ against a much older extractor — `getThumbnailUrl()` rather than+ `getThumbnails()`, a different `Downloader` — and both publish the same+ `org.schabi.newpipe.extractor` packages, so the two cannot coexist in one APK.+ This app's anonymous path was written and verified against upstream v0.26.4,+ where the fork's vintage is close to the version that could search but could+ not resolve a single stream.++**`pages/NewPipe.kt` — deleted**, and its one caller in `YouTube.kt`+(`getNewPipeStreamUrls`) reduced to `emptyList()`. That file is upstream's+NewPipe-based stream extractor and is what would not compile against the newer+extractor. Nothing here needs it: the branch calling it is behind+`ENABLE_NEWPIPE_STREAM_INFO_EXTRACTOR`, which is `false` upstream as well, and+stream URLs in this app come from `YouTubeStreamResolver`.++## Updating++Copy the module over from a newer Metrolist checkout, then re-apply everything+under "Local changes" above.diff --git a/innertube/build.gradle.kts b/innertube/build.gradle.ktsnew file mode 100644index 0000000..317c44c--- /dev/null+++ b/innertube/build.gradle.kts@@ -0,0 +1,57 @@+plugins {+ id("com.android.library")+ alias(libs.plugins.kotlin.android)+ alias(libs.plugins.kotlin.serialization)+}++android {+ namespace = "com.metrolist.innertube"+ compileSdk = 37++ defaultConfig {+ minSdk = 26+ }++ buildTypes {+ // The app builds `dev` as well as debug and release, and a library that+ // does not declare it has no variant Gradle can match against — see+ // the app's own buildTypes for what `dev` is for. Nothing is configured+ // here: a library has no shrinker or signing of its own to set.+ create("dev") {+ initWith(getByName("release"))+ }+ }++ compileOptions {+ // The module reads java.time; on API 26 most of it exists, but the+ // upstream sources assume the desugared library and this is not the+ // place to find out which calls do not.+ isCoreLibraryDesugaringEnabled = true+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ kotlin {+ compilerOptions {+ jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)+ }+ }+}++dependencies {+ // Exposed rather than hidden: this module's public functions return+ // `Result<HttpResponse>`, so anything calling them needs the type on its+ // own classpath.+ api(libs.ktor.client.core)+ implementation(libs.ktor.client.okhttp)+ implementation(libs.ktor.client.content.negotiation)+ implementation(libs.ktor.serialization.json)+ implementation(libs.ktor.client.encoding)+ implementation(libs.brotli)+ implementation(libs.newpipe.extractor) {+ exclude(group = "com.google.protobuf")+ }+ implementation(libs.timber)++ coreLibraryDesugaring(libs.desugaring)+}diff --git a/innertube/src/main/AndroidManifest.xml b/innertube/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..9a40236--- /dev/null+++ b/innertube/src/main/AndroidManifest.xml@@ -0,0 +1,3 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+</manifest>diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.ktnew file mode 100644index 0000000..6df7870--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/InnerTube.kt@@ -0,0 +1,869 @@+package com.metrolist.innertube++import com.metrolist.innertube.models.Context+import com.metrolist.innertube.models.MediaInfo+import com.metrolist.innertube.models.ReturnYouTubeDislikeResponse+import com.metrolist.innertube.models.YouTubeClient+import com.metrolist.innertube.models.YouTubeLocale+import com.metrolist.innertube.models.body.*+import com.metrolist.innertube.models.response.NextResponse+import com.metrolist.innertube.utils.parseCookieString+import com.metrolist.innertube.utils.sha1+import io.ktor.client.*+import io.ktor.client.call.body+import io.ktor.client.engine.okhttp.*+import io.ktor.client.plugins.*+import io.ktor.client.plugins.compression.*+import io.ktor.client.plugins.contentnegotiation.*+import io.ktor.client.plugins.HttpTimeout+import io.ktor.client.request.*+import io.ktor.client.statement.bodyAsText+import io.ktor.http.*+import io.ktor.serialization.kotlinx.json.*+import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.json.Json+import java.net.Proxy+import java.io.IOException+import kotlinx.coroutines.delay+import java.util.*+import kotlin.io.encoding.Base64+import timber.log.Timber+import kotlin.io.encoding.ExperimentalEncodingApi++/**+ * Provide access to InnerTube endpoints.+ * For making HTTP requests, not parsing response.+ */+@OptIn(ExperimentalEncodingApi::class)+class InnerTube {+ private var httpClient = createClient()++ private companion object {+ const val PLAYBACK_TELEMETRY_VER = "2"+ }++ var locale = YouTubeLocale(+ gl = Locale.getDefault().country,+ hl = Locale.getDefault().toLanguageTag()+ )+ var visitorData: String? = null+ var dataSyncId: String? = null+ var cookie: String? = null+ set(value) {+ field = value+ cookieMap = if (value == null) emptyMap() else parseCookieString(value)+ }+ private var cookieMap = emptyMap<String, String>()++ var proxy: Proxy? = null+ set(value) {+ field = value+ httpClient.close()+ httpClient = createClient()+ }++ var proxyAuth: String? = null++ var useLoginForBrowse: Boolean = false++ @OptIn(ExperimentalSerializationApi::class)+ private fun createClient() = HttpClient(OkHttp) {+ expectSuccess = true++ install(ContentNegotiation) {+ json(Json {+ ignoreUnknownKeys = true+ explicitNulls = false+ encodeDefaults = true+ })+ }++ install(ContentEncoding) {+ gzip(0.9F)+ deflate(0.8F)+ }++ // Enhanced network configuration for better performance+ engine {+ config {+ // Connection pool settings for better connection reuse+ connectionPool(+ okhttp3.ConnectionPool(+ 10, // maxIdleConnections+ 5, // keepAliveDuration+ java.util.concurrent.TimeUnit.MINUTES+ )+ )++ // Timeout configurations+ connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)+ readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)+ writeTimeout(60, java.util.concurrent.TimeUnit.SECONDS)++ // Enable HTTP/2 for better performance+ protocols(listOf(okhttp3.Protocol.HTTP_2, okhttp3.Protocol.HTTP_1_1))++ // Retry on connection failure+ retryOnConnectionFailure(true)++ // Cache configuration for better performance+ cache(+ okhttp3.Cache(+ directory = java.io.File(System.getProperty("java.io.tmpdir"), "http_cache"),+ maxSize = 50L * 1024L * 1024L // 50 MB+ )+ )++ // Apply proxy configuration+ [email protected]?.let { proxyConfig ->+ proxy(proxyConfig)+ }++ // Apply proxy authentication+ [email protected]?.let { auth ->+ proxyAuthenticator { _, response ->+ response.request.newBuilder()+ .header("Proxy-Authorization", auth)+ .build()+ }+ }+ }+ }++ // Request timeout configuration+ install(HttpTimeout) {+ requestTimeoutMillis = 60000+ connectTimeoutMillis = 30000+ socketTimeoutMillis = 60000+ }++ defaultRequest {+ url(YouTubeClient.API_URL_YOUTUBE_MUSIC)+ // Add common headers for better compatibility+ header("Accept", "application/json")+ header("Accept-Language", "en-US,en;q=0.9")+ header("Cache-Control", "no-cache")+ }+ }++ private fun HttpRequestBuilder.ytClient(client: YouTubeClient, setLogin: Boolean = false) {+ contentType(ContentType.Application.Json)+ headers {+ append("X-Goog-Api-Format-Version", "1")+ append("X-YouTube-Client-Name", client.clientId /* Not a typo. The Client-Name header does contain the client id. */)+ append("X-YouTube-Client-Version", client.clientVersion)+ append("X-Origin", YouTubeClient.ORIGIN_YOUTUBE_MUSIC)+ append("Referer", YouTubeClient.REFERER_YOUTUBE_MUSIC)+ visitorData?.let { append("X-Goog-Visitor-Id", it) }+ if (setLogin && client.loginSupported) {+ cookie?.let { cookie ->+ append("cookie", cookie)+ if ("SAPISID" !in cookieMap) return@let+ val currentTime = System.currentTimeMillis() / 1000+ val sapisidHash = sha1("$currentTime ${cookieMap["SAPISID"]} ${YouTubeClient.ORIGIN_YOUTUBE_MUSIC}")+ append("Authorization", "SAPISIDHASH ${currentTime}_${sapisidHash}")+ }+ }+ }+ userAgent(client.userAgent)+ parameter("prettyPrint", false)+ }++ /**+ * Simple retry wrapper for transient IO errors (socket aborts, timeouts).+ * Retries the given block up to [maxAttempts] times with exponential backoff.+ * Cancellation is respected since [delay] will throw if the coroutine is cancelled.+ */+ private suspend fun <T> withRetry(+ maxAttempts: Int = 3,+ initialDelay: Long = 500L,+ factor: Double = 2.0,+ block: suspend () -> T,+ ): T {+ var currentDelay = initialDelay+ var attempt = 0+ while (true) {+ try {+ return block()+ } catch (e: IOException) {+ attempt+++ if (attempt >= maxAttempts) throw e+ delay(currentDelay)+ currentDelay = (currentDelay * factor).toLong()+ }+ }+ }++ suspend fun search(+ client: YouTubeClient,+ query: String? = null,+ params: String? = null,+ continuation: String? = null,+ ) = withRetry {+ httpClient.post("search") {+ ytClient(client, setLogin = false)+ setBody(+ SearchBody(+ context = client.toContext(+ locale,+ visitorData,+ null+ ),+ query = query,+ params = params+ )+ )+ parameter("continuation", continuation)+ parameter("ctoken", continuation)+ }+ }++ suspend fun player(+ client: YouTubeClient,+ videoId: String,+ playlistId: String?,+ signatureTimestamp: Int?,+ poToken: String? = null,+ ) = withRetry {+ httpClient.post("player") {+ ytClient(client, setLogin = true)+ setBody(+ PlayerBody(+ context = client.toContext(locale, visitorData, dataSyncId).let {+ if (client.isEmbedded) {+ it.copy(+ thirdParty = Context.ThirdParty(+ embedUrl = "https://www.youtube.com/watch?v=${videoId}"+ )+ )+ } else it+ },+ videoId = videoId,+ playlistId = playlistId,+ playbackContext = if (client.useSignatureTimestamp && signatureTimestamp != null) {+ PlayerBody.PlaybackContext(+ PlayerBody.PlaybackContext.ContentPlaybackContext(+ signatureTimestamp+ )+ )+ } else null,+ serviceIntegrityDimensions = if (client.useWebPoTokens && poToken != null) {+ PlayerBody.ServiceIntegrityDimensions(poToken)+ } else null,+ )+ )+ }+ }++ suspend fun registerPlayback(+ url: String,+ cpn: String,+ playlistId: String?,+ client: YouTubeClient = YouTubeClient.WEB_REMIX,+ ) = withRetry {+ httpClient.get(url) {+ ytClient(client, true)+ parameter("c", client.clientName)+ parameter("cpn", cpn)+ parameter("ver", PLAYBACK_TELEMETRY_VER)++ if (playlistId != null) {+ parameter("list", playlistId)+ parameter("referrer", "https://music.youtube.com/playlist?list=$playlistId")+ }+ }+ }++ suspend fun browse(+ client: YouTubeClient,+ browseId: String? = null,+ params: String? = null,+ continuation: String? = null,+ setLogin: Boolean = false,+ ) = withRetry {+ httpClient.post("browse") {+ ytClient(client, setLogin = setLogin || useLoginForBrowse)+ setBody(+ BrowseBody(+ context = client.toContext(+ locale,+ visitorData,+ if (setLogin || useLoginForBrowse) dataSyncId else null+ ),+ browseId = browseId,+ params = params,+ continuation = continuation+ )+ )+ }+ }++ suspend fun next(+ client: YouTubeClient,+ videoId: String?,+ playlistId: String?,+ playlistSetVideoId: String?,+ index: Int?,+ params: String?,+ continuation: String? = null,+ ) = withRetry {+ httpClient.post("next") {+ ytClient(client, setLogin = true)+ setBody(+ NextBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ videoId = videoId,+ playlistId = playlistId,+ playlistSetVideoId = playlistSetVideoId,+ index = index,+ params = params,+ continuation = continuation+ )+ )+ }+ }++ suspend fun feedback(+ client: YouTubeClient,+ tokens: List<String>+ ) = withRetry {+ httpClient.post("feedback") {+ ytClient(client, setLogin = true)+ setBody(+ FeedbackBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ feedbackTokens = tokens+ )+ )+ }+ }++ suspend fun getSearchSuggestions(+ client: YouTubeClient,+ input: String,+ ) = withRetry {+ httpClient.post("music/get_search_suggestions") {+ ytClient(client)+ setBody(+ GetSearchSuggestionsBody(+ context = client.toContext(locale, visitorData, null),+ input = input+ )+ )+ }+ }++ suspend fun getQueue(+ client: YouTubeClient,+ videoIds: List<String>?,+ playlistId: String?,+ ) = withRetry {+ httpClient.post("music/get_queue") {+ ytClient(client)+ setBody(+ GetQueueBody(+ context = client.toContext(locale, visitorData, null),+ videoIds = videoIds,+ playlistId = playlistId+ )+ )+ }+ }++ suspend fun getTranscript(+ client: YouTubeClient,+ videoId: String,+ ) = withRetry {+ httpClient.post("https://music.youtube.com/youtubei/v1/get_transcript") {+ parameter("key", "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX3")+ headers {+ append("Content-Type", "application/json")+ }+ setBody(+ GetTranscriptBody(+ context = client.toContext(locale, null, null),+ params = Base64.Default.encode(+ "\n${11.toChar()}$videoId".encodeToByteArray()+ )+ )+ )+ }+ }++ suspend fun getSwJsData() = withRetry { httpClient.get("https://music.youtube.com/sw.js_data") }++ suspend fun accountMenu(client: YouTubeClient) = withRetry {+ httpClient.post("account/account_menu") {+ ytClient(client, setLogin = true)+ setBody(AccountMenuBody(client.toContext(locale, visitorData, dataSyncId)))+ }+ }++ suspend fun likeVideo(+ client: YouTubeClient,+ videoId: String,+ ) = withRetry {+ httpClient.post("like/like") {+ ytClient(client, setLogin = true)+ setBody(+ LikeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ target = LikeBody.Target.video(videoId)+ )+ )+ }+ }++ suspend fun unlikeVideo(+ client: YouTubeClient,+ videoId: String,+ ) = withRetry {+ httpClient.post("like/removelike") {+ ytClient(client, setLogin = true)+ setBody(+ LikeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ target = LikeBody.Target.video(videoId)+ )+ )+ }+ }++ suspend fun subscribeChannel(+ client: YouTubeClient,+ channelId: String,+ params: String? = null,+ ) = withRetry {+ httpClient.post("subscription/subscribe") {+ ytClient(client, setLogin = true)+ setBody(+ SubscribeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ channelIds = listOf(channelId),+ params = params+ )+ )+ }+ }++ suspend fun unsubscribeChannel(+ client: YouTubeClient,+ channelId: String,+ params: String? = null,+ ) = withRetry {+ httpClient.post("subscription/unsubscribe") {+ ytClient(client, setLogin = true)+ setBody(+ SubscribeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ channelIds = listOf(channelId),+ params = params+ )+ )+ }+ }++ suspend fun likePlaylist(+ client: YouTubeClient,+ playlistId: String,+ ) = withRetry {+ httpClient.post("like/like") {+ ytClient(client, setLogin = true)+ setBody(+ LikeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ target = LikeBody.Target.playlist(playlistId)+ )+ )+ }+ }++ suspend fun unlikePlaylist(+ client: YouTubeClient,+ playlistId: String,+ ) = withRetry {+ httpClient.post("like/removelike") {+ ytClient(client, setLogin = true)+ setBody(+ LikeBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ target = LikeBody.Target.playlist(playlistId)+ )+ )+ }+ }++ suspend fun addToPlaylist(+ client: YouTubeClient,+ playlistId: String,+ videoId: String,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId.removePrefix("VL"),+ actions = listOf(+ Action.AddVideoAction(addedVideoId = videoId)+ )+ )+ )+ }+ }++ suspend fun addPlaylistToPlaylist(+ client: YouTubeClient,+ playlistId: String,+ addPlaylistId: String,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId.removePrefix("VL"),+ actions = listOf(+ Action.AddPlaylistAction(addedFullListId = addPlaylistId)+ )+ )+ )+ }+ }++ suspend fun removeFromPlaylist(+ client: YouTubeClient,+ playlistId: String,+ videoId: String,+ setVideoId: String,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId.removePrefix("VL"),+ actions = listOf(+ Action.RemoveVideoAction(+ removedVideoId = videoId,+ setVideoId = setVideoId,+ )+ )+ )+ )+ }+ }++ suspend fun moveSongPlaylist(+ client: YouTubeClient,+ playlistId: String,+ setVideoId: String,+ successorSetVideoId: String?,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId,+ actions = listOf(+ Action.MoveVideoAction(+ movedSetVideoIdSuccessor = successorSetVideoId,+ setVideoId = setVideoId,+ )+ )+ )+ )+ }+ }++ suspend fun createPlaylist(+ client: YouTubeClient,+ title: String,+ ) = withRetry {+ httpClient.post("playlist/create") {+ ytClient(client, true)+ setBody(+ CreatePlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ title = title+ )+ )+ }+ }++ suspend fun renamePlaylist(+ client: YouTubeClient,+ playlistId: String,+ name: String,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId,+ actions = listOf(+ Action.RenamePlaylistAction(+ playlistName = name+ )+ )+ )+ )+ }+ }++ suspend fun getUploadCustomThumbnailLink(+ client: YouTubeClient,+ contentLength: Int+ ) = withRetry {+ httpClient.post("https://music.youtube.com/playlist_image_upload/playlist_custom_thumbnail") {+ ytClient(client, setLogin = true)+ headers {+ append("X-Goog-Upload-Command", "start")+ append("X-Goog-Upload-Protocol", "resumable")+ append("X-Goog-Upload-Header-Content-Length", contentLength.toString())+ }+ }+ }++ suspend fun uploadCustomThumbnail(+ client: YouTubeClient,+ uploadId: String,+ image: ByteArray,+ ) = withRetry {+ httpClient.post("https://music.youtube.com/playlist_image_upload/playlist_custom_thumbnail") {+ ytClient(client, setLogin = true)+ parameter("upload_id", uploadId)+ parameter("upload_protocol", "resumable")+ headers {+ append("X-Goog-Upload-Command", "upload, finalize")+ append("X-Goog-Upload-Offset", "0")+ }+ setBody(image)+ }+ }++ suspend fun setThumbnailPlaylist(+ client: YouTubeClient,+ playlistId: String,+ blobId: String,+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId,+ actions = listOf(+ Action.SetCustomThumbnailAction(+ addedCustomThumbnail = Action.SetCustomThumbnailAction.AddedCustomThumbnail(+ playlistScottyEncryptedBlobId = blobId+ )+ )+ )+ )+ )+ }+ }++ suspend fun removeThumbnailPlaylist(+ client: YouTubeClient,+ playlistId: String+ ) = withRetry {+ httpClient.post("browse/edit_playlist") {+ ytClient(client, setLogin = true)+ setBody(+ EditPlaylistBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId,+ actions = listOf(+ Action.RemoveCustomThumbnailAction()+ )+ )+ )+ }+ }++ suspend fun deletePlaylist(+ client: YouTubeClient,+ playlistId: String,+ ) = withRetry {+ httpClient.post("playlist/delete") {+ println("deleting $playlistId")+ ytClient(client, setLogin = true)+ setBody(+ PlaylistDeleteBody(+ context = client.toContext(locale, visitorData, dataSyncId),+ playlistId = playlistId+ )+ )+ }+ }++ private suspend fun returnYouTubeDislike(videoId: String) = withRetry {+ httpClient.get("https://returnyoutubedislikeapi.com/Votes?videoId=$videoId") {+ contentType(ContentType.Application.Json)+ }+ }+++ /**+ * Initialize a song upload to YouTube Music.+ * Returns the upload URL in the X-Goog-Upload-URL header.+ */+ suspend fun initSongUpload(+ filename: String,+ contentLength: Long+ ) = withRetry {+ val authUser = "0"+ httpClient.post("https://upload.youtube.com/upload/usermusic/http?authuser=$authUser") {+ headers {+ append("X-Goog-Upload-Command", "start")+ append("X-Goog-Upload-Protocol", "resumable")+ append("X-Goog-Upload-Header-Content-Length", contentLength.toString())+ append("X-Goog-AuthUser", authUser)+ append("Origin", YouTubeClient.ORIGIN_YOUTUBE_MUSIC)+ cookie?.let { cookie ->+ append("cookie", cookie)+ if ("SAPISID" !in cookieMap) return@let+ val currentTime = System.currentTimeMillis() / 1000+ val sapisidHash = sha1("$currentTime ${cookieMap["SAPISID"]} ${YouTubeClient.ORIGIN_YOUTUBE_MUSIC}")+ append("Authorization", "SAPISIDHASH ${currentTime}_${sapisidHash}")+ }+ }+ contentType(ContentType.Application.FormUrlEncoded)+ setBody("filename=$filename")+ }+ }++ /**+ * Upload song data to the provided upload URL.+ */+ suspend fun uploadSongData(+ uploadUrl: String,+ data: ByteArray,+ onProgress: ((Float) -> Unit)? = null+ ) = withRetry {+ httpClient.post(uploadUrl) {+ headers {+ append("X-Goog-Upload-Command", "upload, finalize")+ append("X-Goog-Upload-Offset", "0")+ append("X-Goog-AuthUser", "0")+ append("Origin", YouTubeClient.ORIGIN_YOUTUBE_MUSIC)+ cookie?.let { cookie ->+ append("cookie", cookie)+ if ("SAPISID" !in cookieMap) return@let+ val currentTime = System.currentTimeMillis() / 1000+ val sapisidHash = sha1("$currentTime ${cookieMap["SAPISID"]} ${YouTubeClient.ORIGIN_YOUTUBE_MUSIC}")+ append("Authorization", "SAPISIDHASH ${currentTime}_${sapisidHash}")+ }+ }+ contentType(ContentType.Application.OctetStream)+ setBody(data)+ onUpload { bytesSentTotal, contentLength ->+ contentLength?.let {+ onProgress?.invoke(bytesSentTotal.toFloat() / it.toFloat())+ }+ }+ }+ }++ /**+ * Delete a privately owned (uploaded) song from YouTube Music.+ */+ suspend fun deletePrivatelyOwnedEntity(entityId: String) = withRetry {+ val context = YouTubeClient.WEB_REMIX.toContext(locale, visitorData, null)+ val requestBody = """{"context":${Json.encodeToString(context)},"entityId":"$entityId"}"""+ httpClient.post("https://music.youtube.com/youtubei/v1/music/delete_privately_owned_entity") {+ contentType(ContentType.Application.Json)+ headers {+ append("Referer", YouTubeClient.REFERER_YOUTUBE_MUSIC)+ append("Origin", YouTubeClient.ORIGIN_YOUTUBE_MUSIC)+ cookie?.let { cookie ->+ append("cookie", cookie)+ if ("SAPISID" !in cookieMap) return@let+ val currentTime = System.currentTimeMillis() / 1000+ val sapisidHash = sha1("$currentTime ${cookieMap["SAPISID"]} ${YouTubeClient.ORIGIN_YOUTUBE_MUSIC}")+ append("Authorization", "SAPISIDHASH ${currentTime}_${sapisidHash}")+ }+ }+ parameter("key", "AIzaSyC9XL3ZjWddXya6X74dJoCTL-WEYFDNX3")+ parameter("prettyPrint", false)+ setBody(requestBody)+ }+ }++ suspend fun getMediaInfo(videoId: String): Result<MediaInfo> =+ runCatching {+ val response = next(client = YouTubeClient.WEB, videoId, null, null, null, null, null).body<NextResponse>()++ val baseForInfo =+ response.contents.twoColumnWatchNextResults+ ?.results+ ?.results+ ?.content+ ?.find {+ it?.videoSecondaryInfoRenderer != null+ }?.videoSecondaryInfoRenderer++ val baseForTitle =+ response.contents.twoColumnWatchNextResults+ ?.results+ ?.results+ ?.content+ ?.find {+ it?.videoPrimaryInfoRenderer != null+ }?.videoPrimaryInfoRenderer++ val returnYouTubeDislikeResponse =+ returnYouTubeDislike(videoId).body<ReturnYouTubeDislikeResponse>()++ return@runCatching MediaInfo(+ videoId = videoId,+ title = baseForTitle+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ author = baseForInfo+ ?.owner+ ?.videoOwnerRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ authorId =+ baseForInfo+ ?.owner+ ?.videoOwnerRenderer+ ?.navigationEndpoint+ ?.browseEndpoint+ ?.browseId,+ authorThumbnail =+ baseForInfo+ ?.owner+ ?.videoOwnerRenderer+ ?.thumbnail+ ?.thumbnails+ ?.find {+ it.height == 48+ }?.url+ ?.replace("s48", "s960"),+ description = baseForInfo?.attributedDescription?.content,+ subscribers =+ baseForInfo+ ?.owner+ ?.videoOwnerRenderer+ ?.subscriberCountText+ ?.simpleText?.split(" ")?.firstOrNull(),+ uploadDate = baseForTitle?.dateText?.simpleText,+ viewCount = returnYouTubeDislikeResponse.viewCount,+ like = returnYouTubeDislikeResponse.likes,+ dislike = returnYouTubeDislikeResponse.dislikes,+ )++ }+++}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/NetworkConfig.kt b/innertube/src/main/kotlin/com/metrolist/innertube/NetworkConfig.ktnew file mode 100644index 0000000..4af7424--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/NetworkConfig.kt@@ -0,0 +1,125 @@+package com.metrolist.innertube++import io.ktor.client.HttpClient+import io.ktor.client.engine.okhttp.OkHttp+import io.ktor.client.plugins.HttpTimeout+import io.ktor.client.plugins.compression.ContentEncoding+import io.ktor.client.plugins.contentnegotiation.ContentNegotiation+import io.ktor.serialization.kotlinx.json.json+import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.json.Json+import java.io.File+import java.util.concurrent.TimeUnit++/**+ * Enhanced network configuration for better performance and reliability+ * Inspired by ArchiveTune optimizations+ */+object NetworkConfig {++ // Timeout settings+ private const val CONNECT_TIMEOUT_SECONDS = 30L+ private const val READ_TIMEOUT_SECONDS = 60L+ private const val WRITE_TIMEOUT_SECONDS = 60L+ private const val REQUEST_TIMEOUT_MILLIS = 60000L++ // Cache settings+ private const val CACHE_SIZE_MB = 128L * 1024L * 1024L // 128 MB++ @OptIn(ExperimentalSerializationApi::class)+ fun createOptimizedHttpClient(+ cacheDir: File? = null,+ enableCache: Boolean = true+ ): HttpClient = HttpClient(OkHttp) {+ expectSuccess = true++ install(ContentNegotiation) {+ json(Json {+ ignoreUnknownKeys = true+ explicitNulls = false+ encodeDefaults = true+ isLenient = true+ })+ }++ install(ContentEncoding) {+ gzip(0.9F)+ deflate(0.8F)+ }++ install(HttpTimeout) {+ requestTimeoutMillis = REQUEST_TIMEOUT_MILLIS+ connectTimeoutMillis = CONNECT_TIMEOUT_SECONDS * 1000+ socketTimeoutMillis = READ_TIMEOUT_SECONDS * 1000+ }++ engine {+ config {+ // Timeout configurations+ connectTimeout(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)++ // Retry configuration+ retryOnConnectionFailure(true)++ // Cache configuration+ if (enableCache) {+ val cacheDirectory = cacheDir ?: File(System.getProperty("java.io.tmpdir"), "metrolist_http_cache")+ cache(okhttp3.Cache(cacheDirectory, CACHE_SIZE_MB))+ }+ }+ }+ }++ /**+ * Create a client specifically optimized for YouTube Music API+ */+ @OptIn(ExperimentalSerializationApi::class)+ fun createYouTubeMusicClient(+ cacheDir: File? = null+ ): HttpClient {+ val baseClient = createOptimizedHttpClient(cacheDir)+ return baseClient.config {+ // Additional configuration can be added here if needed+ }+ }++ /**+ * Network quality detection and adaptive configuration+ */+ fun getAdaptiveTimeouts(networkQuality: NetworkQuality): TimeoutConfig {+ return when (networkQuality) {+ NetworkQuality.EXCELLENT -> TimeoutConfig(+ connectTimeout = 10000L,+ readTimeout = 30000L,+ requestTimeout = 45000L+ )+ NetworkQuality.GOOD -> TimeoutConfig(+ connectTimeout = 20000L,+ readTimeout = 45000L,+ requestTimeout = 60000L+ )+ NetworkQuality.POOR -> TimeoutConfig(+ connectTimeout = 30000L,+ readTimeout = 60000L,+ requestTimeout = 90000L+ )+ NetworkQuality.UNKNOWN -> TimeoutConfig(+ connectTimeout = CONNECT_TIMEOUT_SECONDS * 1000,+ readTimeout = READ_TIMEOUT_SECONDS * 1000,+ requestTimeout = REQUEST_TIMEOUT_MILLIS+ )+ }+ }++ enum class NetworkQuality {+ EXCELLENT, GOOD, POOR, UNKNOWN+ }++ data class TimeoutConfig(+ val connectTimeout: Long,+ val readTimeout: Long,+ val requestTimeout: Long+ )+}\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.ktnew file mode 100644index 0000000..df5c15d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/YouTube.kt@@ -0,0 +1,3695 @@+package com.metrolist.innertube++import com.metrolist.innertube.models.AccountInfo+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.BrowseEndpoint+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.GridRenderer+import com.metrolist.innertube.models.MediaInfo+import com.metrolist.innertube.models.MusicCarouselShelfRenderer+import com.metrolist.innertube.models.MusicMultiRowListItemRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicShelfRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.Run+import com.metrolist.innertube.models.Runs+import com.metrolist.innertube.models.SearchSuggestions+import com.metrolist.innertube.models.SectionListRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.TasteArtist+import com.metrolist.innertube.models.TasteProfile+import com.metrolist.innertube.models.WatchEndpoint+import com.metrolist.innertube.models.WatchEndpoint.WatchEndpointMusicSupportedConfigs.WatchEndpointMusicConfig.Companion.MUSIC_VIDEO_TYPE_ATV+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.YouTubeClient+import com.metrolist.innertube.models.YouTubeClient.Companion.WEB+import com.metrolist.innertube.models.YouTubeClient.Companion.WEB_REMIX+import com.metrolist.innertube.models.YouTubeLocale+import com.metrolist.innertube.models.getContinuation+import com.metrolist.innertube.models.getItems+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime+import com.metrolist.innertube.models.response.AccountMenuResponse+import com.metrolist.innertube.models.response.BrowseResponse+import com.metrolist.innertube.models.response.CreatePlaylistResponse+import com.metrolist.innertube.models.response.EditPlaylistResponse+import com.metrolist.innertube.models.response.FeedbackResponse+import com.metrolist.innertube.models.response.GetQueueResponse+import com.metrolist.innertube.models.response.GetSearchSuggestionsResponse+import com.metrolist.innertube.models.response.GetTranscriptResponse+import com.metrolist.innertube.models.response.ImageUploadResponse+import com.metrolist.innertube.models.response.NextResponse+import com.metrolist.innertube.models.response.PlayerResponse+import com.metrolist.innertube.models.response.SearchResponse+import com.metrolist.innertube.pages.AlbumPage+import com.metrolist.innertube.pages.ArtistItemsContinuationPage+import com.metrolist.innertube.pages.ArtistItemsPage+import com.metrolist.innertube.pages.ArtistPage+import com.metrolist.innertube.pages.BrowseResult+import com.metrolist.innertube.pages.ChartsPage+import com.metrolist.innertube.pages.ExplorePage+import com.metrolist.innertube.pages.HistoryPage+import com.metrolist.innertube.pages.HomePage+import com.metrolist.innertube.pages.LibraryContinuationPage+import com.metrolist.innertube.pages.LibraryPage+import com.metrolist.innertube.pages.MoodAndGenres+import com.metrolist.innertube.pages.NewReleaseAlbumPage+import com.metrolist.innertube.pages.NextPage+import com.metrolist.innertube.pages.NextResult+import com.metrolist.innertube.pages.PageHelper+import com.metrolist.innertube.pages.PlaylistContinuationPage+import com.metrolist.innertube.pages.PlaylistPage+import com.metrolist.innertube.pages.PodcastPage+import com.metrolist.innertube.pages.RelatedPage+import com.metrolist.innertube.pages.SearchPage+import com.metrolist.innertube.pages.SearchResult+import com.metrolist.innertube.pages.SearchSuggestionPage+import com.metrolist.innertube.pages.SearchSummary+import com.metrolist.innertube.pages.SearchSummaryPage+import io.ktor.client.call.body+import io.ktor.client.statement.bodyAsText+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonPrimitive+import timber.log.Timber+import java.net.Proxy+import kotlin.random.Random++/**+ * Parse useful data with [InnerTube] sending requests.+ * Modified from [ViMusic](https://github.com/vfsfitvnm/ViMusic)+ */+object YouTube {+ private val innerTube = InnerTube()+ private const val ENABLE_NEWPIPE_STREAM_INFO_EXTRACTOR = false++ var locale: YouTubeLocale+ get() = innerTube.locale+ set(value) {+ innerTube.locale = value+ }+ var visitorData: String?+ get() = innerTube.visitorData+ set(value) {+ innerTube.visitorData = value+ }+ var dataSyncId: String?+ get() = innerTube.dataSyncId+ set(value) {+ innerTube.dataSyncId = value+ }+ var cookie: String?+ get() = innerTube.cookie+ set(value) {+ innerTube.cookie = value+ }+ var proxy: Proxy?+ get() = innerTube.proxy+ set(value) {+ innerTube.proxy = value+ }++ var proxyAuth: String?+ get() = innerTube.proxyAuth+ set(value) {+ innerTube.proxyAuth = value+ }+ var useLoginForBrowse: Boolean+ get() = innerTube.useLoginForBrowse+ set(value) {+ innerTube.useLoginForBrowse = value+ }++ suspend fun searchSuggestions(query: String): Result<SearchSuggestions> =+ runCatching {+ val response = innerTube.getSearchSuggestions(WEB_REMIX, query).body<GetSearchSuggestionsResponse>()+ SearchSuggestions(+ queries =+ response.contents+ ?.getOrNull(0)+ ?.searchSuggestionsSectionRenderer+ ?.contents+ ?.mapNotNull { content ->+ content.searchSuggestionRenderer+ ?.suggestion+ ?.runs+ ?.joinToString(separator = "") { it.text }+ }.orEmpty(),+ recommendedItems =+ response.contents+ ?.getOrNull(1)+ ?.searchSuggestionsSectionRenderer+ ?.contents+ ?.mapNotNull {+ it.musicResponsiveListItemRenderer?.let { renderer ->+ SearchSuggestionPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ }.orEmpty(),+ )+ }++ suspend fun searchSummary(query: String): Result<SearchSummaryPage> =+ runCatching {+ val response = innerTube.search(WEB_REMIX, query).body<SearchResponse>()+ val allSummaries = mutableListOf<SearchSummary>()++ response.contents+ ?.tabbedSearchResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.forEach { section ->+ if (section.musicCardShelfRenderer != null) {+ // Top result card - keep as single section+ val cardRenderer = section.musicCardShelfRenderer+ val cardArtists = if (cardRenderer.onTap.browseEndpoint?.isArtistEndpoint == true) {+ listOfNotNull(+ cardRenderer.title.runs?.firstOrNull()?.text?.let { name ->+ Artist(name, cardRenderer.onTap.browseEndpoint.browseId)+ },+ )+ } else {+ PageHelper.extractArtists(cardRenderer.subtitle.runs)+ }+ val items =+ listOfNotNull(SearchSummaryPage.fromMusicCardShelfRenderer(cardRenderer))+ .plus(+ cardRenderer.contents+ ?.mapNotNull { it.musicResponsiveListItemRenderer }+ ?.mapNotNull { renderer ->+ SearchSummaryPage.fromMusicResponsiveListItemRenderer(renderer, cardArtists)+ }+ .orEmpty(),+ ).distinctBy { it.id }++ if (items.isNotEmpty()) {+ allSummaries.add(+ SearchSummary(+ title =+ cardRenderer.header+ ?.musicCardShelfHeaderBasicRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: YouTubeConstants.DEFAULT_TOP_RESULT,+ items = items,+ ),+ )+ }+ } else if (section.musicShelfRenderer != null) {+ val items =+ section.musicShelfRenderer.contents+ ?.getItems()+ ?.mapNotNull { SearchSummaryPage.fromMusicResponsiveListItemRenderer(it) }+ ?.distinctBy { it.id }+ ?: emptyList()++ if (items.isEmpty()) return@forEach++ val apiTitle =+ section.musicShelfRenderer.title+ ?.runs+ ?.firstOrNull()+ ?.text++ if (apiTitle != null) {+ // API provided a title, use single section+ allSummaries.add(SearchSummary(title = apiTitle, items = items))+ } else {+ allSummaries.addAll(groupItemsByType(items))+ }+ } else if (section.itemSectionRenderer != null) {+ val items =+ section.itemSectionRenderer.contents+ ?.mapNotNull { it.musicResponsiveListItemRenderer }+ ?.mapNotNull { SearchSummaryPage.fromMusicResponsiveListItemRenderer(it) }+ ?.distinctBy { it.id }+ ?: emptyList()++ if (items.isNotEmpty()) {+ allSummaries.addAll(groupItemsByType(items))+ }+ }+ }++ // Merge sections with the same title+ val mergedSummaries =+ allSummaries+ .groupBy { it.title }+ .map { (title, sections) ->+ SearchSummary(+ title = title,+ items = sections.flatMap { it.items }.distinctBy { it.id },+ )+ }+ // Reorder to maintain logical order+ .sortedBy { summary ->+ when (summary.title) {+ YouTubeConstants.DEFAULT_TOP_RESULT -> 0+ "Songs" -> 1+ "Videos" -> 2+ "Albums" -> 3+ "Artists" -> 4+ "Playlists" -> 5+ "Podcasts" -> 6+ "Episodes" -> 7+ "Profiles" -> 8+ else -> 9+ }+ }++ SearchSummaryPage(summaries = mergedSummaries)+ }++ private fun groupItemsByType(items: List<YTItem>): List<SearchSummary> {+ val grouped =+ items.groupBy { item ->+ when (item) {+ is EpisodeItem -> "Episodes"+ is PodcastItem -> "Podcasts"+ is AlbumItem -> "Albums"+ is ArtistItem -> if (item.isProfile) "Profiles" else "Artists"+ is PlaylistItem -> "Playlists"+ is SongItem -> when {+ item.isEpisode -> "Episodes"+ item.isVideoSong -> "Videos"+ else -> "Songs"+ }+ }+ }++ val sectionOrder =+ listOf(+ "Songs", "Videos", "Albums", "Artists", "Playlists",+ "Podcasts", "Episodes", "Profiles", YouTubeConstants.DEFAULT_OTHER_RESULTS,+ )++ return sectionOrder.mapNotNull { sectionName ->+ grouped[sectionName]?.takeIf { it.isNotEmpty() }?.let { groupItems ->+ SearchSummary(title = sectionName, items = groupItems)+ }+ }+ }++ suspend fun search(+ query: String,+ filter: SearchFilter,+ ): Result<SearchResult> =+ runCatching {+ val response = innerTube.search(WEB_REMIX, query, filter.value).body<SearchResponse>()+ val searchItems = mutableListOf<YTItem>()+ var searchContinuation: String? = null++ response.contents+ ?.tabbedSearchResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.forEach { section ->+ if (section.musicShelfRenderer != null) {+ val shelf = section.musicShelfRenderer+ val items = shelf.contents?.getItems()?.mapNotNull { SearchPage.toYTItem(it) } ?: emptyList()+ searchItems.addAll(items)+ if (searchContinuation == null) {+ searchContinuation = shelf.continuations?.getContinuation()+ }+ } else if (section.itemSectionRenderer != null) {+ val items =+ section.itemSectionRenderer.contents+ ?.mapNotNull { it.musicResponsiveListItemRenderer }+ ?.mapNotNull { SearchPage.toYTItem(it) }+ ?: emptyList()+ searchItems.addAll(items)+ }+ }++ SearchResult(+ items = searchItems.distinctBy { it.id },+ continuation = searchContinuation,+ )+ }++ suspend fun searchContinuation(continuation: String): Result<SearchResult> =+ runCatching {+ val response = innerTube.search(WEB_REMIX, continuation = continuation).body<SearchResponse>()+ val items =+ response.continuationContents+ ?.musicShelfContinuation+ ?.contents+ ?.mapNotNull {+ SearchPage.toYTItem(it.musicResponsiveListItemRenderer)+ } ?: emptyList()+ SearchResult(+ items = items,+ continuation =+ if (items.isEmpty()) {+ null+ } else {+ response.continuationContents+ ?.musicShelfContinuation+ ?.continuations+ ?.getContinuation()+ },+ )+ }++ suspend fun album(+ browseId: String,+ withSongs: Boolean = true,+ ): Result<AlbumPage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, browseId).body<BrowseResponse>()+ if (browseId.contains("FEmusic_library_privately_owned_release_detail")) {+ val playlistId =+ response.header+ ?.musicDetailHeaderRenderer+ ?.menu+ ?.menuRenderer+ ?.topLevelButtons+ ?.firstOrNull()+ ?.buttonRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId!!+ val albumItem =+ AlbumItem(+ browseId = browseId,+ playlistId = playlistId,+ title =+ response.header.musicDetailHeaderRenderer.title.runs+ ?.firstOrNull()+ ?.text!!,+ artists =+ response.header.musicDetailHeaderRenderer.subtitle.runs?.filter { it.navigationEndpoint != null }?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ year =+ response.header.musicDetailHeaderRenderer.subtitle.runs+ ?.lastOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail =+ response.header.musicDetailHeaderRenderer.thumbnail.croppedSquareThumbnailRenderer+ ?.thumbnail+ ?.thumbnails+ ?.lastOrNull()!!+ .url,+ explicit = false, // TODO: Extract explicit badge for albums from YouTube response+ )+ return@runCatching AlbumPage(+ album = albumItem,+ songs =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.contents+ ?.getItems()+ ?.mapNotNull {+ AlbumPage.getSong(it, albumItem)+ }!!+ .toMutableList(),+ otherVersions = emptyList(),+ )+ } else {+ val playlistId =+ response.microformat+ ?.microformatDataRenderer+ ?.urlCanonical+ ?.substringAfterLast('=')!!+ val albumItem =+ AlbumItem(+ browseId = browseId,+ playlistId = playlistId,+ title =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text!!,+ artists =+ response.contents.twoColumnBrowseResultsRenderer.tabs+ .firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer+ ?.straplineTextOne+ ?.runs+ ?.oddElements()+ ?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ }!!,+ year =+ response.contents.twoColumnBrowseResultsRenderer.tabs+ .firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer+ ?.subtitle+ ?.runs+ ?.lastOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail =+ response.contents.twoColumnBrowseResultsRenderer.tabs+ .firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.thumbnail+ ?.thumbnails+ ?.lastOrNull()+ ?.url!!,+ explicit = false, // TODO: Extract explicit badge for albums from YouTube response+ )+ val albumSongsList =+ if (withSongs) {+ albumSongs(+ playlistId,+ albumItem,+ ).getOrThrow()+ } else {+ emptyList()+ }+ // When YouTube credits the album to a label/distributor channel (the header+ // strapline) but every track names the same performing artist, surface the+ // performer as the album artist instead of the label.+ val performer =+ albumSongsList.firstOrNull()?.artists?.firstOrNull()?.takeIf { first ->+ first.name.isNotBlank() &&+ albumSongsList.all { it.artists.firstOrNull()?.name == first.name }+ }+ val resolvedAlbum =+ if (performer != null && albumItem.artists?.any { it.name == performer.name } != true) {+ albumItem.copy(artists = listOf(performer))+ } else {+ albumItem+ }+ return@runCatching AlbumPage(+ album = resolvedAlbum,+ songs = albumSongsList,+ otherVersions =+ response.contents.twoColumnBrowseResultsRenderer.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.getOrNull(+ 1,+ )?.musicCarouselShelfRenderer+ ?.contents+ ?.mapNotNull { it.musicTwoRowItemRenderer }+ ?.mapNotNull(NewReleaseAlbumPage::fromMusicTwoRowItemRenderer)+ .orEmpty(),+ )+ }+ }++ suspend fun albumSongs(+ playlistId: String,+ album: AlbumItem? = null,+ ): Result<List<SongItem>> =+ runCatching {+ var response = innerTube.browse(WEB_REMIX, "VL$playlistId").body<BrowseResponse>()+ val shelf =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val shelfContents =+ shelf?.musicPlaylistShelfRenderer?.contents+ ?: shelf?.musicShelfRenderer?.contents+ ?: emptyList()+ val songs =+ shelfContents+ .getItems()+ .mapNotNull {+ AlbumPage.getSong(it, album)+ }+ .toMutableList()+ var continuation =+ shelfContents+ .getContinuation()+ val seenContinuations = mutableSetOf<String>()+ var requestCount = 0+ val maxRequests = 50 // Prevent excessive API calls++ while (continuation != null && requestCount < maxRequests) {+ // Prevent infinite loops by tracking seen continuations+ if (continuation in seenContinuations) {+ break+ }+ seenContinuations.add(continuation)+ requestCount++++ response =+ innerTube+ .browse(+ client = WEB_REMIX,+ continuation = continuation,+ ).body<BrowseResponse>()+ songs +=+ response.onResponseReceivedActions+ ?.firstOrNull()+ ?.appendContinuationItemsAction+ ?.continuationItems+ ?.getItems()+ ?.mapNotNull {+ AlbumPage.getSong(it, album)+ }.orEmpty()+ continuation =+ response.continuationContents+ ?.musicPlaylistShelfContinuation+ ?.continuations+ ?.getContinuation()+ }+ songs+ }++ suspend fun artist(browseId: String): Result<ArtistPage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, browseId).body<BrowseResponse>()++ fun mapRuns(runs: List<Run>?): List<Run>? =+ runs?.map { run ->+ Run(+ text = run.text,+ navigationEndpoint = run.navigationEndpoint,+ )+ }++ val descriptionRuns =+ response.contents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull { it.musicDescriptionShelfRenderer != null }+ ?.musicDescriptionShelfRenderer+ ?.description+ ?.runs+ ?.let(::mapRuns)+ ?: response.header+ ?.musicImmersiveHeaderRenderer+ ?.description+ ?.runs+ ?.let(::mapRuns)++ // Check subscription state from multiple locations:+ // 1. musicImmersiveHeaderRenderer.subscriptionButton (regular artists)+ // 2. musicVisualHeaderRenderer.subscriptionButton (podcast channels)+ val immersiveSubscribed =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.subscribed+ val visualSubscribed =+ response.header+ ?.musicVisualHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.subscribed+ val isSubscribed = immersiveSubscribed ?: visualSubscribed ?: false++ // Also extract channelId from visual header if not in immersive header+ val channelIdFromVisual =+ response.header+ ?.musicVisualHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.channelId++ ArtistPage(+ artist =+ ArtistItem(+ id = browseId,+ title =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: response.header+ ?.musicVisualHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: response.header+ ?.musicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text!!,+ thumbnail =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ ?: response.header+ ?.musicVisualHeaderRenderer+ ?.foregroundThumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ ?: response.header+ ?.musicDetailHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl(),+ channelId =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.channelId+ ?: channelIdFromVisual,+ playEndpoint =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveListItemRenderer+ ?.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchEndpoint,+ shuffleEndpoint =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.playButton+ ?.buttonRenderer+ ?.navigationEndpoint+ ?.watchEndpoint+ ?: response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveListItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ radioEndpoint =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.startRadioButton+ ?.buttonRenderer+ ?.navigationEndpoint+ ?.watchEndpoint,+ ),+ sections =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.mapNotNull(ArtistPage::fromSectionListRendererContent)!!,+ description = descriptionRuns?.joinToString(separator = "") { it.text },+ subscriberCountText =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.subscriptionButton2+ ?.subscribeButtonRenderer+ ?.subscriberCountWithSubscribeText+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: response.header+ ?.musicImmersiveHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.longSubscriberCountText+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: response.header+ ?.musicImmersiveHeaderRenderer+ ?.subscriptionButton+ ?.subscribeButtonRenderer+ ?.shortSubscriberCountText+ ?.runs+ ?.firstOrNull()+ ?.text,+ monthlyListenerCount =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.monthlyListenerCount+ ?.runs+ ?.firstOrNull()+ ?.text,+ descriptionRuns = descriptionRuns,+ isSubscribed = isSubscribed,+ )+ }++ suspend fun artistItems(endpoint: BrowseEndpoint): Result<ArtistItemsPage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, endpoint.browseId, endpoint.params).body<BrowseResponse>()+ val sectionContent =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()++ val gridRenderer = sectionContent?.gridRenderer+ val musicCarouselShelfRenderer = sectionContent?.musicCarouselShelfRenderer+ val musicPlaylistShelfRenderer = sectionContent?.musicPlaylistShelfRenderer+ val musicShelfRenderer = sectionContent?.musicShelfRenderer++ when {+ gridRenderer != null -> {+ ArtistItemsPage(+ title =+ gridRenderer.header+ ?.gridHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ .orEmpty(),+ items =+ gridRenderer.items.mapNotNull {+ it.musicTwoRowItemRenderer?.let { renderer ->+ ArtistItemsPage.fromMusicTwoRowItemRenderer(renderer)+ }+ },+ continuation = gridRenderer.continuations?.getContinuation(),+ )+ }++ musicCarouselShelfRenderer != null -> {+ ArtistItemsPage(+ title =+ musicCarouselShelfRenderer.header+ ?.musicCarouselShelfBasicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ .orEmpty(),+ items =+ musicCarouselShelfRenderer.contents.mapNotNull { content ->+ content.musicTwoRowItemRenderer?.let { renderer ->+ ArtistItemsPage.fromMusicTwoRowItemRenderer(renderer)+ } ?: content.musicResponsiveListItemRenderer?.let { renderer ->+ ArtistItemsPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ },+ continuation = null,+ )+ }++ musicShelfRenderer != null -> {+ ArtistItemsPage(+ title =+ musicShelfRenderer.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: response.header+ ?.musicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: "",+ items =+ musicShelfRenderer.contents?.getItems()?.mapNotNull {+ ArtistItemsPage.fromMusicResponsiveListItemRenderer(it)+ } ?: emptyList(),+ continuation = musicShelfRenderer.continuations?.getContinuation(),+ )+ }++ else -> {+ ArtistItemsPage(+ title =+ response.header+ ?.musicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text ?: "",+ items =+ musicPlaylistShelfRenderer?.contents?.getItems()?.mapNotNull {+ ArtistItemsPage.fromMusicResponsiveListItemRenderer(it)+ } ?: emptyList(),+ continuation = musicPlaylistShelfRenderer?.contents?.getContinuation(),+ )+ }+ }+ }++ suspend fun artistItemsContinuation(continuation: String): Result<ArtistItemsContinuationPage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, continuation = continuation).body<BrowseResponse>()++ when {+ response.continuationContents?.gridContinuation != null -> {+ val gridContinuation = response.continuationContents.gridContinuation+ val items =+ gridContinuation.items.mapNotNull {+ it.musicTwoRowItemRenderer?.let { renderer ->+ ArtistItemsPage.fromMusicTwoRowItemRenderer(renderer)+ }+ }+ ArtistItemsContinuationPage(+ items = items,+ continuation = if (items.isEmpty()) null else gridContinuation.continuations?.getContinuation(),+ )+ }++ response.continuationContents?.musicPlaylistShelfContinuation != null -> {+ val musicPlaylistShelfContinuation = response.continuationContents.musicPlaylistShelfContinuation+ val items =+ musicPlaylistShelfContinuation.contents.getItems().mapNotNull {+ ArtistItemsPage.fromMusicResponsiveListItemRenderer(it)+ }+ ArtistItemsContinuationPage(+ items = items,+ continuation = if (items.isEmpty()) null else musicPlaylistShelfContinuation.continuations?.getContinuation(),+ )+ }++ else -> {+ val continuationItems =+ response.onResponseReceivedActions+ ?.firstOrNull()+ ?.appendContinuationItemsAction+ ?.continuationItems+ val items =+ continuationItems?.getItems()?.mapNotNull {+ ArtistItemsPage.fromMusicResponsiveListItemRenderer(it)+ } ?: emptyList()+ ArtistItemsContinuationPage(+ items = items,+ continuation = if (items.isEmpty()) null else continuationItems?.getContinuation(),+ )+ }+ }+ }++ suspend fun playlist(playlistId: String): Result<PlaylistPage> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "VL$playlistId",+ setLogin = true,+ ).body<BrowseResponse>()+ val base =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val header =+ base?.musicResponsiveHeaderRenderer+ ?: base?.musicEditablePlaylistDetailHeaderRenderer?.header?.musicResponsiveHeaderRenderer++ val editable = base?.musicEditablePlaylistDetailHeaderRenderer != null++ val description: String? =+ header?.description?.musicDescriptionShelfRenderer?.description?.runs?.joinToString("") { it.text }+ ?: base?.musicEditablePlaylistDetailHeaderRenderer+ ?.header?.musicDetailHeaderRenderer+ ?.description?.runs?.joinToString("") { it.text }+ ?: response.header?.musicDetailHeaderRenderer+ ?.description?.runs?.joinToString("") { it.text }++ val author: Artist? = run {+ val fromStrapline = header?.straplineTextOne?.runs+ ?.firstOrNull()+ ?.let { Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId) }+ if (fromStrapline != null) return@run fromStrapline++ val detailSubtitle = base?.musicEditablePlaylistDetailHeaderRenderer+ ?.header?.musicDetailHeaderRenderer?.subtitle?.runs+ ?: response.header?.musicDetailHeaderRenderer?.subtitle?.runs+ if (detailSubtitle != null) {+ val segments = detailSubtitle.splitBySeparator()+ val run = segments.getOrNull(1)?.firstOrNull()+ ?: segments.firstOrNull()?.firstOrNull()+ val fromDetail = run?.let {+ Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId)+ }+ if (fromDetail != null) return@run fromDetail+ }++ val fromHeaderSubtitle = header?.subtitle?.runs+ ?.firstOrNull { it.navigationEndpoint != null }+ ?.let { Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId) }+ if (fromHeaderSubtitle != null) return@run fromHeaderSubtitle++ val facepile = header?.facepile?.avatarStackViewModel+ if (facepile != null) {+ val name = facepile.text?.content+ val browseId = facepile.rendererContext?.commandContext?.onTap?.innertubeCommand?.browseEndpoint?.browseId+ if (name != null) return@run Artist(name = name, id = browseId)+ }++ val fromMusicHeaderStrapline = response.header?.musicHeaderRenderer+ ?.straplineTextOne?.runs?.firstOrNull()+ ?.let { Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId) }+ if (fromMusicHeaderStrapline != null) return@run fromMusicHeaderStrapline++ null+ }++ val authorAvatarUrl: String? = header?.facepile+ ?.avatarStackViewModel?.avatars?.firstOrNull()+ ?.avatarViewModel?.image?.sources?.firstOrNull()+ ?.url++ PlaylistPage(+ playlist =+ PlaylistItem(+ id = playlistId,+ title =+ header?.title?.runs?.firstOrNull()?.text+ ?: response.header?.musicHeaderRenderer?.title?.runs?.firstOrNull()?.text+ ?: "",+ author = author,+ songCountText =+ (header?.secondSubtitle+ ?: response.header?.musicHeaderRenderer?.secondSubtitle)+ ?.runs+ ?.findLast {+ it.text.any { c -> c.isDigit() } &&+ !it.text.contains("view", ignoreCase = true) &&+ !it.text.contains("hour", ignoreCase = true) &&+ !it.text.contains("minute", ignoreCase = true)+ }?.text,+ thumbnail =+ header?.thumbnail+ ?.musicThumbnailRenderer+ ?.thumbnail+ ?.thumbnails+ ?.lastOrNull()+ ?.url+ ?: response.header+ ?.musicHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.thumbnails+ ?.lastOrNull()+ ?.url+ ?: "",+ playEndpoint = null,+ shuffleEndpoint =+ header?.buttons?.lastOrNull()+ ?.menuRenderer?.items?.firstOrNull()+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint+ ?: response.header?.musicHeaderRenderer?.buttons?.lastOrNull()+ ?.menuRenderer?.items?.firstOrNull()+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ radioEndpoint =+ header?.buttons?.getOrNull(2)+ ?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint+ ?: response.header?.musicHeaderRenderer?.buttons?.getOrNull(2)+ ?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ isEditable = editable,+ description = description,+ authorAvatarUrl = authorAvatarUrl,+ ),+ songs = run {+ val twoColShelf =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val twoColContents =+ twoColShelf?.musicPlaylistShelfRenderer?.contents+ ?: twoColShelf?.musicShelfRenderer?.contents+ val singleColShelf =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val singleColContents =+ singleColShelf?.musicPlaylistShelfRenderer?.contents+ ?: singleColShelf?.musicShelfRenderer?.contents+ (twoColContents ?: singleColContents)+ ?.getItems()+ ?.mapNotNull { PlaylistPage.fromMusicResponsiveListItemRenderer(it) }+ ?: emptyList()+ },+ songsContinuation = run {+ val twoColShelf =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val twoColContents =+ twoColShelf?.musicPlaylistShelfRenderer?.contents+ ?: twoColShelf?.musicShelfRenderer?.contents+ val twoColContinuations =+ twoColShelf?.musicPlaylistShelfRenderer?.continuations+ ?: twoColShelf?.musicShelfRenderer?.continuations+ val singleColShelf =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ val singleColContents =+ singleColShelf?.musicPlaylistShelfRenderer?.contents+ ?: singleColShelf?.musicShelfRenderer?.contents+ val singleColContinuations =+ singleColShelf?.musicPlaylistShelfRenderer?.continuations+ ?: singleColShelf?.musicShelfRenderer?.continuations+ val mergedContents = twoColContents ?: singleColContents+ val mergedContinuations = twoColContinuations ?: singleColContinuations+ mergedContents?.getContinuation() ?: mergedContinuations?.getContinuation()+ },+ continuation =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.continuations+ ?.getContinuation(),+ )+ }++ suspend fun playlistContinuation(continuation: String): Result<PlaylistContinuationPage> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ continuation = continuation,+ setLogin = true,+ ).body<BrowseResponse>()++ val mainContents: List<MusicShelfRenderer.Content> =+ response.continuationContents+ ?.sectionListContinuation+ ?.contents+ ?.mapNotNull { content: SectionListRenderer.Content ->+ content.musicPlaylistShelfRenderer?.contents+ ?: content.musicShelfRenderer?.contents+ }+ ?.flatten()+ ?: emptyList()++ val shelfContents: List<MusicShelfRenderer.Content> =+ response.continuationContents?.musicPlaylistShelfContinuation?.contents ?: emptyList()++ val musicShelfContinuationContents: List<MusicShelfRenderer.Content> =+ response.continuationContents?.musicShelfContinuation?.contents ?: emptyList()++ val appendedContents: List<MusicShelfRenderer.Content> =+ response.onResponseReceivedActions+ ?.firstOrNull()+ ?.appendContinuationItemsAction+ ?.continuationItems+ .orEmpty()++ val allContents = mainContents + shelfContents + musicShelfContinuationContents + appendedContents++ val songs =+ allContents+ .mapNotNull { content: MusicShelfRenderer.Content -> content.musicResponsiveListItemRenderer }+ .mapNotNull { renderer -> PlaylistPage.fromMusicResponsiveListItemRenderer(renderer) }++ val nextContinuation =+ if (songs.isEmpty()) {+ null+ } else {+ response.continuationContents+ ?.sectionListContinuation+ ?.continuations+ ?.getContinuation()+ ?: response.continuationContents+ ?.musicPlaylistShelfContinuation+ ?.continuations+ ?.getContinuation()+ ?: response.continuationContents+ ?.musicShelfContinuation+ ?.continuations+ ?.getContinuation()+ ?: response.onResponseReceivedActions+ ?.firstOrNull()+ ?.appendContinuationItemsAction+ ?.continuationItems+ ?.getContinuation()+ }++ PlaylistContinuationPage(+ songs = songs,+ continuation = nextContinuation,+ )+ }++ suspend fun podcast(podcastId: String): Result<PodcastPage> = podcastWithDebug(podcastId) { }++ suspend fun podcastWithDebug(+ podcastId: String,+ log: (String) -> Unit,+ ): Result<PodcastPage> =+ runCatching {+ Timber.d("Fetching podcast with ID: $podcastId")+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = podcastId,+ setLogin = true,+ ).body<BrowseResponse>()++ Timber.d("Response received, twoColumnBrowseResultsRenderer: ${response.contents?.twoColumnBrowseResultsRenderer != null}")+ Timber.d("singleColumnBrowseResultsRenderer: ${response.contents?.singleColumnBrowseResultsRenderer != null}")++ // Try twoColumn first (standard layout)+ var header =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer++ // Fallback to singleColumn layout+ if (header == null) {+ header =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicResponsiveHeaderRenderer+ Timber.d("Using singleColumn layout, header found: ${header != null}")+ }++ Timber.d("Header title: ${header?.title?.runs?.firstOrNull()?.text}")++ // Debug: Log button structure+ header?.buttons?.forEachIndexed { i, button ->+ Timber.d(+ "[PODCAST] Button[$i]: menuRenderer=${button.menuRenderer != null}, toggleButtonRenderer=${button.toggleButtonRenderer != null}, playButtonRenderer=${button.musicPlayButtonRenderer != null}",+ )+ button.menuRenderer?.items?.forEachIndexed { j, item ->+ Timber.d(+ "[PODCAST] Button[$i].menuItems[$j]: toggle=${item.toggleMenuServiceItemRenderer?.defaultIcon?.iconType}, nav=${item.menuNavigationItemRenderer?.icon?.iconType}",+ )+ // Check for SUBSCRIBE button (like artists have)+ if (item.toggleMenuServiceItemRenderer?.defaultIcon?.iconType == "SUBSCRIBE") {+ val channelIds =+ item.toggleMenuServiceItemRenderer.defaultServiceEndpoint.subscribeEndpoint+ ?.channelIds+ Timber.d("[PODCAST] Found SUBSCRIBE button! channelIds=$channelIds")+ }+ }+ button.toggleButtonRenderer?.let { toggle ->+ Timber.d(+ "[PODCAST] Button[$i].toggleButtonRenderer: defaultIcon=${toggle.defaultIcon?.iconType}, defaultToken=${toggle.defaultServiceEndpoint?.feedbackEndpoint?.feedbackToken?.take(+ 30,+ )}, subscribeChannelIds=${toggle.defaultServiceEndpoint?.subscribeEndpoint?.channelIds}",+ )+ }+ }++ // Extract channelId and subscription state for subscription (like artists)+ val subscribeToggle =+ header+ ?.buttons+ ?.flatMap { button ->+ button.menuRenderer?.items ?: emptyList()+ }?.find {+ it.toggleMenuServiceItemRenderer?.defaultIcon?.iconType == "SUBSCRIBE"+ }?.toggleMenuServiceItemRenderer+ val channelId =+ subscribeToggle+ ?.defaultServiceEndpoint+ ?.subscribeEndpoint+ ?.channelIds+ ?.firstOrNull()+ // isSelected indicates user is currently subscribed (toggle is in "toggled" state)+ val isChannelSubscribed = subscribeToggle?.isSelected == true+ Timber.d("[PODCAST] Extracted channelId for subscription: $channelId, isSubscribed: $isChannelSubscribed")++ // Extract library tokens from the header's menu buttons OR toggle buttons+ var libraryTokens =+ header+ ?.buttons+ ?.flatMap { button ->+ button.menuRenderer?.items ?: emptyList()+ }?.let { menuItems ->+ PageHelper.extractLibraryTokensFromMenuItems(menuItems)+ }++ // Also check for standalone toggle buttons (used by some podcasts)+ if (libraryTokens?.addToken == null && libraryTokens?.removeToken == null) {+ header?.buttons?.forEach { button ->+ button.toggleButtonRenderer?.let { toggle ->+ val iconType = toggle.defaultIcon?.iconType+ if (iconType != null && PageHelper.isLibraryIcon(iconType)) {+ val defaultToken = toggle.defaultServiceEndpoint?.feedbackEndpoint?.feedbackToken+ val toggledToken = toggle.toggledServiceEndpoint?.feedbackEndpoint?.feedbackToken+ libraryTokens =+ if (PageHelper.isAddLibraryIcon(iconType)) {+ // BOOKMARK_BORDER: default=add, toggled=remove+ PageHelper.LibraryFeedbackTokens(defaultToken, toggledToken)+ } else {+ // BOOKMARK: default=remove, toggled=add+ PageHelper.LibraryFeedbackTokens(toggledToken, defaultToken)+ }+ Timber.d(+ "[PODCAST] Found toggle button with library tokens - add: ${libraryTokens.addToken != null}, remove: ${libraryTokens.removeToken != null}",+ )+ }+ }+ }+ }+ Timber.d("[PODCAST] Library tokens - add: ${libraryTokens?.addToken != null}, remove: ${libraryTokens?.removeToken != null}")++ val podcastItem =+ PodcastItem(+ id = podcastId,+ title =+ header+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text ?: "",+ author =+ header?.straplineTextOne?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ episodeCountText =+ header+ ?.secondSubtitle+ ?.runs+ ?.firstOrNull()+ ?.text,+ thumbnail =+ header+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.thumbnail+ ?.thumbnails+ ?.lastOrNull()+ ?.url,+ playEndpoint =+ header+ ?.buttons+ ?.find {+ it.menuRenderer+ ?.items+ ?.firstOrNull()+ ?.menuNavigationItemRenderer+ ?.icon+ ?.iconType == "PLAY_ARROW"+ }?.menuRenderer+ ?.items+ ?.firstOrNull()+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint =+ header+ ?.buttons+ ?.find {+ it.menuRenderer?.items?.any { item ->+ item.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ } ==+ true+ }?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ libraryAddToken = libraryTokens?.addToken,+ libraryRemoveToken = libraryTokens?.removeToken,+ channelId = channelId,+ )++ // Try twoColumn for episodes+ val secondaryContents = response.contents?.twoColumnBrowseResultsRenderer?.secondaryContents+ Timber.d("secondaryContents null: ${secondaryContents == null}")+ Timber.d("secondaryContents.sectionListRenderer null: ${secondaryContents?.sectionListRenderer == null}")+ Timber.d("sectionListRenderer.contents size: ${secondaryContents?.sectionListRenderer?.contents?.size ?: 0}")++ secondaryContents?.sectionListRenderer?.contents?.forEachIndexed { index, content ->+ Timber.d(+ "Content[$index]: musicShelfRenderer=${content.musicShelfRenderer != null}, musicPlaylistShelfRenderer=${content.musicPlaylistShelfRenderer != null}, gridRenderer=${content.gridRenderer != null}",+ )+ content.musicShelfRenderer?.let { shelf ->+ Timber.d("musicShelfRenderer.contents size: ${shelf.contents?.size ?: 0}")+ }+ content.musicPlaylistShelfRenderer?.let { shelf ->+ Timber.d("musicPlaylistShelfRenderer.contents size: ${shelf.contents.size}")+ }+ }++ var episodeContents =+ secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.contents++ // Try musicPlaylistShelfRenderer+ if (episodeContents == null) {+ episodeContents =+ secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicPlaylistShelfRenderer+ ?.contents+ Timber.d("Trying musicPlaylistShelfRenderer: ${episodeContents?.size ?: 0}")+ }++ // Fallback to singleColumn+ if (episodeContents == null) {+ episodeContents =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.find { it.musicShelfRenderer != null }+ ?.musicShelfRenderer+ ?.contents+ Timber.d("Using singleColumn for episodes, found: ${episodeContents?.size ?: 0}")+ }++ Timber.d("Episode contents count: ${episodeContents?.size ?: 0}")++ // Get episodes from musicMultiRowListItemRenderer (used for podcasts)+ val multiRowItems = episodeContents?.mapNotNull { it.musicMultiRowListItemRenderer } ?: emptyList()+ Timber.d("multiRowItems count: ${multiRowItems.size}")++ multiRowItems.take(2).forEachIndexed { idx, renderer ->+ Timber.d("Episode[$idx] title: ${renderer.title?.runs?.firstOrNull()?.text}")+ Timber.d("Episode[$idx] subtitle: ${renderer.subtitle?.runs?.map { it.text }}")+ Timber.d("Episode[$idx] videoId: ${renderer.onTap?.watchEndpoint?.videoId}")+ Timber.d("Episode[$idx] thumbnail: ${renderer.thumbnail?.getThumbnailUrl()}")+ }++ val episodes =+ multiRowItems.mapNotNull { renderer ->+ PodcastPage.fromMusicMultiRowListItemRenderer(renderer, podcastItem)+ }++ Timber.d("Parsed episodes: ${episodes.size}")++ PodcastPage(+ podcast = podcastItem,+ episodes = episodes,+ continuation =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.continuations+ ?.getContinuation()+ ?: response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.find { it.musicShelfRenderer != null }+ ?.musicShelfRenderer+ ?.continuations+ ?.getContinuation(),+ isChannelSubscribed = isChannelSubscribed,+ )+ }++ suspend fun home(+ continuation: String? = null,+ params: String? = null,+ ): Result<HomePage> =+ runCatching {+ Timber.d("home() called with continuation=$continuation, params=$params")+ if (continuation != null) {+ return@runCatching homeContinuation(continuation).getOrThrow()+ }++ val response = innerTube.browse(WEB_REMIX, browseId = "FEmusic_home", params = params).body<BrowseResponse>()+ Timber.d("home() response received")+ val continuation =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.continuations+ ?.getContinuation()+ val sectionListRender =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ Timber.d("home() sectionListRender contents size: ${sectionListRender?.contents?.size ?: 0}")+ val carousels = sectionListRender?.contents?.mapNotNull { it.musicCarouselShelfRenderer } ?: emptyList()+ Timber.d("home() carousels count: ${carousels.size}")+ val sections =+ carousels+ .mapNotNull {+ HomePage.Section.fromMusicCarouselShelfRenderer(it)+ }.toMutableList()+ Timber.d("home() sections parsed: ${sections.size}")+ val chips =+ sectionListRender+ ?.header+ ?.chipCloudRenderer+ ?.chips+ ?.mapNotNull { HomePage.Chip.fromChipCloudChipRenderer(it) }+ Timber.d("home() chips: ${chips?.size ?: 0}")+ HomePage(chips, sections, continuation)+ }++ private suspend fun homeContinuation(continuation: String): Result<HomePage> =+ runCatching {+ val response =+ innerTube.browse(WEB_REMIX, continuation = continuation).body<BrowseResponse>()+ val continuation =+ response.continuationContents+ ?.sectionListContinuation+ ?.continuations+ ?.getContinuation()+ HomePage(+ null,+ response.continuationContents+ ?.sectionListContinuation+ ?.contents+ ?.mapNotNull { it.musicCarouselShelfRenderer }+ ?.mapNotNull {+ HomePage.Section.fromMusicCarouselShelfRenderer(it)+ }.orEmpty(),+ continuation,+ )+ }++ suspend fun explore(): Result<ExplorePage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, browseId = "FEmusic_explore").body<BrowseResponse>()+ ExplorePage(+ newReleaseAlbums =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.find {+ it.musicCarouselShelfRenderer+ ?.header+ ?.musicCarouselShelfBasicHeaderRenderer+ ?.moreContentButton+ ?.buttonRenderer+ ?.navigationEndpoint+ ?.browseEndpoint+ ?.browseId ==+ "FEmusic_new_releases_albums"+ }?.musicCarouselShelfRenderer+ ?.contents+ ?.mapNotNull { it.musicTwoRowItemRenderer }+ ?.mapNotNull(NewReleaseAlbumPage::fromMusicTwoRowItemRenderer)+ .orEmpty(),+ moodAndGenres =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.find {+ it.musicCarouselShelfRenderer+ ?.header+ ?.musicCarouselShelfBasicHeaderRenderer+ ?.moreContentButton+ ?.buttonRenderer+ ?.navigationEndpoint+ ?.browseEndpoint+ ?.browseId ==+ "FEmusic_moods_and_genres"+ }?.musicCarouselShelfRenderer+ ?.contents+ ?.mapNotNull { it.musicNavigationButtonRenderer }+ ?.mapNotNull(MoodAndGenres.Companion::fromMusicNavigationButtonRenderer)+ .orEmpty(),+ )+ }++ suspend fun newReleaseAlbums(): Result<List<AlbumItem>> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, browseId = "FEmusic_new_releases_albums").body<BrowseResponse>()+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.gridRenderer+ ?.items+ ?.mapNotNull { it.musicTwoRowItemRenderer }+ ?.mapNotNull(NewReleaseAlbumPage::fromMusicTwoRowItemRenderer)+ .orEmpty()+ }++ suspend fun moodAndGenres(): Result<List<MoodAndGenres>> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, browseId = "FEmusic_moods_and_genres").body<BrowseResponse>()+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents!!+ .mapNotNull(MoodAndGenres.Companion::fromSectionListRendererContent)+ }++ suspend fun browse(+ browseId: String,+ params: String?,+ ): Result<BrowseResult> =+ runCatching {+ // Use authentication for library endpoints+ val needsLogin = browseId.startsWith("FEmusic_library") || browseId == "VLSE" || browseId == "VLRDPN"+ val response = innerTube.browse(WEB_REMIX, browseId = browseId, params = params, setLogin = needsLogin).body<BrowseResponse>()+ val sectionContents =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ BrowseResult(+ title =+ response.header+ ?.musicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ items =+ sectionContents+ ?.mapNotNull { content ->+ when {+ content.gridRenderer != null -> {+ BrowseResult.Item(+ title =+ content.gridRenderer.header+ ?.gridHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ items =+ content.gridRenderer.items+ .mapNotNull(GridRenderer.Item::musicTwoRowItemRenderer)+ .mapNotNull { renderer ->+ // Try LibraryPage first (more lenient for library endpoints), fall back to RelatedPage+ LibraryPage.fromMusicTwoRowItemRenderer(renderer)+ ?: RelatedPage.fromMusicTwoRowItemRenderer(renderer)+ },+ )+ }++ content.musicCarouselShelfRenderer != null -> {+ val carouselItems = mutableListOf<YTItem>()+ for (carouselContent in content.musicCarouselShelfRenderer.contents) {+ val item = carouselContent.musicTwoRowItemRenderer?.let { renderer ->+ LibraryPage.fromMusicTwoRowItemRenderer(renderer)+ ?: RelatedPage.fromMusicTwoRowItemRenderer(renderer)+ } ?: carouselContent.musicMultiRowListItemRenderer?.let { renderer ->+ PodcastPage.fromMusicMultiRowListItemRenderer(renderer)+ } ?: carouselContent.musicResponsiveListItemRenderer?.let { renderer ->+ LibraryPage.fromMusicResponsiveListItemRenderer(renderer)+ ?: RelatedPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ if (item != null) {+ carouselItems.add(item)+ }+ }+ BrowseResult.Item(+ title =+ content.musicCarouselShelfRenderer.header+ ?.musicCarouselShelfBasicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ items =+ content.musicCarouselShelfRenderer.contents.mapNotNull { content ->+ content.musicTwoRowItemRenderer?.let { renderer ->+ LibraryPage.fromMusicTwoRowItemRenderer(renderer)+ ?: RelatedPage.fromMusicTwoRowItemRenderer(renderer)+ } ?: content.musicMultiRowListItemRenderer?.let { renderer ->+ PodcastPage.fromMusicMultiRowListItemRenderer(renderer)+ } ?: content.musicResponsiveListItemRenderer?.let { renderer ->+ LibraryPage.fromMusicResponsiveListItemRenderer(renderer)+ ?: RelatedPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ },+ )+ }++ content.musicShelfRenderer != null -> {+ BrowseResult.Item(+ title =+ content.musicShelfRenderer.title+ ?.runs+ ?.firstOrNull()+ ?.text,+ items =+ content.musicShelfRenderer.contents+ ?.mapNotNull(MusicShelfRenderer.Content::musicResponsiveListItemRenderer)+ ?.mapNotNull(LibraryPage.Companion::fromMusicResponsiveListItemRenderer)+ ?: emptyList(),+ )+ }++ content.musicPlaylistShelfRenderer != null -> {+ BrowseResult.Item(+ title = null, // MusicPlaylistShelfRenderer doesn't have a title+ items =+ content.musicPlaylistShelfRenderer.contents+ .getItems()+ .mapNotNull(LibraryPage.Companion::fromMusicResponsiveListItemRenderer),+ )+ }++ else -> {+ null+ }+ }+ }.orEmpty(),+ )+ }++ suspend fun library(+ browseId: String,+ tabIndex: Int = 0,+ ): Result<LibraryPage> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = browseId,+ setLogin = true,+ ).body<BrowseResponse>()++ val tab = response.contents?.singleColumnBrowseResultsRenderer?.tabs?.getOrNull(tabIndex)+ ?: response.contents?.twoColumnBrowseResultsRenderer?.tabs?.getOrNull(tabIndex)+ val contents = tab+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull {+ it.gridRenderer != null ||+ it.musicShelfRenderer != null ||+ it.musicPlaylistShelfRenderer != null ||+ it.itemSectionRenderer?.contents.orEmpty().any { child ->+ child.gridRenderer != null ||+ child.musicShelfRenderer != null ||+ child.musicPlaylistShelfRenderer != null+ }+ }+ val nestedContents = contents?.itemSectionRenderer?.contents.orEmpty()+ val gridRenderer = contents?.gridRenderer+ ?: nestedContents.firstNotNullOfOrNull { it.gridRenderer }+ val playlistShelfRenderer = contents?.musicPlaylistShelfRenderer+ ?: nestedContents.firstNotNullOfOrNull { it.musicPlaylistShelfRenderer }+ val musicShelfRenderer = contents?.musicShelfRenderer+ ?: nestedContents.firstNotNullOfOrNull { it.musicShelfRenderer }++ when {+ gridRenderer != null -> {+ val gridItems = gridRenderer.items+ val parsedItems =+ gridItems+ .mapNotNull(GridRenderer.Item::musicTwoRowItemRenderer)+ .mapNotNull { LibraryPage.fromMusicTwoRowItemRenderer(it) }+ LibraryPage(+ items = parsedItems,+ continuation = gridRenderer.continuations?.getContinuation(),+ )+ }++ playlistShelfRenderer != null -> {+ LibraryPage(+ items = playlistShelfRenderer.contents+ .getItems()+ .mapNotNull(LibraryPage.Companion::fromMusicResponsiveListItemRenderer),+ continuation = playlistShelfRenderer.continuations?.getContinuation(),+ )+ }++ musicShelfRenderer != null -> {+ val listItemRenderers = musicShelfRenderer.contents.orEmpty()+ .mapNotNull(MusicShelfRenderer.Content::musicResponsiveListItemRenderer)+ val parsedItems =+ listItemRenderers.mapNotNull { renderer ->+ LibraryPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ LibraryPage(+ items = parsedItems,+ continuation = musicShelfRenderer.continuations?.getContinuation(),+ )+ }++ else -> LibraryPage(items = emptyList(), continuation = null)+ }+ }++ suspend fun libraryContinuation(continuation: String) =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ continuation = continuation,+ setLogin = true,+ ).body<BrowseResponse>()++ val contents = response.continuationContents++ when {+ contents?.gridContinuation != null -> {+ LibraryContinuationPage(+ items =+ contents.gridContinuation.items+ .mapNotNull(GridRenderer.Item::musicTwoRowItemRenderer)+ .mapNotNull { LibraryPage.fromMusicTwoRowItemRenderer(it) },+ continuation = contents.gridContinuation.continuations?.getContinuation(),+ )+ }++ else -> { // contents?.musicShelfContinuation != null+ LibraryContinuationPage(+ items =+ contents+ ?.musicShelfContinuation+ ?.contents!!+ .mapNotNull(MusicShelfRenderer.Content::musicResponsiveListItemRenderer)+ .mapNotNull { LibraryPage.fromMusicResponsiveListItemRenderer(it) },+ continuation = contents.musicShelfContinuation.continuations?.getContinuation(),+ )+ }+ }+ }++ suspend fun libraryRecentActivity(): Result<LibraryPage> =+ runCatching {+ val continuation = LibraryFilter.FILTER_RECENT_ACTIVITY.value++ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ continuation = continuation,+ setLogin = true,+ ).body<BrowseResponse>()++ val gridItems =+ response.continuationContents+ ?.sectionListContinuation+ ?.contents+ ?.firstOrNull()+ ?.gridRenderer+ ?.items++ if (gridItems == null) {+ return@runCatching LibraryPage(+ items = emptyList(),+ continuation = null,+ )+ }++ val items =+ gridItems+ .mapNotNull {+ it.musicTwoRowItemRenderer?.let { renderer ->+ LibraryPage.fromMusicTwoRowItemRenderer(renderer)+ }+ }.toMutableList()++ /*+ * We need to fetch the artist page when accessing the library because it allows to have+ * a proper playEndpoint, which is needed to correctly report the playing indicator in+ * the home page.+ *+ * Despite this, we need to use the old thumbnail because it's the proper format for a+ * square picture, which is what we need.+ */+ items.forEachIndexed { index, item ->+ if (item is ArtistItem) {+ artist(item.id).getOrNull()?.artist?.let { fetchedArtist ->+ items[index] = fetchedArtist.copy(thumbnail = item.thumbnail)+ }+ }+ }++ LibraryPage(+ items = items,+ continuation = null,+ )+ }++ suspend fun getChartsPage(continuation: String? = null): Result<ChartsPage> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_charts",+ params = "ggMGCgQIgAQ%3D",+ continuation = continuation,+ ).body<BrowseResponse>()++ val sections = mutableListOf<ChartsPage.ChartSection>()++ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.forEach { content ->++ content.musicCarouselShelfRenderer?.let { renderer ->+ val title =+ renderer.header+ ?.musicCarouselShelfBasicHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return@forEach++ val items =+ renderer.contents+ .mapNotNull { item ->+ when {+ item.musicResponsiveListItemRenderer != null -> {+ convertToChartItem(item.musicResponsiveListItemRenderer)+ }++ item.musicTwoRowItemRenderer != null -> {+ convertMusicTwoRowItem(item.musicTwoRowItemRenderer)+ }++ else -> {+ null+ }+ }+ }.filterNotNull()++ if (items.isNotEmpty()) {+ sections.add(+ ChartsPage.ChartSection(+ title = title,+ items = items,+ chartType = determineChartType(title),+ ),+ )+ }+ }++ content.gridRenderer?.let { renderer ->+ val title =+ renderer.header+ ?.gridHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return@let++ val items =+ renderer.items+ .mapNotNull { item ->+ item.musicTwoRowItemRenderer?.let { renderer ->+ convertMusicTwoRowItem(renderer)+ }+ }.filterNotNull()++ if (items.isNotEmpty()) {+ sections.add(+ ChartsPage.ChartSection(+ title = title,+ items = items,+ chartType = ChartsPage.ChartType.NEW_RELEASES,+ ),+ )+ }+ }+ }++ ChartsPage(+ sections = sections,+ continuation =+ response.continuationContents+ ?.sectionListContinuation+ ?.continuations+ ?.getContinuation(),+ )+ }++ private fun determineChartType(title: String): ChartsPage.ChartType =+ when {+ title.contains("Trending", ignoreCase = true) -> ChartsPage.ChartType.TRENDING+ title.contains("Top", ignoreCase = true) -> ChartsPage.ChartType.TOP+ else -> ChartsPage.ChartType.GENRE+ }++ private fun convertToChartItem(renderer: MusicResponsiveListItemRenderer): YTItem? {+ return try {+ when {+ renderer.flexColumns.size >= 3 && renderer.videoId != null -> {+ val firstColumn =+ renderer.flexColumns+ .getOrNull(0)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text ?: return null++ val secondColumn =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text ?: return null++ val titleRun = firstColumn.runs?.firstOrNull() ?: return null+ val title = titleRun.text.takeIf { it.isNotBlank() } ?: return null++ val artists = PageHelper.extractArtists(secondColumn.runs)++ if (artists.isEmpty()) {+ Timber.w("convertMusicResponsiveListItemRenderer: Song '$title' (id=${renderer.videoId}) has EMPTY artists list")+ }++ val thirdColumn =+ renderer.flexColumns+ .getOrNull(2)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text++ SongItem(+ id = renderer.videoId!!,+ title = title,+ artists = artists,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ musicVideoType = renderer.musicVideoType,+ explicit =+ renderer.badges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true,+ chartPosition =+ thirdColumn+ ?.runs+ ?.firstOrNull()+ ?.text+ ?.toIntOrNull(),+ chartChange = thirdColumn?.runs?.getOrNull(1)?.text,+ )+ }++ else -> {+ null+ }+ }+ } catch (e: Exception) {+ println("Error converting chart item: ${e.message}\n${Json.encodeToString(renderer)}")+ null+ }+ }++ private fun convertMusicTwoRowItem(renderer: MusicTwoRowItemRenderer): YTItem? {+ return try {+ when {+ renderer.isSong -> {+ val subtitle = renderer.subtitle?.runs ?: return null+ val title = renderer.title.runs?.firstOrNull()?.text ?: return null+ val artists = PageHelper.extractArtists(subtitle)+ val videoId = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null++ if (artists.isEmpty()) {+ Timber.w("convertMusicTwoRowItem: Song '$title' (id=$videoId) has EMPTY artists list from ${subtitle.size} subtitle runs")+ }++ SongItem(+ id = videoId,+ title = title,+ artists = artists,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ musicVideoType = renderer.musicVideoType,+ explicit =+ renderer.subtitleBadges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true,+ )+ }++ renderer.isAlbum -> {+ AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ renderer.subtitle?.runs?.oddElements()?.drop(1)?.mapNotNull {+ it.navigationEndpoint?.browseEndpoint?.browseId?.let { id ->+ Artist(name = it.text, id = id)+ }+ },+ year =+ renderer.subtitle+ ?.runs+ ?.lastOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit =+ renderer.subtitleBadges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true,+ )+ }++ else -> {+ null+ }+ }+ } catch (e: Exception) {+ println("Error converting two row item: ${e.message}\n${Json.encodeToString(renderer)}")+ null+ }+ }++ suspend fun musicHistory() =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_history",+ setLogin = true,+ ).body<BrowseResponse>()++ HistoryPage(+ sections =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.mapNotNull {+ it.musicShelfRenderer?.let { musicShelfRenderer ->+ HistoryPage.fromMusicShelfRenderer(musicShelfRenderer)+ }+ },+ )+ }++ /**+ * Fetch podcast discovery/recommendations page.+ * Returns sections like "Popular shows", "Popular episodes", category sections.+ */+ suspend fun podcastDiscover(): Result<HomePage> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_non_music_audio",+ setLogin = true,+ ).body<BrowseResponse>()++ val sectionListRenderer =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ val carousels = sectionListRenderer?.contents?.mapNotNull { it.musicCarouselShelfRenderer } ?: emptyList()+ val sections =+ carousels.mapNotNull {+ HomePage.Section.fromMusicCarouselShelfRenderer(it)+ }+ val chips =+ sectionListRenderer?.header?.chipCloudRenderer?.chips?.mapNotNull {+ HomePage.Chip.fromChipCloudChipRenderer(it)+ }+ val continuation = sectionListRenderer?.continuations?.getContinuation()++ HomePage(chips, sections, continuation)+ }++ suspend fun likeVideo(+ videoId: String,+ like: Boolean,+ ) = runCatching {+ if (like) {+ innerTube.likeVideo(WEB_REMIX, videoId)+ } else {+ innerTube.unlikeVideo(WEB_REMIX, videoId)+ }+ }++ suspend fun likePlaylist(+ playlistId: String,+ like: Boolean,+ ) = runCatching {+ if (like) {+ innerTube.likePlaylist(WEB_REMIX, playlistId)+ } else {+ innerTube.unlikePlaylist(WEB_REMIX, playlistId)+ }+ }++ suspend fun subscribeChannel(+ channelId: String,+ subscribe: Boolean,+ params: String? = null,+ ) = runCatching {+ // Default params from YouTube Music API - required for subscription to work+ val subscribeParams = params ?: "EgIIAhgA"+ if (subscribe) {+ innerTube.subscribeChannel(WEB_REMIX, channelId, subscribeParams)+ } else {+ innerTube.unsubscribeChannel(WEB_REMIX, channelId, subscribeParams)+ }+ }++ /**+ * Save a podcast show to library.+ * Uses likePlaylist API. Podcast IDs are "MPSP<playlistId>".+ */+ suspend fun savePodcast(+ podcastId: String,+ save: Boolean,+ ) = runCatching {+ val playlistId = podcastId.removePrefix("MPSP")+ Timber.d("[PODCAST_API] savePodcast: podcastId=$podcastId, playlistId=$playlistId, save=$save")+ if (save) {+ innerTube.likePlaylist(WEB_REMIX, playlistId)+ } else {+ innerTube.unlikePlaylist(WEB_REMIX, playlistId)+ }+ }++ /**+ * Add episode to "Episodes for Later" playlist (SE).+ */+ suspend fun addEpisodeToSavedEpisodes(videoId: String) =+ runCatching {+ innerTube.addToPlaylist(WEB_REMIX, "SE", videoId)+ }++ /**+ * Remove episode from "Episodes for Later" playlist (SE).+ * Note: setVideoId is required for removal and must be obtained from the playlist response.+ */+ suspend fun removeEpisodeFromSavedEpisodes(+ videoId: String,+ setVideoId: String,+ ) = runCatching {+ innerTube.removeFromPlaylist(WEB_REMIX, "SE", videoId, setVideoId)+ }++ suspend fun libraryPodcastChannels(): Result<LibraryPage> {+ Timber.d("[PODCAST_API] libraryPodcastChannels: calling browse with FEmusic_library_non_music_audio_channels_list")+ return runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_library_non_music_audio_channels_list",+ setLogin = true,+ ).body<BrowseResponse>()++ val contentList =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents ?: emptyList()++ val items =+ contentList.flatMap { content ->+ when {+ content.gridRenderer != null -> {+ content.gridRenderer.items+ .mapNotNull(GridRenderer.Item::musicTwoRowItemRenderer)+ .mapNotNull { LibraryPage.fromMusicTwoRowItemRenderer(it) }+ }++ content.musicShelfRenderer != null -> {+ content.musicShelfRenderer.contents+ ?.mapNotNull(MusicShelfRenderer.Content::musicResponsiveListItemRenderer)+ ?.mapNotNull { LibraryPage.fromMusicResponsiveListItemRenderer(it) }+ ?: emptyList()+ }++ content.musicCarouselShelfRenderer != null -> {+ content.musicCarouselShelfRenderer.contents.mapNotNull { content ->+ content.musicTwoRowItemRenderer?.let { renderer ->+ LibraryPage.fromMusicTwoRowItemRenderer(renderer)+ } ?: content.musicMultiRowListItemRenderer?.let { renderer ->+ PodcastPage.fromMusicMultiRowListItemRenderer(renderer)+ } ?: content.musicResponsiveListItemRenderer?.let { renderer ->+ LibraryPage.fromMusicResponsiveListItemRenderer(renderer)+ }+ }+ }++ else -> {+ emptyList()+ }+ }+ }++ LibraryPage(+ items = items,+ continuation = null,+ )+ }.also { result ->+ result.onFailure { e -> Timber.e(e, "[PODCAST_API] libraryPodcastChannels FAILED") }+ result.onSuccess { Timber.d("[PODCAST_API] libraryPodcastChannels SUCCESS: ${it.items.size} items") }+ }+ }++ suspend fun libraryPodcastEpisodes(): Result<LibraryPage> {+ Timber.d("[PODCAST_API] libraryPodcastEpisodes: calling browse with FEmusic_library_non_music_audio_list")+ return runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_library_non_music_audio_list",+ setLogin = true,+ ).body<BrowseResponse>()++ val contents =+ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()++ val items =+ when {+ contents?.gridRenderer != null -> {+ contents.gridRenderer.items+ .mapNotNull(GridRenderer.Item::musicTwoRowItemRenderer)+ .mapNotNull { LibraryPage.fromMusicTwoRowItemRenderer(it) }+ }++ contents?.musicShelfRenderer != null -> {+ contents.musicShelfRenderer.contents+ ?.mapNotNull(MusicShelfRenderer.Content::musicResponsiveListItemRenderer)+ ?.mapNotNull { LibraryPage.fromMusicResponsiveListItemRenderer(it) }+ ?: emptyList()+ }++ else -> {+ emptyList()+ }+ }++ LibraryPage(+ items = items,+ continuation = null,+ )+ }.also { result ->+ result.onFailure { e -> Timber.e(e, "[PODCAST_API] libraryPodcastEpisodes FAILED") }+ result.onSuccess { Timber.d("[PODCAST_API] libraryPodcastEpisodes SUCCESS: ${it.items.size} items") }+ }+ }++ /**+ * Fetch saved podcast shows from library.+ * Uses FEmusic_library_non_music_audio_list and filters to only PodcastItem.+ */+ suspend fun savedPodcastShows(): Result<List<PodcastItem>> =+ runCatching {+ val libraryPage = libraryPodcastEpisodes().getOrThrow()+ libraryPage.items.filterIsInstance<PodcastItem>()+ }++ /**+ * Fetch "New Episodes" auto-playlist (VLRDPN).+ * Returns new episodes from saved/subscribed podcasts.+ */+ suspend fun newEpisodes(): Result<List<SongItem>> {+ Timber.d("[PODCAST_API] newEpisodes: calling browse with VLRDPN")+ return runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "VLRDPN",+ setLogin = true,+ ).body<BrowseResponse>()++ val twoColumn = response.contents?.twoColumnBrowseResultsRenderer++ // RDPN may have content in either tabs (first tab) or secondaryContents+ val sections = mutableListOf<SectionListRenderer.Content>()++ // Check tabs path+ twoColumn?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.let { sections.addAll(it) }++ // Check secondaryContents path (original working path for RDPN)+ // Use TwoColumnBrowseResultsRenderer's inner SectionListRenderer types+ twoColumn?.secondaryContents?.sectionListRenderer?.contents?.let { secContents ->+ sections.addAll(secContents.map { secContent ->+ SectionListRenderer.Content(+ musicCarouselShelfRenderer = null,+ musicShelfRenderer = secContent.musicShelfRenderer,+ musicCardShelfRenderer = null,+ musicPlaylistShelfRenderer = secContent.musicPlaylistShelfRenderer,+ musicDescriptionShelfRenderer = null,+ musicResponsiveHeaderRenderer = null,+ musicEditablePlaylistDetailHeaderRenderer = null,+ gridRenderer = null,+ itemSectionRenderer = null,+ )+ })+ }++ Timber.d("[PODCAST_API] newEpisodes: ${sections.size} section(s) found (${twoColumn?.tabs?.size ?: 0} tab(s), secondary has ${twoColumn?.secondaryContents?.sectionListRenderer?.contents?.size ?: 0})")++ // Log all section types+ sections.forEachIndexed { idx, section ->+ Timber.d("[PODCAST_API] section[$idx]: hasCarousel=${section.musicCarouselShelfRenderer != null} hasShelf=${section.musicShelfRenderer != null} hasPlaylistShelf=${section.musicPlaylistShelfRenderer != null} hasCardShelf=${section.musicCardShelfRenderer != null} hasGrid=${section.gridRenderer != null} hasItemSection=${section.itemSectionRenderer != null}")+ section.musicCarouselShelfRenderer?.let { carousel ->+ val carouselTitle = carousel.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.joinToString("") { it.text }+ Timber.d("[PODCAST_API] carousel title=$carouselTitle, items=${carousel.contents?.size}")+ }+ section.musicShelfRenderer?.let { shelf ->+ Timber.d("[PODCAST_API] shelf title=${shelf.title?.runs?.joinToString("") { it.text }}, items=${shelf.contents?.size}")+ // Log first item's subtitle fields+ shelf.contents?.firstOrNull()?.musicMultiRowListItemRenderer?.let { r ->+ val subtitleText = r.subtitle?.runs?.joinToString("") { it.text }+ val secondSubtitleText = r.secondSubtitle?.runs?.joinToString("") { it.text }+ val secondarySubtitleText = r.secondarySubtitle?.runs?.joinToString("") { it.text }+ Timber.d("[PODCAST_API] first item: subtitle='$subtitleText' secondSubtitle='$secondSubtitleText' secondarySubtitle='$secondarySubtitleText'")+ val subRuns = r.subtitle?.runs+ Timber.d("[PODCAST_API] subtitle runs: ${subRuns?.map { "text='${it.text}' nav=${it.navigationEndpoint?.browseEndpoint?.browseId}" }}")+ val secRuns = r.secondSubtitle?.runs+ Timber.d("[PODCAST_API] secondSubtitle runs: ${secRuns?.map { "text='${it.text}' nav=${it.navigationEndpoint?.browseEndpoint?.browseId}" }}")+ val menuItems = r.menu?.menuRenderer?.items?.mapIndexed { idx, item ->+ val navText = item.menuNavigationItemRenderer?.text?.runs?.joinToString("") { it.text }+ val navId = item.menuNavigationItemRenderer?.navigationEndpoint?.browseEndpoint?.browseId+ val navPageType = item.menuNavigationItemRenderer?.navigationEndpoint?.browseEndpoint+ ?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType+ val svcText = item.menuServiceItemRenderer?.text?.runs?.joinToString("") { it.text }+ val toggleIcon = item.toggleMenuServiceItemRenderer?.defaultIcon?.iconType+ "[$idx](navText='$navText' navId=$navId pageType=$navPageType svcText='$svcText' toggleIcon=$toggleIcon)"+ }+ Timber.d("[PODCAST_API] first item detailed menu: $menuItems")+ }+ }+ section.musicPlaylistShelfRenderer?.let { ps ->+ Timber.d("[PODCAST_API] playlistShelf playlistId=${ps.playlistId}, items=${ps.contents?.size}")+ }+ }++ // Check singleColumnBrowseResultsRenderer too+ val singleColumn = response.contents?.singleColumnBrowseResultsRenderer+ Timber.d("[PODCAST_API] singleColumn is null=${singleColumn == null}")+ if (singleColumn?.tabs != null) {+ singleColumn.tabs.forEachIndexed { idx, tab ->+ val tabTitle = tab.tabRenderer.title+ val tabContent = tab.tabRenderer.content+ val tabSectionList = tabContent?.sectionListRenderer+ val tabSectionsSize = tabSectionList?.contents?.size ?: 0+ Timber.d("[PODCAST_API] singleColumn tab[$idx]: title=$tabTitle, sections=$tabSectionsSize")+ tabSectionList?.contents?.forEachIndexed { sIdx, section ->+ val shelf = section.musicShelfRenderer+ val carousel = section.musicCarouselShelfRenderer+ if (shelf != null) {+ Timber.d("[PODCAST_API] singleCol section[$sIdx] shelf title=${shelf.title?.runs?.joinToString("") { it.text }}, items=${shelf.contents?.size}")+ }+ if (carousel != null) {+ val carTitle = carousel.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.joinToString("") { it.text }+ Timber.d("[PODCAST_API] singleCol section[$sIdx] carousel title=$carTitle, items=${carousel.contents?.size}")+ }+ }+ }+ }++ // Extract episodes from all section types+ val episodesList = mutableListOf<SongItem>()++ // Helper to process musicShelf+ fun processShelf(shelf: MusicShelfRenderer, sectionPodcastName: String? = null) {+ val podcastName = sectionPodcastName ?: shelf.title?.runs?.joinToString("") { it.text }+ shelf.contents+ ?.mapNotNull { it.musicMultiRowListItemRenderer }+ ?.forEach { renderer ->+ if (renderer.onTap?.watchEndpoint?.videoId == null) return@forEach+ val title = renderer.title?.runs?.firstOrNull()?.text ?: return@forEach++ val subtitleGroups = renderer.subtitle?.runs?.splitBySeparator()+ val duration = subtitleGroups+ ?.lastOrNull { group ->+ group.firstOrNull()?.text?.parseTime() != null+ }+ ?.firstOrNull()+ ?.text+ ?.parseTime()++ // Strategy 1: secondSubtitle / secondarySubtitle often has the podcast name+ var artistName: String? = renderer.secondSubtitle?.runs?.joinToString("") { it.text }+ if (artistName.isNullOrBlank()) {+ artistName = renderer.secondarySubtitle?.runs?.joinToString("") { it.text }+ }++ // Strategy 2: Extract browseId from menu items with browse endpoints+ var browseId: String? = null+ val actionLabels = setOf("Save to playlist", "Share", "Remove from library",+ "Add to library", "Don't recommend this episode", "Start radio",+ "Go to podcast", "Go to artist", "Go to album")+ renderer.menu?.menuRenderer?.items?.forEach { item ->+ val text = item.menuNavigationItemRenderer?.text?.runs?.joinToString("") { it.text }+ val navEp = item.menuNavigationItemRenderer?.navigationEndpoint?.browseEndpoint+ if (navEp != null) {+ if (browseId == null) browseId = navEp.browseId+ if (text != null && text !in actionLabels && artistName == null) {+ artistName = text+ }+ }+ }++ // Strategy 3: Fallback to section header's podcast name+ if (artistName.isNullOrBlank()) artistName = podcastName++ val artists = if (!artistName.isNullOrBlank()) {+ listOf(Artist(name = artistName, id = browseId))+ } else emptyList()++ episodesList.add(+ SongItem(+ id = renderer.onTap.watchEndpoint.videoId,+ title = title,+ artists = artists,+ album = null,+ duration = duration,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: "",+ isEpisode = true,+ )+ )+ }+ }++ // Process both sections and carousels+ sections.forEach { section ->+ // Process musicShelfRenderer+ section.musicShelfRenderer?.let { shelf ->+ processShelf(shelf)+ }+ // Process musicCarouselShelfRenderer - each carousel is a podcast group+ section.musicCarouselShelfRenderer?.let { carousel ->+ val carouselTitle = carousel.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.joinToString("") { it.text }+ carousel.contents?.forEach { carouselContent ->+ carouselContent.musicMultiRowListItemRenderer?.let { renderer ->+ if (renderer.onTap?.watchEndpoint?.videoId == null) return@let+ val title = renderer.title?.runs?.firstOrNull()?.text ?: return@let++ val subtitleGroups = renderer.subtitle?.runs?.splitBySeparator()+ val duration = subtitleGroups+ ?.lastOrNull { group ->+ group.firstOrNull()?.text?.parseTime() != null+ }+ ?.firstOrNull()+ ?.text+ ?.parseTime()++ // Try secondSubtitle first, then carousel title+ var artistName: String? = renderer.secondSubtitle?.runs?.joinToString("") { it.text }+ if (artistName.isNullOrBlank()) {+ artistName = renderer.secondarySubtitle?.runs?.joinToString("") { it.text }+ }+ if (artistName.isNullOrBlank()) artistName = carouselTitle++ val artists = if (!artistName.isNullOrBlank()) {+ listOf(Artist(name = artistName, id = null))+ } else emptyList()++ episodesList.add(+ SongItem(+ id = renderer.onTap.watchEndpoint.videoId,+ title = title,+ artists = artists,+ album = null,+ duration = duration,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: "",+ isEpisode = true,+ )+ )+ }+ }+ }+ }++ // Enrich items that have no artist name by calling getMediaInfo (next endpoint)+ val itemsToEnrich = episodesList.filter { it.artists.isEmpty() }+ if (itemsToEnrich.isNotEmpty()) {+ Timber.d("[PODCAST_API] Enriching ${itemsToEnrich.size} items via getMediaInfo")+ coroutineScope {+ itemsToEnrich+ .map { episode ->+ async {+ val mediaInfo = innerTube.getMediaInfo(episode.id).getOrNull()+ if (mediaInfo?.author != null) {+ episode.copy(+ artists = listOf(Artist(name = mediaInfo.author, id = mediaInfo.authorId)),+ )+ } else episode+ }+ }+ .awaitAll()+ .forEach { enriched ->+ val idx = episodesList.indexOfFirst { it.id == enriched.id }+ if (idx >= 0) episodesList[idx] = enriched+ }+ }+ }++ Timber.d("[PODCAST_API] newEpisodes SUCCESS: ${episodesList.size} items")+ episodesList+ }.also { result ->+ result.onFailure { e -> Timber.e(e, "[PODCAST_API] newEpisodes FAILED") }+ }+ }++ /**+ * Fetch the RDPN "New Episodes" playlist info (title + thumbnail).+ * Uses the same VLRDPN browse call as [newEpisodes] but parses the header instead.+ * Falls back to the first episode thumbnail if no header thumbnail is found.+ */+ suspend fun newEpisodesPlaylistInfo(): Result<PlaylistItem> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "VLRDPN",+ setLogin = true,+ ).body<BrowseResponse>()++ // Try all known header renderers in priority order+ val thumbnail: String? =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ ?: response.header+ ?.musicVisualHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ ?: response.header+ ?.musicDetailHeaderRenderer+ ?.thumbnail+ ?.croppedSquareThumbnailRenderer+ ?.thumbnail+ ?.thumbnails+ ?.lastOrNull()+ ?.url+ // Fall back: thumbnail of the first episode in the list+ ?: response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicShelfRenderer+ ?.contents+ ?.firstOrNull()+ ?.musicMultiRowListItemRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()++ val title =+ response.header+ ?.musicImmersiveHeaderRenderer+ ?.title+ ?.runs+ ?.joinToString("") { it.text }+ ?: response.header+ ?.musicVisualHeaderRenderer+ ?.title+ ?.runs+ ?.joinToString("") { it.text }+ ?: "New Episodes"++ PlaylistItem(+ id = "RDPN",+ title = title,+ author = null,+ songCountText = null,+ thumbnail = thumbnail,+ playEndpoint = null,+ shuffleEndpoint = null,+ radioEndpoint = null,+ )+ }++ /**+ * Fetch "Episodes for Later" playlist (VLSE).+ * Returns manually saved episodes.+ */+ suspend fun episodesForLater(): Result<List<SongItem>> =+ runCatching {+ Timber.d("[PODCAST_API] episodesForLater: calling browse with VLSE")+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "VLSE",+ setLogin = true,+ ).body<BrowseResponse>()++ // VLSE uses musicPlaylistShelfRenderer, not musicShelfRenderer+ val contents =+ response.contents+ ?.twoColumnBrowseResultsRenderer+ ?.secondaryContents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull()++ val shelfContents =+ contents?.musicPlaylistShelfRenderer?.contents+ ?: contents?.musicShelfRenderer?.contents++ // Parse musicResponsiveListItemRenderer (standard playlist format)+ shelfContents+ ?.mapNotNull { it.musicResponsiveListItemRenderer }+ ?.mapNotNull { renderer ->+ val videoId = renderer.videoId ?: return@mapNotNull null+ val setVideoId = renderer.playlistSetVideoId+ val title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return@mapNotNull null++ // Subtitle is typically "Channel • Date" or "Channel • Date • Duration"+ val subtitleGroups = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()++ // Channel is the first group with a navigationEndpoint, or just the first group+ val artistRun = subtitleGroups+ ?.firstOrNull { group ->+ group.firstOrNull()?.navigationEndpoint?.browseEndpoint != null+ }+ ?.firstOrNull()+ ?: subtitleGroups?.firstOrNull()?.firstOrNull()++ val duration = subtitleGroups+ ?.drop(1)+ ?.firstOrNull { group ->+ group.firstOrNull()?.text?.parseTime() != null+ }+ ?.firstOrNull()+ ?.text+ ?.parseTime()+ // Fallback to fixedColumns for duration+ ?: renderer.fixedColumns?.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()+ ?.text?.parseTime()++ SongItem(+ id = videoId,+ title = title,+ artists =+ artistRun?.let { listOf(Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId)) }+ ?: emptyList(),+ album = null,+ duration = duration,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: "",+ setVideoId = setVideoId,+ isEpisode = true,+ )+ } ?: emptyList()+ }++ /**+ * Fetch "Continue Listening" / Resume Playback.+ * Returns partially played episodes for resumption.+ */+ suspend fun continueListening(): Result<List<SongItem>> =+ runCatching {+ val response =+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_listening_review",+ setLogin = true,+ ).body<BrowseResponse>()++ response.contents+ ?.singleColumnBrowseResultsRenderer+ ?.tabs+ ?.firstOrNull()+ ?.tabRenderer+ ?.content+ ?.sectionListRenderer+ ?.contents+ ?.flatMap { section ->+ section.musicShelfRenderer?.contents?.mapNotNull { content ->+ content.musicResponsiveListItemRenderer?.let { renderer ->+ val videoId = renderer.videoId ?: return@mapNotNull null+ val title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return@mapNotNull null+ val artistRun =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ SongItem(+ id = videoId,+ title = title,+ artists =+ artistRun?.let { listOf(Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId)) }+ ?: emptyList(),+ album = null,+ duration = null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: "",+ isEpisode = true,+ )+ }+ } ?: emptyList()+ } ?: emptyList()+ }++ suspend fun getChannelId(browseId: String): String {+ artist(browseId).onSuccess {+ return it.artist.channelId ?: ""+ }+ return ""+ }++ suspend fun addToPlaylist(+ playlistId: String,+ videoId: String,+ ) = runCatching {+ innerTube.addToPlaylist(WEB_REMIX, playlistId, videoId)+ }++ suspend fun addPlaylistToPlaylist(+ playlistId: String,+ addPlaylistId: String,+ ) = runCatching {+ innerTube.addPlaylistToPlaylist(WEB_REMIX, playlistId, addPlaylistId)+ }++ suspend fun removeFromPlaylist(+ playlistId: String,+ videoId: String,+ setVideoId: String,+ ) = runCatching {+ innerTube.removeFromPlaylist(WEB_REMIX, playlistId, videoId, setVideoId)+ }++ suspend fun moveSongPlaylist(+ playlistId: String,+ setVideoId: String,+ successorSetVideoId: String?,+ ) = runCatching {+ innerTube.moveSongPlaylist(WEB_REMIX, playlistId, setVideoId, successorSetVideoId)+ }++ fun createPlaylist(title: String) =+ runBlocking {+ innerTube.createPlaylist(WEB_REMIX, title).body<CreatePlaylistResponse>().playlistId+ }++ suspend fun renamePlaylist(+ playlistId: String,+ name: String,+ ) = runCatching {+ innerTube.renamePlaylist(WEB_REMIX, playlistId, name)+ }++ suspend fun uploadCustomThumbnailLink(+ playlistId: String,+ image: ByteArray,+ ) = runCatching {+ val uploadUrl = innerTube.getUploadCustomThumbnailLink(WEB_REMIX, image.size).headers["x-guploader-uploadid"]+ val blobReq =+ innerTube.uploadCustomThumbnail(+ WEB_REMIX,+ uploadUrl!!,+ image,+ )+ val blobId = Json.decodeFromString<ImageUploadResponse>(blobReq.bodyAsText()).encryptedBlobId+ innerTube+ .setThumbnailPlaylist(+ WEB_REMIX,+ playlistId,+ blobId,+ ).body<EditPlaylistResponse>()+ .newHeader+ ?.musicEditablePlaylistDetailHeaderRenderer+ ?.header+ ?.musicResponsiveHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ }++ suspend fun removeThumbnailPlaylist(playlistId: String) =+ runCatching {+ innerTube+ .removeThumbnailPlaylist(+ WEB_REMIX,+ playlistId,+ ).body<EditPlaylistResponse>()+ .newHeader+ ?.musicEditablePlaylistDetailHeaderRenderer+ ?.header+ ?.musicResponsiveHeaderRenderer+ ?.thumbnail+ ?.musicThumbnailRenderer+ ?.getThumbnailUrl()+ }++ suspend fun deletePlaylist(playlistId: String) =+ runCatching {+ innerTube.deletePlaylist(WEB_REMIX, playlistId)+ }++ suspend fun player(+ videoId: String,+ playlistId: String? = null,+ client: YouTubeClient,+ signatureTimestamp: Int? = null,+ poToken: String? = null,+ ): Result<PlayerResponse> =+ runCatching {+ innerTube.player(client, videoId, playlistId, signatureTimestamp, poToken).body<PlayerResponse>()+ }++ suspend fun registerPlayback(+ playlistId: String? = null,+ playbackTracking: String,+ ) = runCatching {+ val cpn =+ (1..16)+ .map {+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"[+ Random.Default.nextInt(+ 0,+ 64,+ ),+ ]+ }.joinToString("")++ innerTube.registerPlayback(+ url = playbackTracking,+ playlistId = playlistId,+ cpn = cpn,+ )+ }++ suspend fun next(+ endpoint: WatchEndpoint,+ continuation: String? = null,+ ): Result<NextResult> =+ runCatching {+ val response =+ innerTube+ .next(+ WEB_REMIX,+ endpoint.videoId,+ endpoint.playlistId,+ endpoint.playlistSetVideoId,+ endpoint.index,+ endpoint.params,+ continuation,+ ).body<NextResponse>()+ val playlistPanelRenderer =+ response.continuationContents?.playlistPanelContinuation+ ?: response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.get(0)+ ?.tabRenderer+ ?.content+ ?.musicQueueRenderer+ ?.content+ ?.playlistPanelRenderer!!+ val title =+ response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.get(0)+ ?.tabRenderer+ ?.content+ ?.musicQueueRenderer+ ?.header+ ?.musicQueueHeaderRenderer+ ?.subtitle+ ?.runs+ ?.firstOrNull()+ ?.text+ val items =+ playlistPanelRenderer.contents.mapNotNull { content ->+ content.playlistPanelVideoRenderer+ ?.let(NextPage::fromPlaylistPanelVideoRenderer)+ ?.let { it to content.playlistPanelVideoRenderer.selected }+ }+ val songs = items.map { it.first }+ val currentIndex = items.indexOfFirst { it.second }.takeIf { it != -1 }++ // load automix items+ playlistPanelRenderer.contents+ .lastOrNull()+ ?.automixPreviewVideoRenderer+ ?.content+ ?.automixPlaylistVideoRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint+ ?.let { watchPlaylistEndpoint ->+ return@runCatching next(watchPlaylistEndpoint).getOrThrow().let { result ->+ result.copy(+ title = title,+ items = songs + result.items,+ lyricsEndpoint =+ response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.getOrNull(+ 1,+ )?.tabRenderer+ ?.endpoint+ ?.browseEndpoint,+ relatedEndpoint =+ response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.getOrNull(+ 2,+ )?.tabRenderer+ ?.endpoint+ ?.browseEndpoint,+ currentIndex = currentIndex,+ endpoint = watchPlaylistEndpoint,+ )+ }+ }+ NextResult(+ title = title,+ items = songs,+ currentIndex = currentIndex,+ lyricsEndpoint =+ response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.getOrNull(+ 1,+ )?.tabRenderer+ ?.endpoint+ ?.browseEndpoint,+ relatedEndpoint =+ response.contents.singleColumnMusicWatchNextResultsRenderer+ ?.tabbedRenderer+ ?.watchNextTabbedResultsRenderer+ ?.tabs+ ?.getOrNull(+ 2,+ )?.tabRenderer+ ?.endpoint+ ?.browseEndpoint,+ continuation = playlistPanelRenderer.continuations?.getContinuation(),+ endpoint = endpoint,+ )+ }++ suspend fun lyrics(endpoint: BrowseEndpoint): Result<String?> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, endpoint.browseId, endpoint.params).body<BrowseResponse>()+ response.contents+ ?.sectionListRenderer+ ?.contents+ ?.firstOrNull { it.musicDescriptionShelfRenderer != null }+ ?.musicDescriptionShelfRenderer+ ?.description+ ?.runs+ ?.joinToString(separator = "") { it.text }+ }++ suspend fun related(endpoint: BrowseEndpoint): Result<RelatedPage> =+ runCatching {+ val response = innerTube.browse(WEB_REMIX, endpoint.browseId).body<BrowseResponse>()+ val songs = mutableListOf<SongItem>()+ val albums = mutableListOf<AlbumItem>()+ val artists = mutableListOf<ArtistItem>()+ val playlists = mutableListOf<PlaylistItem>()+ response.contents?.sectionListRenderer?.contents?.forEach { sectionContent ->+ sectionContent.musicCarouselShelfRenderer?.contents?.forEach { content ->+ when (+ val item =+ content.musicResponsiveListItemRenderer?.let(RelatedPage.Companion::fromMusicResponsiveListItemRenderer)+ ?: content.musicTwoRowItemRenderer?.let(RelatedPage.Companion::fromMusicTwoRowItemRenderer)+ ) {+ is SongItem -> {+ if (content.musicResponsiveListItemRenderer+ ?.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchEndpoint+ ?.watchEndpointMusicSupportedConfigs+ ?.watchEndpointMusicConfig+ ?.musicVideoType == MUSIC_VIDEO_TYPE_ATV+ ) {+ songs.add(item)+ }+ }++ is AlbumItem -> {+ albums.add(item)+ }++ is ArtistItem -> {+ artists.add(item)+ }++ is PlaylistItem -> {+ playlists.add(item)+ }++ is PodcastItem, is EpisodeItem -> {}++ null -> {}+ }+ }+ }+ RelatedPage(songs, albums, artists, playlists)+ }++ suspend fun queue(+ videoIds: List<String>? = null,+ playlistId: String? = null,+ ): Result<List<SongItem>> =+ runCatching {+ if (videoIds != null) {+ assert(videoIds.size <= MAX_GET_QUEUE_SIZE) // Max video limit+ }+ innerTube+ .getQueue(WEB_REMIX, videoIds, playlistId)+ .body<GetQueueResponse>()+ .queueDatas+ .mapNotNull {+ it.content.playlistPanelVideoRenderer?.let { renderer ->+ NextPage.fromPlaylistPanelVideoRenderer(renderer)+ }+ }+ }++ suspend fun transcript(videoId: String): Result<String> =+ runCatching {+ val response = innerTube.getTranscript(WEB, videoId).body<GetTranscriptResponse>()+ response.actions+ ?.firstOrNull()+ ?.updateEngagementPanelAction+ ?.content+ ?.transcriptRenderer+ ?.body+ ?.transcriptBodyRenderer+ ?.cueGroups+ ?.joinToString(+ separator = "\n",+ ) { group ->+ val time =+ group.transcriptCueGroupRenderer.cues[0]+ .transcriptCueRenderer.startOffsetMs+ val text =+ group.transcriptCueGroupRenderer.cues[0]+ .transcriptCueRenderer.cue.simpleText+ .trim('♪')+ .trim(' ')+ "[%02d:%02d.%03d]$text".format(time / 60000, (time / 1000) % 60, time % 1000)+ }!!+ }++ suspend fun visitorData(): Result<String> =+ runCatching {+ Json+ .parseToJsonElement(innerTube.getSwJsData().bodyAsText().substring(5))+ .jsonArray[0]+ .jsonArray[2]+ .jsonArray+ .first {+ (it as? JsonPrimitive)?.contentOrNull?.let { candidate ->+ VISITOR_DATA_REGEX.containsMatchIn(candidate)+ } ?: false+ }.jsonPrimitive.content+ }++ suspend fun accountInfo(): Result<AccountInfo> =+ runCatching {+ innerTube+ .accountMenu(WEB_REMIX)+ .body<AccountMenuResponse>()+ .actions[0]+ .openPopupAction.popup.multiPageMenuRenderer+ .header+ ?.activeAccountHeaderRenderer+ ?.toAccountInfo()!!+ }++ suspend fun feedback(tokens: List<String>): Result<Boolean> =+ runCatching {+ innerTube+ .feedback(WEB_REMIX, tokens)+ .body<FeedbackResponse>()+ .feedbackResponses+ .all { it.isProcessed }+ }++ /**+ * Add a song to library by fetching fresh feedback tokens from the next endpoint+ * This is more reliable than using cached tokens which might be stale+ */+ suspend fun addSongToLibrary(videoId: String): Result<Boolean> =+ runCatching {+ // Get fresh song data with menu tokens using next endpoint+ val nextResult = next(WatchEndpoint(videoId = videoId)).getOrThrow()+ val song =+ nextResult.items.find { it.id == videoId }+ ?: throw Exception("Song not found in next response")++ val addToken =+ song.libraryAddToken+ ?: throw Exception("Add to library token not available")++ feedback(listOf(addToken)).getOrThrow()+ }++ /**+ * Remove a song from library by fetching fresh feedback tokens from the next endpoint+ */+ suspend fun removeSongFromLibrary(videoId: String): Result<Boolean> =+ runCatching {+ // Get fresh song data with menu tokens using next endpoint+ val nextResult = next(WatchEndpoint(videoId = videoId)).getOrThrow()+ val song =+ nextResult.items.find { it.id == videoId }+ ?: throw Exception("Song not found in next response")++ val removeToken =+ song.libraryRemoveToken+ ?: throw Exception("Remove from library token not available")++ feedback(listOf(removeToken)).getOrThrow()+ }++ /**+ * Toggle song library status - adds if not in library, removes if in library+ * Uses fresh tokens fetched from the API for reliability+ */+ suspend fun toggleSongLibrary(+ videoId: String,+ addToLibrary: Boolean,+ ): Result<Boolean> =+ runCatching {+ if (addToLibrary) {+ addSongToLibrary(videoId).getOrThrow()+ } else {+ removeSongFromLibrary(videoId).getOrThrow()+ }+ }++ suspend fun getMediaInfo(videoId: String): Result<MediaInfo> =+ runCatching {+ return innerTube.getMediaInfo(videoId)+ }++ suspend fun getTasteProfile(): Result<TasteProfile> =+ runCatching {+ // Browse the taste builder page+ // Note: Full parsing requires additional model support for musicTastebuilderShelfRenderer+ // This returns an empty profile for now - can be enhanced when models are added+ innerTube+ .browse(+ client = WEB_REMIX,+ browseId = "FEmusic_tastebuilder",+ setLogin = true,+ ).body<BrowseResponse>()++ TasteProfile(artists = emptyMap())+ }++ suspend fun setTasteProfile(+ selectedArtists: List<String>,+ allArtists: Map<String, TasteArtist>,+ ): Result<Unit> =+ runCatching {+ val selectedValues = selectedArtists.mapNotNull { allArtists[it]?.selectionValue }+ val impressionValues = allArtists.values.map { it.impressionValue }++ if (selectedValues.isNotEmpty()) {+ feedback(selectedValues + impressionValues).getOrThrow()+ }+ }++ suspend fun removeHistoryItems(feedbackTokens: List<String>): Result<Boolean> =+ runCatching {+ feedback(feedbackTokens).getOrThrow()+ }++ @JvmInline+ value class SearchFilter(+ val value: String,+ ) {+ companion object {+ val FILTER_SONG = SearchFilter("EgWKAQIIAWoKEAkQBRAKEAMQBA%3D%3D")+ val FILTER_VIDEO = SearchFilter("EgWKAQIQAWoKEAkQChAFEAMQBA%3D%3D")+ val FILTER_ALBUM = SearchFilter("EgWKAQIYAWoKEAkQChAFEAMQBA%3D%3D")+ val FILTER_ARTIST = SearchFilter("EgWKAQIgAWoKEAkQChAFEAMQBA%3D%3D")+ val FILTER_FEATURED_PLAYLIST = SearchFilter("EgeKAQQoADgBagwQDhAKEAMQBRAJEAQ%3D")+ val FILTER_COMMUNITY_PLAYLIST = SearchFilter("EgeKAQQoAEABagoQAxAEEAoQCRAF")+ val FILTER_PODCAST = SearchFilter("EgWKAQJQAWoKEAkQChAFEAMQBA%3D%3D")+ val FILTER_EPISODE = SearchFilter("EgWKAQJYAWoKEAkQChAFEAMQBA%3D%3D")+ val FILTER_PROFILE = SearchFilter("EgWKAQJYAWoSEAUQCRADEAQQEBAVEAoQDhAR")+ }+ }++ @JvmInline+ value class LibraryFilter(+ val value: String,+ ) {+ companion object {+ val FILTER_RECENT_ACTIVITY = LibraryFilter("4qmFsgIrEhdGRW11c2ljX2xpYnJhcnlfbGFuZGluZxoQZ2dNR0tnUUlCaEFCb0FZQg%3D%3D")+ val FILTER_RECENTLY_PLAYED = LibraryFilter("4qmFsgIrEhdGRW11c2ljX2xpYnJhcnlfbGFuZGluZxoQZ2dNR0tnUUlCUkFCb0FZQg%3D%3D")+ val FILTER_PLAYLISTS_ALPHABETICAL = LibraryFilter("4qmFsgIrEhdGRW11c2ljX2xpa2VkX3BsYXlsaXN0cxoQZ2dNR0tnUUlBUkFBb0FZQg%3D%3D")+ val FILTER_PLAYLISTS_RECENTLY_SAVED = LibraryFilter("4qmFsgIrEhdGRW11c2ljX2xpa2VkX3BsYXlsaXN0cxoQZ2dNR0tnUUlBQkFCb0FZQg%3D%3D")+ }+ }++ const val MAX_GET_QUEUE_SIZE = 1000++ private val VISITOR_DATA_REGEX = Regex("^Cg[t|s]")++ // LOCAL CHANGE: upstream calls into pages/NewPipe.kt here, which this copy+ // does not carry — see this module's README. The branch was already dead,+ // since ENABLE_NEWPIPE_STREAM_INFO_EXTRACTOR is false upstream too, and+ // stream URLs in this app are resolved by YouTubeStreamResolver instead.+ fun getNewPipeStreamUrls(videoId: String): List<Pair<Int, String>> = emptyList()++ suspend fun newPipePlayer(+ videoId: String,+ tempRes: PlayerResponse,+ ): PlayerResponse? {+ if (tempRes.playabilityStatus.status != "OK") {+ return null+ }++ val streamsList = getNewPipeStreamUrls(videoId)+ if (streamsList.isEmpty()) return null++ val decodedSigResponse =+ tempRes.copy(+ streamingData =+ tempRes.streamingData?.copy(+ formats =+ tempRes.streamingData.formats?.map { format ->+ format.copy(+ url = streamsList.find { it.first == format.itag }?.second ?: format.url,+ )+ },+ adaptiveFormats =+ tempRes.streamingData.adaptiveFormats.map { adaptiveFormat ->+ adaptiveFormat.copy(+ url = streamsList.find { it.first == adaptiveFormat.itag }?.second ?: adaptiveFormat.url,+ )+ },+ ),+ )++ val urlList =+ (+ decodedSigResponse.streamingData+ ?.adaptiveFormats+ ?.mapNotNull { it.url }+ ?.toMutableList() ?: mutableListOf()+ ).apply {+ decodedSigResponse.streamingData+ ?.formats+ ?.mapNotNull { it.url }+ ?.let { addAll(it) }+ }++ return if (urlList.isNotEmpty()) {+ decodedSigResponse+ } else {+ null+ }+ }++ /**+ * Upload a song to YouTube Music.+ * @param filename The name of the file+ * @param data The file data as ByteArray+ * @param onProgress Callback for upload progress (0.0 to 1.0)+ * @return true if upload succeeded+ */+ suspend fun uploadSong(+ filename: String,+ data: ByteArray,+ onProgress: ((Float) -> Unit)? = null,+ ): Result<Boolean> =+ runCatching {+ onProgress?.invoke(0f)++ // Step 1: Initialize upload (5% of progress)+ val initResponse = innerTube.initSongUpload(filename, data.size.toLong())+ val uploadUrl =+ initResponse.headers["X-Goog-Upload-URL"]+ ?: throw Exception("Failed to get upload URL")++ onProgress?.invoke(0.05f)++ // Step 2: Upload file data (5% to 100% of progress)+ val uploadResponse =+ innerTube.uploadSongData(+ uploadUrl = uploadUrl,+ data = data,+ onProgress = { uploadProgress ->+ // Map upload progress (0-1) to overall progress (0.05-1.0)+ onProgress?.invoke(0.05f + uploadProgress * 0.95f)+ },+ )++ val status = uploadResponse.headers["X-Goog-Upload-Status"]+ status == "final"+ }++ /**+ * Delete an uploaded song from YouTube Music library.+ * @param entityId The entity ID of the uploaded song (typically the video ID)+ * @return true if deletion succeeded+ */+ suspend fun deleteUploadedSong(entityId: String): Result<Boolean> =+ runCatching {+ innerTube.deletePrivatelyOwnedEntity(entityId)+ true+ }++ /**+ * Supported file types for upload+ */+ val SUPPORTED_UPLOAD_TYPES = listOf("mp3", "m4a", "wma", "flac", "ogg")++ /**+ * Maximum file size for upload (300MB)+ */+ const val MAX_UPLOAD_SIZE = 314572800L++ suspend fun resolveArtistIds(items: List<YTItem>): List<YTItem> {+ val missingNames = mutableSetOf<String>()+ for (item in items) {+ when (item) {+ is SongItem -> item.artists.filter { it.id == null }.forEach { missingNames.add(it.name) }+ is AlbumItem -> item.artists?.filter { it.id == null }?.forEach { missingNames.add(it.name) }+ is PlaylistItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ is EpisodeItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ is PodcastItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ else -> {}+ }+ }++ if (missingNames.isEmpty()) return items++ val resolved = coroutineScope {+ val semaphore = kotlinx.coroutines.sync.Semaphore(8)+ missingNames.map { name ->+ async {+ semaphore.acquire()+ try {+ val searchResult = search(name, SearchFilter.FILTER_ARTIST).getOrNull()+ val normalizedName = name.trim()+ val artistId = searchResult?.items+ ?.filterIsInstance<ArtistItem>()+ ?.firstOrNull { candidate ->+ candidate.title.trim().equals(normalizedName, ignoreCase = true)+ }?.id+ if (artistId != null) name to artistId else null+ } finally {+ semaphore.release()+ }+ }+ }.awaitAll().filterNotNull().toMap()+ }++ fun Artist.resolve() = if (id == null) resolved[name]?.let { copy(id = it) } ?: this else this+ return items.map { item ->+ when (item) {+ is SongItem -> item.copy(artists = item.artists.map { it.resolve() })+ is AlbumItem -> item.copy(artists = item.artists?.map { it.resolve() })+ is PlaylistItem -> item.copy(author = item.author?.resolve())+ is EpisodeItem -> item.copy(author = item.author?.resolve())+ is PodcastItem -> item.copy(author = item.author?.resolve())+ else -> item+ }+ }+ }++ /**+ * Collects all unique missing artist names from [items], resolves them in parallel,+ * and returns a name -> id map. Use this when resolving across multiple sections+ * to avoid duplicate searches for the same artist.+ */+ suspend fun resolveArtistIdMap(items: List<YTItem>): Map<String, String> {+ val missingNames = mutableSetOf<String>()+ for (item in items) {+ when (item) {+ is SongItem -> item.artists.filter { it.id == null }.forEach { missingNames.add(it.name) }+ is AlbumItem -> item.artists?.filter { it.id == null }?.forEach { missingNames.add(it.name) }+ is PlaylistItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ is EpisodeItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ is PodcastItem -> item.author?.let { if (it.id == null) missingNames.add(it.name) }+ else -> {}+ }+ }++ if (missingNames.isEmpty()) return emptyMap()++ return coroutineScope {+ val semaphore = kotlinx.coroutines.sync.Semaphore(8)+ missingNames.map { name ->+ async {+ semaphore.acquire()+ try {+ val searchResult = search(name, SearchFilter.FILTER_ARTIST).getOrNull()+ val normalizedName = name.trim()+ val artistId = searchResult?.items+ ?.filterIsInstance<ArtistItem>()+ ?.firstOrNull { candidate ->+ candidate.title.trim().equals(normalizedName, ignoreCase = true)+ }?.id+ if (artistId != null) name to artistId else null+ } finally {+ semaphore.release()+ }+ }+ }.awaitAll().filterNotNull().toMap()+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/YouTubeConstants.kt b/innertube/src/main/kotlin/com/metrolist/innertube/YouTubeConstants.ktnew file mode 100644index 0000000..91e1bea--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/YouTubeConstants.kt@@ -0,0 +1,6 @@+package com.metrolist.innertube++object YouTubeConstants {+ const val DEFAULT_TOP_RESULT = "Top result"+ const val DEFAULT_OTHER_RESULTS = "Other"+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/AccountInfo.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/AccountInfo.ktnew file mode 100644index 0000000..487a11d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/AccountInfo.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.models++data class AccountInfo(+ val name: String,+ val email: String?,+ val channelHandle: String?,+ val thumbnailUrl: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/AutomixPreviewVideoRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/AutomixPreviewVideoRenderer.ktnew file mode 100644index 0000000..4470698--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/AutomixPreviewVideoRenderer.kt@@ -0,0 +1,18 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class AutomixPreviewVideoRenderer(+ val content: Content,+) {+ @Serializable+ data class Content(+ val automixPlaylistVideoRenderer: AutomixPlaylistVideoRenderer,+ ) {+ @Serializable+ data class AutomixPlaylistVideoRenderer(+ val navigationEndpoint: NavigationEndpoint,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Badges.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Badges.ktnew file mode 100644index 0000000..7ca6dde--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Badges.kt@@ -0,0 +1,13 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Badges(+ val musicInlineBadgeRenderer: MusicInlineBadgeRenderer?,+) {+ @Serializable+ data class MusicInlineBadgeRenderer(+ val icon: Icon,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Button.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Button.ktnew file mode 100644index 0000000..9af1edf--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Button.kt@@ -0,0 +1,16 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Button(+ val buttonRenderer: ButtonRenderer,+) {+ @Serializable+ data class ButtonRenderer(+ val text: Runs,+ val navigationEndpoint: NavigationEndpoint?,+ val command: NavigationEndpoint?,+ val icon: Icon?,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Context.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Context.ktnew file mode 100644index 0000000..922fe36--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Context.kt@@ -0,0 +1,43 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Context(+ val client: Client,+ val thirdParty: ThirdParty? = null,+ val request: Request = Request(),+ val user: User = User()+) {+ @Serializable+ data class Client(+ val clientName: String,+ val clientVersion: String,+ val userAgent: String? = null,+ val osName: String? = null,+ val osVersion: String? = null,+ val deviceMake: String? = null,+ val deviceModel: String? = null,+ val androidSdkVersion: String? = null,+ val gl: String,+ val hl: String,+ val visitorData: String?,+ )++ @Serializable+ data class ThirdParty(+ val embedUrl: String,+ )++ @Serializable+ data class Request(+ val internalExperimentFlags: Array<String> = emptyArray(),+ val useSsl: Boolean = true,+ )++ @Serializable+ data class User(+ val lockedSafetyMode: Boolean = false,+ val onBehalfOfUser: String? = null,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Continuation.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Continuation.ktnew file mode 100644index 0000000..0257fba--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Continuation.kt@@ -0,0 +1,20 @@+package com.metrolist.innertube.models++import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.JsonNames++@OptIn(ExperimentalSerializationApi::class)+@Serializable+data class Continuation(+ @JsonNames("nextContinuationData", "nextRadioContinuationData")+ val nextContinuationData: NextContinuationData?,+) {+ @Serializable+ data class NextContinuationData(+ val continuation: String,+ )+}++fun List<Continuation>.getContinuation() =+ firstOrNull()?.nextContinuationData?.continuation\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/ContinuationItemRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/ContinuationItemRenderer.ktnew file mode 100644index 0000000..59ba47b--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/ContinuationItemRenderer.kt@@ -0,0 +1,18 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class ContinuationItemRenderer(+ val continuationEndpoint: ContinuationEndpoint?,+) {+ @Serializable+ data class ContinuationEndpoint(+ val continuationCommand: ContinuationCommand?,+ ) {+ @Serializable+ data class ContinuationCommand(+ val token: String?,+ )+ }+}\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Endpoint.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Endpoint.ktnew file mode 100644index 0000000..205dac8--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Endpoint.kt@@ -0,0 +1,123 @@+package com.metrolist.innertube.models++import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ALBUM+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ARTIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PLAYLIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_AUDIOBOOK+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+import kotlinx.serialization.Serializable++@Serializable+sealed class Endpoint++@Serializable+data class WatchEndpoint(+ val videoId: String? = null,+ val playlistId: String? = null,+ val playlistSetVideoId: String? = null,+ val params: String? = null,+ val index: Int? = null,+ val watchEndpointMusicSupportedConfigs: WatchEndpointMusicSupportedConfigs? = null,+) : Endpoint() {++ @Serializable+ data class WatchEndpointMusicSupportedConfigs(+ val watchEndpointMusicConfig: WatchEndpointMusicConfig,+ ) {+ @Serializable+ data class WatchEndpointMusicConfig(+ val musicVideoType: String,+ ) {+ companion object {+ const val MUSIC_VIDEO_TYPE_OMV = "MUSIC_VIDEO_TYPE_OMV"+ const val MUSIC_VIDEO_TYPE_UGC = "MUSIC_VIDEO_TYPE_UGC"+ const val MUSIC_VIDEO_TYPE_ATV = "MUSIC_VIDEO_TYPE_ATV"+ }+ }+ }+}++@Serializable+data class BrowseEndpoint(+ val browseId: String,+ val params: String? = null,+ val browseEndpointContextSupportedConfigs: BrowseEndpointContextSupportedConfigs? = null,+) : Endpoint() {+ val isArtistEndpoint: Boolean+ get() = browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_ARTIST+ val isAlbumEndpoint: Boolean+ get() = browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_ALBUM ||+ browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_AUDIOBOOK+ val isPlaylistEndpoint: Boolean+ get() = browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_PLAYLIST+ val isPodcastEndpoint: Boolean+ get() = browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE++ @Serializable+ data class BrowseEndpointContextSupportedConfigs(+ val browseEndpointContextMusicConfig: BrowseEndpointContextMusicConfig,+ ) {+ @Serializable+ data class BrowseEndpointContextMusicConfig(+ val pageType: String,+ ) {+ companion object {+ const val MUSIC_PAGE_TYPE_ALBUM = "MUSIC_PAGE_TYPE_ALBUM"+ const val MUSIC_PAGE_TYPE_AUDIOBOOK = "MUSIC_PAGE_TYPE_AUDIOBOOK"+ const val MUSIC_PAGE_TYPE_PLAYLIST = "MUSIC_PAGE_TYPE_PLAYLIST"+ const val MUSIC_PAGE_TYPE_ARTIST = "MUSIC_PAGE_TYPE_ARTIST"+ const val MUSIC_PAGE_TYPE_LIBRARY_ARTIST = "MUSIC_PAGE_TYPE_LIBRARY_ARTIST"+ const val MUSIC_PAGE_TYPE_USER_CHANNEL = "MUSIC_PAGE_TYPE_USER_CHANNEL"+ const val MUSIC_PAGE_TYPE_TRACK_LYRICS = "MUSIC_PAGE_TYPE_TRACK_LYRICS"+ const val MUSIC_PAGE_TYPE_TRACK_RELATED = "MUSIC_PAGE_TYPE_TRACK_RELATED"+ const val MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE = "MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE"+ const val MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE = "MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE"+ }+ }+ }+}++@Serializable+data class SearchEndpoint(+ val params: String?,+ val query: String,+) : Endpoint()++@Serializable+data class FeedbackEndpoint(+ val feedbackToken: String+) : Endpoint()++@Serializable+data class QueueAddEndpoint(+ val queueInsertPosition: String,+ val queueTarget: QueueTarget,+) : Endpoint() {+ @Serializable+ data class QueueTarget(+ val videoId: String? = null,+ val playlistId: String? = null,+ )+}++@Serializable+data class ShareEntityEndpoint(+ val serializedShareEntity: String,+) : Endpoint()++@Serializable+data class DefaultServiceEndpoint(+ var subscribeEndpoint: SubscribeEndpoint?,+ var feedbackEndpoint: FeedbackEndpoint?+) : Endpoint() {+ @Serializable+ data class SubscribeEndpoint(+ val channelIds: List<String>,+ val params: String? = null,+ ) : Endpoint()+}++@Serializable+data class ToggledServiceEndpoint(+ var feedbackEndpoint: FeedbackEndpoint?+) : Endpoint()\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/GridRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/GridRenderer.ktnew file mode 100644index 0000000..a8de409--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/GridRenderer.kt@@ -0,0 +1,26 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class GridRenderer(+ val header: Header?,+ val items: List<Item>,+ val continuations: List<Continuation>?,+) {+ @Serializable+ data class Header(+ val gridHeaderRenderer: GridHeaderRenderer,+ ) {+ @Serializable+ data class GridHeaderRenderer(+ val title: Runs,+ )+ }++ @Serializable+ data class Item(+ val musicNavigationButtonRenderer: MusicNavigationButtonRenderer?,+ val musicTwoRowItemRenderer: MusicTwoRowItemRenderer?,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Icon.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Icon.ktnew file mode 100644index 0000000..3a5116d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Icon.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Icon(+ val iconType: String,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MediaInfo.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MediaInfo.ktnew file mode 100644index 0000000..74f265d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MediaInfo.kt@@ -0,0 +1,15 @@+package com.metrolist.innertube.models++data class MediaInfo(+ val videoId: String,+ val title: String? = null,+ val author: String? = null,+ val authorId: String? = null,+ val authorThumbnail: String? = null,+ val description: String? = null,+ val uploadDate: String? = null,+ val subscribers: String? = null,+ val viewCount: Int? = null,+ val like: Int? = null,+ val dislike: Int? = null,+)\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Menu.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Menu.ktnew file mode 100644index 0000000..76ec104--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Menu.kt@@ -0,0 +1,53 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Menu(+ val menuRenderer: MenuRenderer,+) {+ @Serializable+ data class MenuRenderer(+ val items: List<Item>?,+ val topLevelButtons: List<TopLevelButton>?,+ ) {+ @Serializable+ data class Item(+ val menuNavigationItemRenderer: MenuNavigationItemRenderer?,+ val menuServiceItemRenderer: MenuServiceItemRenderer?,+ val toggleMenuServiceItemRenderer: ToggleMenuServiceRenderer?,+ ) {+ @Serializable+ data class MenuNavigationItemRenderer(+ val text: Runs,+ val icon: Icon,+ val navigationEndpoint: NavigationEndpoint,+ )++ @Serializable+ data class MenuServiceItemRenderer(+ val text: Runs,+ val icon: Icon,+ val serviceEndpoint: NavigationEndpoint,+ )+ @Serializable+ data class ToggleMenuServiceRenderer(+ val defaultIcon: Icon,+ val defaultServiceEndpoint: DefaultServiceEndpoint,+ val toggledServiceEndpoint: ToggledServiceEndpoint?,+ val isSelected: Boolean = false,+ )+ }++ @Serializable+ data class TopLevelButton(+ val buttonRenderer: ButtonRenderer?,+ ) {+ @Serializable+ data class ButtonRenderer(+ val icon: Icon,+ val navigationEndpoint: NavigationEndpoint,+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCardShelfRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCardShelfRenderer.ktnew file mode 100644index 0000000..09c5122--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCardShelfRenderer.kt@@ -0,0 +1,30 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicCardShelfRenderer(+ val title: Runs,+ val subtitle: Runs,+ val thumbnail: ThumbnailRenderer,+ val header: Header?,+ val contents: List<Content>?,+ val buttons: List<Button>,+ val onTap: NavigationEndpoint,+ val subtitleBadges: List<Badges>?,+) {+ @Serializable+ data class Header(+ val musicCardShelfHeaderBasicRenderer: MusicCardShelfHeaderBasicRenderer,+ ) {+ @Serializable+ data class MusicCardShelfHeaderBasicRenderer(+ val title: Runs,+ )+ }++ @Serializable+ data class Content(+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer?,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCarouselShelfRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCarouselShelfRenderer.ktnew file mode 100644index 0000000..df8256b--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicCarouselShelfRenderer.kt@@ -0,0 +1,32 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicCarouselShelfRenderer(+ val header: Header?,+ val contents: List<Content>,+ val itemSize: String,+ val numItemsPerColumn: Int?,+) {+ @Serializable+ data class Header(+ val musicCarouselShelfBasicHeaderRenderer: MusicCarouselShelfBasicHeaderRenderer,+ ) {+ @Serializable+ data class MusicCarouselShelfBasicHeaderRenderer(+ val strapline: Runs?,+ val title: Runs,+ val thumbnail: ThumbnailRenderer?,+ val moreContentButton: Button?,+ )+ }++ @Serializable+ data class Content(+ val musicTwoRowItemRenderer: MusicTwoRowItemRenderer?,+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer?,+ val musicMultiRowListItemRenderer: MusicMultiRowListItemRenderer?,+ val musicNavigationButtonRenderer: MusicNavigationButtonRenderer?, // navigation button in explore tab+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicDescriptionShelfRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicDescriptionShelfRenderer.ktnew file mode 100644index 0000000..64b8d0e--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicDescriptionShelfRenderer.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicDescriptionShelfRenderer(+ val header: Runs?,+ val subheader: Runs?,+ val description: Runs?,+ val footer: Runs?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicEditablePlaylistDetailHeaderRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicEditablePlaylistDetailHeaderRenderer.ktnew file mode 100644index 0000000..44afce8--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicEditablePlaylistDetailHeaderRenderer.kt@@ -0,0 +1,35 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicEditablePlaylistDetailHeaderRenderer(+ val header: Header,+ val editHeader: EditHeader+) {+ @Serializable+ data class Header(+ val musicDetailHeaderRenderer: MusicDetailHeaderRenderer?,+ val musicResponsiveHeaderRenderer: MusicResponsiveHeaderRenderer?+ )++ @Serializable+ data class EditHeader(+ val musicPlaylistEditHeaderRenderer: MusicPlaylistEditHeaderRenderer?+ )+}++@Serializable+data class MusicDetailHeaderRenderer(+ val title: Runs,+ val subtitle: Runs,+ val secondSubtitle: Runs,+ val description: Runs?,+ val thumbnail: ThumbnailRenderer,+ val menu: Menu,+)++@Serializable+data class MusicPlaylistEditHeaderRenderer(+ val editTitle: Runs?+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowImageItemRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowImageItemRenderer.ktnew file mode 100644index 0000000..31d1c4c--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowImageItemRenderer.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicMultiRowImageItemRenderer(+ val title: Runs,+ val subtitle: Runs,+ val thumbnail: ThumbnailRenderer,+ val onTap: NavigationEndpoint,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowListItemRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowListItemRenderer.ktnew file mode 100644index 0000000..6b045e8--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicMultiRowListItemRenderer.kt@@ -0,0 +1,24 @@+package com.metrolist.innertube.models++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++@Serializable+data class MusicMultiRowListItemRenderer(+ val title: Runs?,+ val subtitle: Runs?,+ @SerialName("secondSubtitle")+ val secondSubtitle: Runs? = null,+ @SerialName("secondarySubtitle")+ val secondarySubtitle: Runs? = null,+ val thumbnail: ThumbnailRenderer?,+ val onTap: NavigationEndpoint?,+ val playbackProgress: PlaybackProgress?,+ val displayStyle: String?,+ val menu: Menu?,+) {+ @Serializable+ data class PlaybackProgress(+ val value: Float? = null,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicNavigationButtonRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicNavigationButtonRenderer.ktnew file mode 100644index 0000000..dad8676--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicNavigationButtonRenderer.kt@@ -0,0 +1,21 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicNavigationButtonRenderer(+ val buttonText: Runs,+ val solid: Solid?,+ val iconStyle: IconStyle?,+ val clickCommand: NavigationEndpoint,+) {+ @Serializable+ data class Solid(+ val leftStripeColor: Long,+ )++ @Serializable+ data class IconStyle(+ val icon: Icon,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicPlaylistShelfRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicPlaylistShelfRenderer.ktnew file mode 100644index 0000000..b2495e3--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicPlaylistShelfRenderer.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicPlaylistShelfRenderer(+ val playlistId: String?,+ val contents: List<MusicShelfRenderer.Content> = emptyList(),+ val collapsedItemCount: Int? = null,+ val continuations: List<Continuation>? = null,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicQueueRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicQueueRenderer.ktnew file mode 100644index 0000000..475ac74--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicQueueRenderer.kt@@ -0,0 +1,25 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicQueueRenderer(+ val content: Content?,+ val header: Header?,+) {+ @Serializable+ data class Content(+ val playlistPanelRenderer: PlaylistPanelRenderer,+ )++ @Serializable+ data class Header(+ val musicQueueHeaderRenderer: MusicQueueHeaderRenderer?,+ ) {+ @Serializable+ data class MusicQueueHeaderRenderer(+ val title: Runs?,+ val subtitle: Runs?,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveHeaderRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveHeaderRenderer.ktnew file mode 100644index 0000000..50956a5--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveHeaderRenderer.kt@@ -0,0 +1,101 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicResponsiveHeaderRenderer(+ val thumbnail: ThumbnailRenderer? = null,+ val buttons: List<Button> = emptyList(),+ val title: Runs = Runs(null),+ val subtitle: Runs = Runs(null),+ val secondSubtitle: Runs? = null,+ val straplineTextOne: Runs? = null,+ val description: DescriptionWrapper? = null,+ val facepile: FacepileWrapper? = null,+) {+ @Serializable+ data class Button(+ val musicPlayButtonRenderer: MusicPlayButtonRenderer? = null,+ val menuRenderer: Menu.MenuRenderer? = null,+ val toggleButtonRenderer: ToggleButtonRenderer? = null,+ ) {+ @Serializable+ data class MusicPlayButtonRenderer(+ val playNavigationEndpoint: NavigationEndpoint? = null,+ )++ @Serializable+ data class ToggleButtonRenderer(+ val defaultIcon: Icon? = null,+ val defaultServiceEndpoint: DefaultServiceEndpoint? = null,+ val toggledServiceEndpoint: ToggledServiceEndpoint? = null,+ )+ }+}++@Serializable+data class AvatarStackViewModel(+ val avatars: List<Avatar>?,+ val text: AvatarText?,+ val rendererContext: RendererContext?,+) {+ @Serializable+ data class Avatar(+ val avatarViewModel: AvatarViewModel?,+ )++ @Serializable+ data class AvatarViewModel(+ val image: AvatarImage?,+ )++ @Serializable+ data class AvatarImage(+ val sources: List<ImageSource>?,+ )++ @Serializable+ data class ImageSource(+ val url: String?,+ )++ @Serializable+ data class AvatarText(+ val content: String?,+ )++ @Serializable+ data class RendererContext(+ val commandContext: CommandContext?,+ )++ @Serializable+ data class CommandContext(+ val onTap: OnTap?,+ )++ @Serializable+ data class OnTap(+ val innertubeCommand: InnerTubeBrowseCommand?,+ )++ @Serializable+ data class InnerTubeBrowseCommand(+ val browseEndpoint: BrowseEndpoint?,+ )++ @Serializable+ data class BrowseEndpoint(+ val browseId: String?,+ )+}++@Serializable+data class DescriptionWrapper(+ val musicDescriptionShelfRenderer: MusicDescriptionShelfRenderer?,+)++@Serializable+data class FacepileWrapper(+ val avatarStackViewModel: AvatarStackViewModel?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveListItemRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveListItemRenderer.ktnew file mode 100644index 0000000..aa31350--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicResponsiveListItemRenderer.kt@@ -0,0 +1,149 @@+@file:OptIn(ExperimentalSerializationApi::class)++package com.metrolist.innertube.models++import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ALBUM+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ARTIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_AUDIOBOOK+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_LIBRARY_ARTIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PLAYLIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_USER_CHANNEL+import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.JsonNames++/**+ * Typical list item+ * Used in [MusicCarouselShelfRenderer], [MusicShelfRenderer]+ * Appears in quick picks, search results, table items, etc.+ */+@Serializable+data class MusicResponsiveListItemRenderer(+ val badges: List<Badges>?,+ val fixedColumns: List<FlexColumn>?,+ val flexColumns: List<FlexColumn>,+ val thumbnail: ThumbnailRenderer?,+ val menu: Menu?,+ val playlistItemData: PlaylistItemData?,+ val overlay: Overlay?,+ val navigationEndpoint: NavigationEndpoint?,+) {+ val isSong: Boolean+ get() = navigationEndpoint == null+ || navigationEndpoint.watchEndpoint != null+ || navigationEndpoint.watchPlaylistEndpoint != null+ || overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint != null+ val isPlaylist: Boolean+ get() = navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_PLAYLIST+ val isAlbum: Boolean+ get() = navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_ALBUM ||+ navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_AUDIOBOOK+ val isArtist: Boolean+ get() = navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_ARTIST+ || navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_LIBRARY_ARTIST+ val isPodcast: Boolean+ get() = navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+ val isUserChannel: Boolean+ get() = navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_USER_CHANNEL+ val isEpisode: Boolean+ get() {+ // Method 1: Check browse endpoint (for episode detail pages)+ if (navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType == MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE) {+ return true+ }+ // Method 2: Check if first subtitle text is "Episode" (for search results)+ val firstSubtitleText = flexColumns.getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()?.text+ if (firstSubtitleText == "Episode") {+ return true+ }+ // Method 3: Check for podcast link in subtitle (backup detection).+ //+ // Episode items that appear in filtered search results may have:+ // - navigationEndpoint.watchEndpoint (playable) → isSong=true would wrongly match+ // - playlistItemData = null (not in a playlist context)+ // - subtitle: [date · podcast-name] (podcast-name links to PODCAST_SHOW_DETAIL_PAGE)+ //+ // The presence of a PODCAST_SHOW_DETAIL_PAGE browse link in the subtitle is unique to+ // episodes — regular songs never carry such a link. We accept either a playlistItemData+ // videoId OR a direct watchEndpoint videoId to handle both playlist and standalone contexts.+ val hasPodcastLink = flexColumns.getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.any { run ->+ run.navigationEndpoint?.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType == MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+ } == true+ val hasVideoId = videoId != null+ return hasPodcastLink && hasVideoId+ }++ val musicVideoType: String?+ get() =+ overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.musicVideoType+ ?: navigationEndpoint?.musicVideoType++ val videoId: String?+ get() = playlistItemData?.videoId+ ?: flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId++ val playlistSetVideoId: String?+ get() = playlistItemData?.playlistSetVideoId+ ?: overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.playlistSetVideoId++ @Serializable+ data class FlexColumn(+ @JsonNames("musicResponsiveListItemFixedColumnRenderer")+ val musicResponsiveListItemFlexColumnRenderer: MusicResponsiveListItemFlexColumnRenderer,+ ) {+ @Serializable+ data class MusicResponsiveListItemFlexColumnRenderer(+ val text: Runs?,+ )+ }++ @Serializable+ data class PlaylistItemData(+ val playlistSetVideoId: String?,+ val videoId: String,+ )++ @Serializable+ data class Overlay(+ val musicItemThumbnailOverlayRenderer: MusicItemThumbnailOverlayRenderer,+ ) {+ @Serializable+ data class MusicItemThumbnailOverlayRenderer(+ val content: Content,+ ) {+ @Serializable+ data class Content(+ val musicPlayButtonRenderer: MusicPlayButtonRenderer,+ ) {+ @Serializable+ data class MusicPlayButtonRenderer(+ val playNavigationEndpoint: NavigationEndpoint?,+ )+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicShelfRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicShelfRenderer.ktnew file mode 100644index 0000000..c20a9c3--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicShelfRenderer.kt@@ -0,0 +1,29 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class MusicShelfRenderer(+ val title: Runs?,+ val contents: List<Content>?,+ val continuations: List<Continuation>?,+ val bottomEndpoint: NavigationEndpoint?,+ val moreContentButton: Button?,+) {+ @Serializable+ data class Content(+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer?,+ val musicMultiRowListItemRenderer: MusicMultiRowListItemRenderer?,+ val continuationItemRenderer: ContinuationItemRenderer?,+ )+}++fun List<MusicShelfRenderer.Content>.getItems(): List<MusicResponsiveListItemRenderer> =+ mapNotNull { it.musicResponsiveListItemRenderer }++fun List<MusicShelfRenderer.Content>.getContinuation(): String? =+ firstOrNull { it.continuationItemRenderer != null }+ ?.continuationItemRenderer+ ?.continuationEndpoint+ ?.continuationCommand+ ?.token\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicTwoRowItemRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicTwoRowItemRenderer.ktnew file mode 100644index 0000000..eaac38b--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/MusicTwoRowItemRenderer.kt@@ -0,0 +1,86 @@+package com.metrolist.innertube.models++import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ALBUM+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ARTIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_AUDIOBOOK+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PLAYLIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_USER_CHANNEL+import kotlinx.serialization.Serializable++/**+ * Two row: a big thumbnail, a title, and a subtitle+ * Used in [GridRenderer] and [MusicCarouselShelfRenderer]+ * Item type: song, video, album, playlist, artist+ */+@Serializable+data class MusicTwoRowItemRenderer(+ val title: Runs,+ val subtitle: Runs?,+ val subtitleBadges: List<Badges>?,+ val menu: Menu?,+ val thumbnailRenderer: ThumbnailRenderer,+ val navigationEndpoint: NavigationEndpoint,+ val thumbnailOverlay: MusicResponsiveListItemRenderer.Overlay?,+) {+ val isSong: Boolean+ get() = navigationEndpoint.endpoint is WatchEndpoint+ val isPlaylist: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_PLAYLIST+ val isAlbum: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_ALBUM ||+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_AUDIOBOOK+ val isArtist: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_ARTIST+ val isPodcast: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+ val isUserChannel: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_USER_CHANNEL+ val isEpisode: Boolean+ get() =+ navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType ==+ MUSIC_PAGE_TYPE_NON_MUSIC_AUDIO_TRACK_PAGE++ val musicVideoType: String?+ get() =+ thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.musicVideoType+ ?: navigationEndpoint.musicVideoType+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/NavigationEndpoint.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/NavigationEndpoint.ktnew file mode 100644index 0000000..f545b4f--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/NavigationEndpoint.kt@@ -0,0 +1,70 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class NavigationEndpoint(+ val watchEndpoint: WatchEndpoint? = null,+ val watchPlaylistEndpoint: WatchEndpoint? = null,+ val browseEndpoint: BrowseEndpoint? = null,+ val searchEndpoint: SearchEndpoint? = null,+ val queueAddEndpoint: QueueAddEndpoint? = null,+ val shareEntityEndpoint: ShareEntityEndpoint? = null,+ val feedbackEndpoint: FeedbackEndpoint? = null,+ val urlEndpoint: UrlEndpoint? = null,+ val deletePrivatelyOwnedEntityCommand: DeletePrivatelyOwnedEntityCommand? = null,+ val confirmDialogEndpoint: ConfirmDialogEndpoint? = null,+) {+ @Serializable+ data class DeletePrivatelyOwnedEntityCommand(+ val entityId: String,+ )++ @Serializable+ data class ConfirmDialogEndpoint(+ val content: ConfirmDialogContent? = null,+ ) {+ @Serializable+ data class ConfirmDialogContent(+ val confirmDialogRenderer: ConfirmDialogRenderer? = null,+ )++ @Serializable+ data class ConfirmDialogRenderer(+ val confirmButton: ConfirmButton? = null,+ )++ @Serializable+ data class ConfirmButton(+ val buttonRenderer: ConfirmButtonRenderer? = null,+ )++ @Serializable+ data class ConfirmButtonRenderer(+ val command: ConfirmCommand? = null,+ )++ @Serializable+ data class ConfirmCommand(+ val musicDeletePrivatelyOwnedEntityCommand: DeletePrivatelyOwnedEntityCommand? = null,+ )+ }+ val endpoint: Endpoint?+ get() =+ watchEndpoint+ ?: watchPlaylistEndpoint+ ?: browseEndpoint+ ?: searchEndpoint+ ?: queueAddEndpoint+ ?: shareEntityEndpoint++ val anyWatchEndpoint: WatchEndpoint?+ get() = watchEndpoint+ ?: watchPlaylistEndpoint++ val musicVideoType: String?+ get() = anyWatchEndpoint+ ?.watchEndpointMusicSupportedConfigs+ ?.watchEndpointMusicConfig+ ?.musicVideoType+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistDeleteBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistDeleteBody.ktnew file mode 100644index 0000000..90026d5--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistDeleteBody.kt@@ -0,0 +1,10 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class PlaylistDeleteBody(+ val context: Context,+ val playlistId: String+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelRenderer.ktnew file mode 100644index 0000000..d164e59--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelRenderer.kt@@ -0,0 +1,21 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class PlaylistPanelRenderer(+ val title: String?,+ val titleText: Runs?,+ val shortBylineText: Runs?,+ val contents: List<Content>,+ val isInfinite: Boolean?,+ val numItemsToShow: Int?,+ val playlistId: String?,+ val continuations: List<Continuation>?,+) {+ @Serializable+ data class Content(+ val playlistPanelVideoRenderer: PlaylistPanelVideoRenderer?,+ val automixPreviewVideoRenderer: AutomixPreviewVideoRenderer?,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelVideoRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelVideoRenderer.ktnew file mode 100644index 0000000..8b08b23--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/PlaylistPanelVideoRenderer.kt@@ -0,0 +1,19 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class PlaylistPanelVideoRenderer(+ val title: Runs?,+ val lengthText: Runs?,+ val longBylineText: Runs?,+ val shortBylineText: Runs?,+ val badges: List<Badges>?,+ val videoId: String?,+ val playlistSetVideoId: String?,+ val selected: Boolean,+ val thumbnail: Thumbnails,+ val unplayableText: Runs?,+ val menu: Menu?,+ val navigationEndpoint: NavigationEndpoint,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/ResponseContext.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/ResponseContext.ktnew file mode 100644index 0000000..aa2ebe7--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/ResponseContext.kt@@ -0,0 +1,21 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class ResponseContext(+ val visitorData: String?,+ val serviceTrackingParams: List<ServiceTrackingParam>?,+) {+ @Serializable+ data class ServiceTrackingParam(+ val params: List<Param>,+ val service: String,+ ) {+ @Serializable+ data class Param(+ val key: String,+ val value: String,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/ReturnYouTubeDislikeResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/ReturnYouTubeDislikeResponse.ktnew file mode 100644index 0000000..b8b60cb--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/ReturnYouTubeDislikeResponse.kt@@ -0,0 +1,14 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class ReturnYouTubeDislikeResponse(+ val id: String? = null,+ val dateCreated: String? = null,+ val likes: Int? = null,+ val dislikes: Int? = null,+ val rating: Double? = null,+ val viewCount: Int? = null,+ val deleted: Boolean? = null,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.ktnew file mode 100644index 0000000..16d396a--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Runs.kt@@ -0,0 +1,76 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Runs(+ val runs: List<Run>?,+)++@Serializable+data class Run(+ val text: String,+ val navigationEndpoint: NavigationEndpoint?,+)++fun List<Run>.splitBySeparator(): List<List<Run>> {+ val res = mutableListOf<List<Run>>()+ var tmp = mutableListOf<Run>()+ forEach { run ->+ if (run.text.trim() == "•") {+ res.add(tmp)+ tmp = mutableListOf()+ } else {+ tmp.add(run)+ }+ }+ res.add(tmp)+ return res+}++fun List<Run>.splitArtistsByConjunction(): List<Run> {+ val result = mutableListOf<Run>()+ val words = ArtistConjunctions.conjunctions+ val conjunctionPattern = Regex(+ if (words.isNotEmpty()) " (${words.joinToString("|") { Regex.escape(it) }}) | & "+ else " & ",+ RegexOption.IGNORE_CASE+ )+ forEach { run ->+ val text = run.text+ if (text.contains(conjunctionPattern)) {+ val parts = text.split(conjunctionPattern)+ parts.forEachIndexed { index, part ->+ if (part.isNotBlank()) {+ result.add(Run(part.trim(), if (index == 0) run.navigationEndpoint else null))+ }+ }+ } else if (text.trim().equals("&", ignoreCase = true) ||+ text.trim().equals("•") ||+ words.any { text.trim().equals(it, ignoreCase = true) }+ ) {+ } else {+ result.add(run)+ }+ }+ return result+}++object ArtistConjunctions {+ var conjunctions: List<String> = listOf("and")+}++fun List<List<Run>>.clean(): List<List<Run>> {+ val firstGroup = getOrNull(0) ?: return this+ val hasArtistSignals = firstGroup.any { it.navigationEndpoint != null } ||+ firstGroup.any { it.text.contains(" & ") } ||+ ArtistConjunctions.conjunctions.any { conj ->+ firstGroup.any { it.text.trim().equals(conj, ignoreCase = true) }+ }+ return if (hasArtistSignals) this else drop(1)+}++fun List<Run>.oddElements() =+ filterIndexed { index, _ ->+ index % 2 == 0+ }diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestions.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestions.ktnew file mode 100644index 0000000..15a11fc--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestions.kt@@ -0,0 +1,6 @@+package com.metrolist.innertube.models++data class SearchSuggestions(+ val queries: List<String>,+ val recommendedItems: List<YTItem>,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestionsSectionRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestionsSectionRenderer.ktnew file mode 100644index 0000000..cf21f30--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/SearchSuggestionsSectionRenderer.kt@@ -0,0 +1,20 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class SearchSuggestionsSectionRenderer(+ val contents: List<Content>,+) {+ @Serializable+ data class Content(+ val searchSuggestionRenderer: SearchSuggestionRenderer?,+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer?,+ ) {+ @Serializable+ data class SearchSuggestionRenderer(+ val suggestion: Runs,+ val navigationEndpoint: NavigationEndpoint,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/SectionListRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/SectionListRenderer.ktnew file mode 100644index 0000000..7481d30--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/SectionListRenderer.kt@@ -0,0 +1,76 @@+package com.metrolist.innertube.models++import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.JsonNames++@Serializable+data class SectionListRenderer(+ val header: Header?,+ val contents: List<Content>?,+ val continuations: List<Continuation>?,+) {+ @Serializable+ data class Header(+ val chipCloudRenderer: ChipCloudRenderer?,+ ) {+ @Serializable+ data class ChipCloudRenderer(+ val chips: List<Chip>,+ ) {+ @Serializable+ data class Chip(+ val chipCloudChipRenderer: ChipCloudChipRenderer,+ ) {+ @Serializable+ data class ChipCloudChipRenderer(+ val isSelected: Boolean = false,+ val navigationEndpoint: NavigationEndpoint? = null,+ val onDeselectedCommand: NavigationEndpoint? = null,+ // The close button doesn't have the following two fields+ val text: Runs?,+ val uniqueId: String?,+ )+ }+ }+ }++ @OptIn(ExperimentalSerializationApi::class)+ @Serializable+ data class Content(+ @JsonNames("musicImmersiveCarouselShelfRenderer")+ val musicCarouselShelfRenderer: MusicCarouselShelfRenderer?,+ val musicShelfRenderer: MusicShelfRenderer?,+ val musicCardShelfRenderer: MusicCardShelfRenderer?,+ val musicPlaylistShelfRenderer: MusicPlaylistShelfRenderer?,+ val musicDescriptionShelfRenderer: MusicDescriptionShelfRenderer?,+ val musicResponsiveHeaderRenderer: MusicResponsiveHeaderRenderer?,+ val musicEditablePlaylistDetailHeaderRenderer: MusicEditablePlaylistDetailHeaderRenderer?,+ val gridRenderer: GridRenderer?,+ val itemSectionRenderer: ItemSectionRenderer?,+ )+}++@Serializable+data class ItemSectionRenderer(+ val contents: List<Content>?,+ val header: Header? = null,+) {+ @Serializable+ data class Content(+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer? = null,+ val musicShelfRenderer: MusicShelfRenderer? = null,+ val musicPlaylistShelfRenderer: MusicPlaylistShelfRenderer? = null,+ val gridRenderer: GridRenderer? = null,+ )++ @Serializable+ data class Header(+ val itemSectionTabbedHeaderRenderer: ItemSectionTabbedHeaderRenderer?,+ )++ @Serializable+ data class ItemSectionTabbedHeaderRenderer(+ val title: Runs?,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/SubscriptionButton.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/SubscriptionButton.ktnew file mode 100644index 0000000..b968931--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/SubscriptionButton.kt@@ -0,0 +1,16 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class SubscriptionButton(+ val subscribeButtonRenderer: SubscribeButtonRenderer,+) {+ @Serializable+ data class SubscribeButtonRenderer(+ val subscribed: Boolean,+ val channelId: String,+ val longSubscriberCountText: Runs? = null,+ val shortSubscriberCountText: Runs? = null,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Tabs.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Tabs.ktnew file mode 100644index 0000000..7b036a4--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Tabs.kt@@ -0,0 +1,26 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Tabs(+ val tabs: List<Tab>,+) {+ @Serializable+ data class Tab(+ val tabRenderer: TabRenderer,+ ) {+ @Serializable+ data class TabRenderer(+ val title: String?,+ val content: Content?,+ val endpoint: NavigationEndpoint?,+ ) {+ @Serializable+ data class Content(+ val sectionListRenderer: SectionListRenderer?,+ val musicQueueRenderer: MusicQueueRenderer?,+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/TasteProfile.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/TasteProfile.ktnew file mode 100644index 0000000..5d60b31--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/TasteProfile.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models++data class TasteArtist(+ val name: String,+ val selectionValue: String,+ val impressionValue: String,+)++data class TasteProfile(+ val artists: Map<String, TasteArtist>,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/ThumbnailRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/ThumbnailRenderer.ktnew file mode 100644index 0000000..6723025--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/ThumbnailRenderer.kt@@ -0,0 +1,30 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class ThumbnailRenderer(+ val musicThumbnailRenderer: MusicThumbnailRenderer?,+ val musicAnimatedThumbnailRenderer: MusicAnimatedThumbnailRenderer?,+ val croppedSquareThumbnailRenderer: MusicThumbnailRenderer?,+) {+ @Serializable+ data class MusicThumbnailRenderer(+ val thumbnail: Thumbnails,+ val thumbnailCrop: String?,+ val thumbnailScale: String?,+ ) {+ fun getThumbnailUrl() = thumbnail.thumbnails.lastOrNull()?.url+ }++ fun getThumbnailUrl(): String? =+ musicThumbnailRenderer?.getThumbnailUrl()+ ?: musicAnimatedThumbnailRenderer?.backupRenderer?.getThumbnailUrl()+ ?: croppedSquareThumbnailRenderer?.getThumbnailUrl()++ @Serializable+ data class MusicAnimatedThumbnailRenderer(+ val animatedThumbnail: Thumbnails,+ val backupRenderer: MusicThumbnailRenderer,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/Thumbnails.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/Thumbnails.ktnew file mode 100644index 0000000..ef2011d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/Thumbnails.kt@@ -0,0 +1,15 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class Thumbnails(+ val thumbnails: List<Thumbnail>,+)++@Serializable+data class Thumbnail(+ val url: String,+ val width: Int?,+ val height: Int?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/TwoColumnBrowseResultsRenderer.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/TwoColumnBrowseResultsRenderer.ktnew file mode 100644index 0000000..9ea121b--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/TwoColumnBrowseResultsRenderer.kt@@ -0,0 +1,26 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class TwoColumnBrowseResultsRenderer(+ val secondaryContents: SecondaryContents?,+ val tabs: List<Tabs.Tab>?+) {+ @Serializable+ data class SecondaryContents(+ val sectionListRenderer: SectionListRenderer?+ )++ @Serializable+ data class SectionListRenderer(+ val contents: List<Content>?,+ val continuations: List<Continuation>?,+ ) {+ @Serializable+ data class Content(+ val musicPlaylistShelfRenderer: MusicPlaylistShelfRenderer?,+ val musicShelfRenderer: MusicShelfRenderer?+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/UrlEndpoint.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/UrlEndpoint.ktnew file mode 100644index 0000000..893ed80--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/UrlEndpoint.kt@@ -0,0 +1,9 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class UrlEndpoint(+ val url: String? = null,+ val target: String? = null,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YTItem.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YTItem.ktnew file mode 100644index 0000000..c917056--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YTItem.kt@@ -0,0 +1,182 @@+package com.metrolist.innertube.models++import com.metrolist.innertube.models.WatchEndpoint.WatchEndpointMusicSupportedConfigs.WatchEndpointMusicConfig.Companion.MUSIC_VIDEO_TYPE_ATV++sealed class YTItem {+ abstract val id: String+ abstract val title: String+ abstract val thumbnail: String?+ abstract val explicit: Boolean+ abstract val shareLink: String+}++data class Artist(+ val name: String,+ val id: String?,+)++data class Album(+ val name: String,+ val id: String,+)++data class SongItem(+ override val id: String,+ override val title: String,+ val artists: List<Artist>,+ val album: Album? = null,+ val duration: Int? = null,+ val musicVideoType: String? = null,+ val chartPosition: Int? = null,+ val chartChange: String? = null,+ override val thumbnail: String,+ override val explicit: Boolean = false,+ val endpoint: WatchEndpoint? = null,+ val setVideoId: String? = null,+ val libraryAddToken: String? = null,+ val libraryRemoveToken: String? = null,+ val historyRemoveToken: String? = null,+ val isEpisode: Boolean = false,+ val uploadEntityId: String? = null+) : YTItem() {+ val isVideoSong: Boolean+ get() = musicVideoType != null && musicVideoType != MUSIC_VIDEO_TYPE_ATV++ override val shareLink: String+ get() = "https://music.youtube.com/watch?v=$id"+}++data class AlbumItem(+ val browseId: String,+ val playlistId: String,+ override val id: String = browseId,+ override val title: String,+ val artists: List<Artist>?,+ val year: Int? = null,+ override val thumbnail: String,+ override val explicit: Boolean = false,+) : YTItem() {+ override val shareLink: String+ get() = "https://music.youtube.com/playlist?list=$playlistId"+}++data class PlaylistItem(+ override val id: String,+ override val title: String,+ val author: Artist?,+ val songCountText: String?,+ override val thumbnail: String?,+ val playEndpoint: WatchEndpoint?,+ val shuffleEndpoint: WatchEndpoint?,+ val radioEndpoint: WatchEndpoint?,+ val isEditable: Boolean = false,+ val isPodcast: Boolean = false,+ val description: String? = null,+ val authorAvatarUrl: String? = null,+) : YTItem() {+ override val explicit: Boolean+ get() = false+ override val shareLink: String+ get() = "https://music.youtube.com/playlist?list=$id"+}++data class ArtistItem(+ override val id: String,+ override val title: String,+ override val thumbnail: String?,+ val channelId: String? = null,+ val playEndpoint: WatchEndpoint? = null,+ val shuffleEndpoint: WatchEndpoint?,+ val radioEndpoint: WatchEndpoint?,+ val isProfile: Boolean = false,+) : YTItem() {+ override val explicit: Boolean+ get() = false+ override val shareLink: String+ get() = "https://music.youtube.com/channel/$id"+}++data class PodcastItem(+ override val id: String,+ override val title: String,+ val author: Artist?,+ val episodeCountText: String?,+ override val thumbnail: String?,+ val playEndpoint: WatchEndpoint?,+ val shuffleEndpoint: WatchEndpoint?,+ val libraryAddToken: String? = null,+ val libraryRemoveToken: String? = null,+ val channelId: String? = null,+) : YTItem() {+ override val explicit: Boolean+ get() = false+ override val shareLink: String+ get() = "https://music.youtube.com/playlist?list=$id"++ fun asPlaylistItem() = PlaylistItem(+ id = id,+ title = title,+ author = author,+ songCountText = episodeCountText,+ thumbnail = thumbnail,+ playEndpoint = playEndpoint,+ shuffleEndpoint = shuffleEndpoint,+ radioEndpoint = null,+ isEditable = false,+ isPodcast = true+ )+}++data class EpisodeItem(+ override val id: String,+ override val title: String,+ val author: Artist?,+ val podcast: Album? = null,+ val duration: Int? = null,+ val publishDateText: String? = null,+ override val thumbnail: String,+ override val explicit: Boolean = false,+ val endpoint: WatchEndpoint? = null,+ val libraryAddToken: String? = null,+ val libraryRemoveToken: String? = null,+ val markAsPlayedToken: String? = null,+ val markAsUnplayedToken: String? = null,+) : YTItem() {+ override val shareLink: String+ get() = "https://music.youtube.com/watch?v=$id"++ fun asSongItem() = SongItem(+ id = id,+ title = title,+ artists = listOfNotNull(author),+ album = podcast,+ duration = duration,+ thumbnail = thumbnail,+ explicit = explicit,+ endpoint = endpoint,+ isEpisode = true,+ libraryAddToken = libraryAddToken,+ libraryRemoveToken = libraryRemoveToken,+ )+}++fun <T : YTItem> List<T>.filterExplicit(enabled: Boolean = true) =+ if (enabled) {+ filter { !it.explicit }+ } else {+ this+ }++fun <T : YTItem> List<T>.filterVideoSongs(disableVideos: Boolean = false) =+ if (disableVideos) {+ filterNot { it is SongItem && it.isVideoSong }+ } else {+ this+ }++fun <T : YTItem> List<T>.filterYoutubeShorts(enabled: Boolean = false) =+ if (enabled) {+ filterNot { it is PlaylistItem && it.id.startsWith("SS") }+ } else {+ this+ }diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.ktnew file mode 100644index 0000000..8f46922--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeClient.kt@@ -0,0 +1,280 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class YouTubeClient(+ val clientName: String,+ val clientVersion: String,+ val clientId: String,+ val userAgent: String,+ val osName: String? = null,+ val osVersion: String? = null,+ val deviceMake: String? = null,+ val deviceModel: String? = null,+ val androidSdkVersion: String? = null,+ val buildId: String? = null,+ val cronetVersion: String? = null,+ val packageName: String? = null,+ val friendlyName: String? = null,+ val loginSupported: Boolean = false,+ val loginRequired: Boolean = false,+ val useSignatureTimestamp: Boolean = false,+ val isEmbedded: Boolean = false,+ val useWebPoTokens: Boolean = false,+ val requirePoToken: Boolean = false,+ val includeUserAgentInContext: Boolean = false,+) {+ fun toContext(locale: YouTubeLocale, visitorData: String?, dataSyncId: String?) = Context(+ thirdParty = if (isEmbedded) Context.ThirdParty(embedUrl = "https://www.reddit.com/") else null,+ client = Context.Client(+ clientName = clientName,+ clientVersion = clientVersion,+ userAgent = if (includeUserAgentInContext) userAgent else null,+ osName = osName,+ osVersion = osVersion,+ deviceMake = deviceMake,+ deviceModel = deviceModel,+ androidSdkVersion = androidSdkVersion,+ gl = locale.gl,+ hl = locale.hl,+ visitorData = visitorData+ ),+ user = Context.User(+ onBehalfOfUser = if (loginSupported) dataSyncId else null+ ),+ )++ companion object {+ const val USER_AGENT_WEB = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0"++ const val ORIGIN_YOUTUBE_MUSIC = "https://music.youtube.com"+ const val REFERER_YOUTUBE_MUSIC = "$ORIGIN_YOUTUBE_MUSIC/"+ const val API_URL_YOUTUBE_MUSIC = "$ORIGIN_YOUTUBE_MUSIC/youtubei/v1/"++ val WEB = YouTubeClient(+ clientName = "WEB",+ clientVersion = "2.20260114.08.00",+ clientId = "1",+ userAgent = USER_AGENT_WEB,+ )++ val WEB_REMIX = YouTubeClient(+ clientName = "WEB_REMIX",+ clientVersion = "1.20260114.03.00",+ clientId = "67",+ userAgent = USER_AGENT_WEB,+ loginSupported = true,+ useSignatureTimestamp = true,+ useWebPoTokens = true,+ )++ val WEB_CREATOR = YouTubeClient(+ clientName = "WEB_CREATOR",+ clientVersion = "1.20260114.05.00",+ clientId = "62",+ userAgent = USER_AGENT_WEB,+ loginSupported = true,+ loginRequired = true,+ useSignatureTimestamp = true,+ useWebPoTokens = true,+ )++ val TVHTML5 = YouTubeClient(+ clientName = "TVHTML5",+ clientVersion = "7.20260114.12.00",+ clientId = "7",+ userAgent = "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Unknown, Unknown)",+ loginSupported = true,+ useSignatureTimestamp = true,+ useWebPoTokens = true,+ includeUserAgentInContext = true,+ )++ val TVHTML5_SIMPLY = YouTubeClient(+ clientName = "TVHTML5_SIMPLY",+ clientVersion = "1.0",+ clientId = "75",+ userAgent = TVHTML5.userAgent,+ useSignatureTimestamp = true,+ useWebPoTokens = true,+ requirePoToken = true,+ )++ /**+ * Embedded player that can bypass age-restriction.+ * Does not require login for age-restricted content.+ */+ val TVHTML5_SIMPLY_EMBEDDED_PLAYER = YouTubeClient(+ clientName = "TVHTML5_SIMPLY_EMBEDDED_PLAYER",+ clientVersion = "2.0",+ clientId = "85",+ userAgent = "Mozilla/5.0 (PlayStation; PlayStation 4/12.02) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15",+ loginSupported = true,+ loginRequired = false,+ useSignatureTimestamp = true,+ isEmbedded = true,+ )++ val IOS = YouTubeClient(+ clientName = "IOS",+ clientVersion = "21.03.1",+ clientId = "5",+ userAgent = "com.google.ios.youtube/21.03.1 (iPhone16,2; U; CPU iOS 18_2 like Mac OS X;)",+ osVersion = "18.2.22C152",+ )++ val MOBILE = YouTubeClient(+ clientName = "ANDROID",+ clientVersion = "21.03.38",+ clientId = "3",+ userAgent = "com.google.android.youtube/21.03.38 (Linux; U; Android 14) gzip",+ loginSupported = true,+ useSignatureTimestamp = true+ )++ /**+ * Video not playable: Paid / Movie / Private / Age-restricted.+ * Note: The 'Authorization' key must be excluded from the header.+ * For some reason, PoToken is not required.+ */+ val ANDROID_NO_SDK = YouTubeClient(+ clientName = "ANDROID",+ clientVersion = "21.03.38",+ clientId = "3",+ userAgent = "com.google.android.youtube/21.03.38 (Linux; U; Android 14) gzip",+ friendlyName = "Android No SDK",+ loginSupported = false,+ useSignatureTimestamp = false+ )++ val ANDROID_VR_NO_AUTH = YouTubeClient(+ clientName = "ANDROID_VR",+ clientVersion = "1.61.48",+ clientId = "28",+ userAgent = "com.google.android.apps.youtube.vr.oculus/1.61.48 (Linux; U; Android 12; en_US; Oculus Quest 3; Build/SQ3A.220605.009.A1; Cronet/132.0.6808.3)",+ loginSupported = false,+ useSignatureTimestamp = false,+ includeUserAgentInContext = true,+ )++ val ANDROID_VR_1_65_10 = YouTubeClient(+ clientName = "ANDROID_VR",+ clientVersion = "1.65.10",+ clientId = "28",+ userAgent = "com.google.android.apps.youtube.vr.oculus/1.65.10 (Linux; U; Android 12L; eureka-user Build/SQ3A.220605.009.A1) gzip",+ osName = "Android",+ osVersion = "12L",+ deviceMake = "Oculus",+ deviceModel = "Quest 3",+ androidSdkVersion = "32",+ friendlyName = "Android VR 1.65",+ loginSupported = false,+ useSignatureTimestamp = false,+ includeUserAgentInContext = true,+ )++ /**+ * Video not playable: Kids / Paid / Movie / Private / Age-restricted.+ * This client can only be used when logged out.+ */+ val ANDROID_VR_1_61_48 = YouTubeClient(+ clientName = "ANDROID_VR",+ clientVersion = "1.61.48",+ clientId = "28",+ userAgent = "com.google.android.apps.youtube.vr.oculus/1.61.48 (Linux; U; Android 12; en_US; Quest 3; Build/SQ3A.220605.009.A1; Cronet/132.0.6808.3)",+ osName = "Android",+ osVersion = "12",+ deviceMake = "Oculus",+ deviceModel = "Quest 3",+ androidSdkVersion = "32",+ buildId = "SQ3A.220605.009.A1",+ cronetVersion = "132.0.6808.3",+ packageName = "com.google.android.apps.youtube.vr.oculus",+ friendlyName = "Android VR 1.61",+ loginSupported = false,+ useSignatureTimestamp = false,+ includeUserAgentInContext = true,+ )++ /**+ * Uses non adaptive bitrate, which fixes audio stuttering with YT Music.+ * Does not use AV1.+ */+ val ANDROID_VR_1_43_32 = YouTubeClient(+ clientName = "ANDROID_VR",+ clientVersion = "1.43.32",+ clientId = "28",+ userAgent = "com.google.android.apps.youtube.vr.oculus/1.43.32 (Linux; U; Android 12; en_US; Quest 3; Build/SQ3A.220605.009.A1; Cronet/107.0.5284.2)",+ osName = "Android",+ osVersion = "12",+ deviceMake = "Oculus",+ deviceModel = "Quest 3",+ androidSdkVersion = "32",+ buildId = "SQ3A.220605.009.A1",+ cronetVersion = "107.0.5284.2",+ packageName = "com.google.android.apps.youtube.vr.oculus",+ friendlyName = "Android VR 1.43",+ loginSupported = false,+ useSignatureTimestamp = false,+ includeUserAgentInContext = true,+ )++ /**+ * Cannot play livestreams and lacks HDR, but can play videos with music and labeled "for children".+ */+ val ANDROID_CREATOR = YouTubeClient(+ clientName = "ANDROID_CREATOR",+ clientVersion = "25.03.101",+ clientId = "14",+ userAgent = "com.google.android.apps.youtube.creator/25.03.101 (Linux; U; Android 15; en_US; Pixel 9 Pro Fold; Build/AP3A.241005.015.A2; Cronet/132.0.6779.0)",+ osName = "Android",+ osVersion = "15",+ deviceMake = "Google",+ deviceModel = "Pixel 9 Pro Fold",+ androidSdkVersion = "35",+ buildId = "AP3A.241005.015.A2",+ cronetVersion = "132.0.6779.0",+ packageName = "com.google.android.apps.youtube.creator",+ friendlyName = "Android Studio",+ loginSupported = true,+ useSignatureTimestamp = true+ )++ /**+ * Internal YT client for an unreleased YT client. May stop working at any time.+ */+ val VISIONOS = YouTubeClient(+ clientName = "VISIONOS",+ clientVersion = "0.1",+ clientId = "101",+ userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",+ osName = "visionOS",+ osVersion = "1.3.21O771",+ deviceMake = "Apple",+ deviceModel = "RealityDevice14,1",+ friendlyName = "visionOS",+ loginSupported = false,+ useSignatureTimestamp = false+ )++ /**+ * The device machine id for the iPad 6th Gen (iPad7,6).+ * AV1 hardware decoding is not supported.+ */+ val IPADOS = YouTubeClient(+ clientName = "IOS",+ clientVersion = "21.03.3",+ clientId = "5",+ userAgent = "com.google.ios.youtube/21.03.3 (iPad7,6; U; CPU iPadOS 17_7_10 like Mac OS X; en-US)",+ osName = "iPadOS",+ osVersion = "17.7.10.21H450",+ deviceMake = "Apple",+ deviceModel = "iPad7,6",+ friendlyName = "iPadOS",+ loginSupported = false,+ useSignatureTimestamp = false,+ packageName = "com.google.ios.youtube"+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeDataPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeDataPage.ktnew file mode 100644index 0000000..cc82f5f--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeDataPage.kt@@ -0,0 +1,183 @@+package com.metrolist.innertube.models+++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++@Serializable+data class YouTubeDataPage(+ @SerialName("contents")+ val contents: Contents? = null,+) {+ @Serializable+ data class Contents(+ @SerialName("twoColumnWatchNextResults")+ val twoColumnWatchNextResults: TwoColumnWatchNextResults? = null,+ ) {+ @Serializable+ data class TwoColumnWatchNextResults(+ @SerialName("results")+ val results: Results? = null,+ ) {+ @Serializable+ data class Results(+ @SerialName("results")+ val results: Results? = null,+ ) {+ @Serializable+ data class Results(+ @SerialName("contents")+ val content: List<Content?>? = null,+ ) {+ @Serializable+ data class Content(+ @SerialName("videoPrimaryInfoRenderer")+ val videoPrimaryInfoRenderer: VideoPrimaryInfoRenderer? = null,+ @SerialName("videoSecondaryInfoRenderer")+ val videoSecondaryInfoRenderer: VideoSecondaryInfoRenderer? = null,+ @SerialName("itemSectionRenderer")+ val itemSectionRenderer: ItemSectionRenderer? = null,+ ) {+ @Serializable+ data class ItemSectionRenderer(+ @SerialName("contents")+ val contents: List<Content?>? = null,+ ) {+ @Serializable+ data class Content(+ @SerialName("continuationItemRenderer")+ val continuationItemRenderer: ContinuationItemRenderer? = null,+ ) {+ @Serializable+ data class ContinuationItemRenderer(+ @SerialName("trigger")+ val trigger: String? = null,+ @SerialName("continuationEndpoint")+ val continuationEndpoint: ContinuationEndpoint? = null,+ ) {+ @Serializable+ data class ContinuationEndpoint(+ @SerialName("clickTrackingParams")+ val clickTrackingParams: String? = null,+ @SerialName("continuationCommand")+ val continuationCommand: ContinuationCommand? = null,+ ) {+ @Serializable+ data class ContinuationCommand(+ @SerialName("token")+ val token: String? = null,+ @SerialName("request")+ val request: String? = null,+ )+ }+ }+ }+ }++ @Serializable+ data class VideoPrimaryInfoRenderer(+ @SerialName("title")+ val title: Title? = null,+ @SerialName("viewCount")+ val viewCount: ViewCount? = null,+ @SerialName("dateText")+ val dateText: DateText? = null,+ ) {+ @Serializable+ data class Title(+ @SerialName("runs")+ val runs: List<Run>? = null,+ ) {+ @Serializable+ data class Run(+ @SerialName("text")+ val text: String? = null,+ )+ }++ @Serializable+ data class ViewCount(+ @SerialName("videoViewCountRenderer")+ val videoViewCountRenderer: VideoViewCountRenderer? = null,+ ) {+ @Serializable+ data class VideoViewCountRenderer(+ @SerialName("viewCount")+ val viewCount: VideoViewCountRenderer.ViewCount? = null,+ ) {+ @Serializable+ data class ViewCount(+ @SerialName("simpleText")+ val simpleText: String? = null,+ )+ }+ }++ @Serializable+ data class DateText(+ @SerialName("simpleText")+ val simpleText: String? = null,+ )+ }++ @Serializable+ data class VideoSecondaryInfoRenderer(+ @SerialName("owner")+ val owner: Owner? = null,+ @SerialName("attributedDescription")+ val attributedDescription: AttributedDescription? = null,+ ) {+ @Serializable+ data class AttributedDescription(+ @SerialName("content")+ val content: String? = null,+ )++ @Serializable+ data class Owner(+ @SerialName("videoOwnerRenderer")+ val videoOwnerRenderer: VideoOwnerRenderer? = null,+ ) {+ @Serializable+ data class VideoOwnerRenderer(+ @SerialName("thumbnail")+ val thumbnail: Thumbnail? = null,+ @SerialName("subscriberCountText")+ val subscriberCountText: SubscriberCountText? = null,+ @SerialName("title")+ val title: Title? = null,+ @SerialName("navigationEndpoint")+ val navigationEndpoint: NavigationEndpoint? = null,+ ) {+ @Serializable+ data class Thumbnail(+ @SerialName("thumbnails")+ val thumbnails: List<com.metrolist.innertube.models.Thumbnail>? = null,+ )++ @Serializable+ data class SubscriberCountText(+ @SerialName("simpleText")+ val simpleText: String? = null,+ )++ @Serializable+ data class Title(+ @SerialName("runs")+ val runs: List<Run>? = null,+ ) {+ @Serializable+ data class Run(+ @SerialName("text")+ val text: String? = null,+ )+ }+ }+ }+ }+ }+ }+ }+ }+ }+}\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeLocale.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeLocale.ktnew file mode 100644index 0000000..a48fb96--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/YouTubeLocale.kt@@ -0,0 +1,9 @@+package com.metrolist.innertube.models++import kotlinx.serialization.Serializable++@Serializable+data class YouTubeLocale(+ val gl: String, // geolocation+ val hl: String, // host language+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/AccountMenuBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/AccountMenuBody.ktnew file mode 100644index 0000000..11e0277--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/AccountMenuBody.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class AccountMenuBody(+ val context: Context,+ val deviceTheme: String = "DEVICE_THEME_SELECTED",+ val userInterfaceTheme: String = "USER_INTERFACE_THEME_DARK",+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/BrowseBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/BrowseBody.ktnew file mode 100644index 0000000..38f259d--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/BrowseBody.kt@@ -0,0 +1,13 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import com.metrolist.innertube.models.Continuation+import kotlinx.serialization.Serializable++@Serializable+data class BrowseBody(+ val context: Context,+ val browseId: String?,+ val params: String?,+ val continuation: String?+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/CreatePlaylistBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/CreatePlaylistBody.ktnew file mode 100644index 0000000..13702a2--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/CreatePlaylistBody.kt@@ -0,0 +1,18 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class CreatePlaylistBody(+ val context: Context,+ val title: String,+ val privacyStatus: String = PrivacyStatus.PRIVATE,+ val videoIds: List<String>? = null+) {+ object PrivacyStatus {+ const val PRIVATE = "PRIVATE"+ const val PUBLIC = "PUBLIC"+ const val UNLISTED = "UNLISTED"+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/EditPlaylistBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/EditPlaylistBody.ktnew file mode 100644index 0000000..de7491a--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/EditPlaylistBody.kt@@ -0,0 +1,79 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class EditPlaylistBody(+ val context: Context,+ val playlistId: String,+ val actions: List<Action>+)++@Serializable+sealed class Action {+ @Serializable+ data class AddVideoAction(+ val action: String = "ACTION_ADD_VIDEO",+ val addedVideoId: String+ ) : Action()++ @Serializable+ data class AddPlaylistAction(+ val action: String = "ACTION_ADD_PLAYLIST",+ val addedFullListId: String+ ) : Action()++ @Serializable+ data class MoveVideoAction(+ val action: String = "ACTION_MOVE_VIDEO_BEFORE",+ val setVideoId: String,+ val movedSetVideoIdSuccessor: String?+ ) : Action()++ @Serializable+ data class RemoveVideoAction(+ val action: String = "ACTION_REMOVE_VIDEO",+ val setVideoId: String,+ val removedVideoId: String+ ) : Action()++ @Serializable+ data class RenamePlaylistAction(+ val action: String = "ACTION_SET_PLAYLIST_NAME",+ val playlistName: String+ ) : Action()++ @Serializable+ data class SetCustomThumbnailAction(+ val action: String = "ACTION_SET_CUSTOM_THUMBNAIL",+ val addedCustomThumbnail: AddedCustomThumbnail+ ) : Action() {+ @Serializable+ data class AddedCustomThumbnail(+ val imageKey: ImageKey = ImageKey(+ name = "studio_square_thumbnail",+ type = "PLAYLIST_IMAGE_TYPE_CUSTOM_THUMBNAIL"+ ),+ val playlistScottyEncryptedBlobId: String+ ) {+ @Serializable+ data class ImageKey(+ val name: String,+ val type: String+ )+ }+ }++ @Serializable+ data class RemoveCustomThumbnailAction(+ val action: String = "ACTION_REMOVE_CUSTOM_THUMBNAIL",+ val deletedCustomThumbnail: DeletedCustomThumbnail = DeletedCustomThumbnail()+ ) : Action() {+ @Serializable+ data class DeletedCustomThumbnail(+ val name: String = "studio_square_thumbnail",+ val type: String = "PLAYLIST_IMAGE_TYPE_CUSTOM_THUMBNAIL"+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/FeedbackBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/FeedbackBody.ktnew file mode 100644index 0000000..07f673f--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/FeedbackBody.kt@@ -0,0 +1,12 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class FeedbackBody(+ val context: Context,+ val feedbackTokens: List<String>,+ val isFeedbackTokenUnencrypted: Boolean = false,+ val shouldMerge: Boolean = false,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetQueueBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetQueueBody.ktnew file mode 100644index 0000000..ade3dbb--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetQueueBody.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class GetQueueBody(+ val context: Context,+ val videoIds: List<String>?,+ val playlistId: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetSearchSuggestionsBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetSearchSuggestionsBody.ktnew file mode 100644index 0000000..b2b31ea--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetSearchSuggestionsBody.kt@@ -0,0 +1,10 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class GetSearchSuggestionsBody(+ val context: Context,+ val input: String,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetTranscriptBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetTranscriptBody.ktnew file mode 100644index 0000000..5b38935--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/GetTranscriptBody.kt@@ -0,0 +1,10 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class GetTranscriptBody(+ val context: Context,+ val params: String,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/LikeBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/LikeBody.ktnew file mode 100644index 0000000..e8892fb--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/LikeBody.kt@@ -0,0 +1,26 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class LikeBody(+ val context: Context,+ val target: Target,+) {+ /**+ * Target for like/unlike operations.+ * Note: Only one of videoId or playlistId should be set.+ * Using a flat structure instead of sealed class to avoid type discriminator in serialization.+ */+ @Serializable+ data class Target(+ val videoId: String? = null,+ val playlistId: String? = null,+ ) {+ companion object {+ fun video(id: String) = Target(videoId = id)+ fun playlist(id: String) = Target(playlistId = id)+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/NextBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/NextBody.ktnew file mode 100644index 0000000..f746b74--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/NextBody.kt@@ -0,0 +1,15 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class NextBody(+ val context: Context,+ val videoId: String?,+ val playlistId: String?,+ val playlistSetVideoId: String?,+ val index: Int?,+ val params: String?,+ val continuation: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/PlayerBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/PlayerBody.ktnew file mode 100644index 0000000..f5b9596--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/PlayerBody.kt@@ -0,0 +1,30 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class PlayerBody(+ val context: Context,+ val videoId: String,+ val playlistId: String?,+ val playbackContext: PlaybackContext? = null,+ val serviceIntegrityDimensions: ServiceIntegrityDimensions? = null,+ val contentCheckOk: Boolean = true,+ val racyCheckOk: Boolean = true,+) {+ @Serializable+ data class PlaybackContext(+ val contentPlaybackContext: ContentPlaybackContext+ ) {+ @Serializable+ data class ContentPlaybackContext(+ val signatureTimestamp: Int+ )+ }++ @Serializable+ data class ServiceIntegrityDimensions(+ val poToken: String+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SearchBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SearchBody.ktnew file mode 100644index 0000000..16c2afd--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SearchBody.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class SearchBody(+ val context: Context,+ val query: String?,+ val params: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SubscribeBody.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SubscribeBody.ktnew file mode 100644index 0000000..92fb03e--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/body/SubscribeBody.kt@@ -0,0 +1,11 @@+package com.metrolist.innertube.models.body++import com.metrolist.innertube.models.Context+import kotlinx.serialization.Serializable++@Serializable+data class SubscribeBody(+ val channelIds: List<String>,+ val context: Context,+ val params: String? = null,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountMenuResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountMenuResponse.ktnew file mode 100644index 0000000..2aac2c8--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AccountMenuResponse.kt@@ -0,0 +1,53 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.AccountInfo+import com.metrolist.innertube.models.Runs+import com.metrolist.innertube.models.Thumbnails+import com.metrolist.innertube.models.Thumbnail+import kotlinx.serialization.Serializable++@Serializable+data class AccountMenuResponse(+ val actions: List<Action>,+) {+ @Serializable+ data class Action(+ val openPopupAction: OpenPopupAction,+ ) {+ @Serializable+ data class OpenPopupAction(+ val popup: Popup,+ ) {+ @Serializable+ data class Popup(+ val multiPageMenuRenderer: MultiPageMenuRenderer,+ ) {+ @Serializable+ data class MultiPageMenuRenderer(+ val header: Header?,+ ) {+ @Serializable+ data class Header(+ val activeAccountHeaderRenderer: ActiveAccountHeaderRenderer,+ ) {+ @Serializable+ data class ActiveAccountHeaderRenderer(+ val accountName: Runs,+ val email: Runs?,+ val channelHandle: Runs?,+ val accountPhoto: Thumbnails,+ ) {+ fun toAccountInfo() =+ AccountInfo(+ name = accountName.runs!!.first().text,+ email = email?.runs?.first()?.text,+ channelHandle = channelHandle?.runs?.first()?.text,+ thumbnailUrl = accountPhoto.thumbnails.lastOrNull()?.url,+ )+ }+ }+ }+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AddItemYouTubePlaylistResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AddItemYouTubePlaylistResponse.ktnew file mode 100644index 0000000..38fc5b9--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/AddItemYouTubePlaylistResponse.kt@@ -0,0 +1,20 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class AddItemYouTubePlaylistResponse(+ val status: String,+ val playlistEditResults: List<PlaylistEditResult>+) {+ @Serializable+ data class PlaylistEditResult(+ val playlistEditVideoAddedResultData: PlaylistEditVideoAddedResultData,+ ) {+ @Serializable+ data class PlaylistEditVideoAddedResultData(+ val setVideoId: String,+ val videoId: String+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/BrowseResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/BrowseResponse.ktnew file mode 100644index 0000000..c67c338--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/BrowseResponse.kt@@ -0,0 +1,155 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.Button+import com.metrolist.innertube.models.Continuation+import com.metrolist.innertube.models.GridRenderer+import com.metrolist.innertube.models.Menu+import com.metrolist.innertube.models.MusicDetailHeaderRenderer+import com.metrolist.innertube.models.MusicEditablePlaylistDetailHeaderRenderer+import com.metrolist.innertube.models.MusicShelfRenderer+import com.metrolist.innertube.models.ResponseContext+import com.metrolist.innertube.models.Runs+import com.metrolist.innertube.models.SectionListRenderer+import com.metrolist.innertube.models.SubscriptionButton+import com.metrolist.innertube.models.Tabs+import com.metrolist.innertube.models.ThumbnailRenderer+import kotlinx.serialization.Serializable++@Serializable+data class BrowseResponse(+ val contents: Contents?,+ val continuationContents: ContinuationContents?,+ val onResponseReceivedActions: List<ResponseAction>?,+ val header: Header?,+ val microformat: Microformat?,+ val responseContext: ResponseContext,+ val background: ThumbnailRenderer?+) {+ @Serializable+ data class Contents(+ val singleColumnBrowseResultsRenderer: Tabs?,+ val sectionListRenderer: SectionListRenderer?,+ val twoColumnBrowseResultsRenderer: TwoColumnBrowseResultsRenderer?,+ )++ @Serializable+ data class TwoColumnBrowseResultsRenderer(+ val tabs: List<Tabs.Tab?>?,+ val secondaryContents: SecondaryContents?,+ )+ @Serializable+ data class SecondaryContents(+ val sectionListRenderer: SectionListRenderer?,+ )++ @Serializable+ data class ContinuationContents(+ val sectionListContinuation: SectionListContinuation?,+ val musicPlaylistShelfContinuation: MusicPlaylistShelfContinuation?,+ val gridContinuation: GridContinuation?,+ val musicShelfContinuation: MusicShelfRenderer?+ ) {+ @Serializable+ data class SectionListContinuation(+ val contents: List<SectionListRenderer.Content> = emptyList(),+ val continuations: List<Continuation>?,+ )++ @Serializable+ data class MusicPlaylistShelfContinuation(+ val contents: List<MusicShelfRenderer.Content> = emptyList(),+ val continuations: List<Continuation>?,+ )++ @Serializable+ data class GridContinuation(+ val items: List<GridRenderer.Item> = emptyList(),+ val continuations: List<Continuation>?,+ )+ }++ @Serializable+ data class ResponseAction(+ val appendContinuationItemsAction: ContinuationItems?,+ ) {+ @Serializable+ data class ContinuationItems(+ val continuationItems: List<MusicShelfRenderer.Content>?,+ )+ }++ @Serializable+ data class Header(+ val musicImmersiveHeaderRenderer: MusicImmersiveHeaderRenderer?,+ val musicDetailHeaderRenderer: MusicDetailHeaderRenderer?,+ val musicEditablePlaylistDetailHeaderRenderer: MusicEditablePlaylistDetailHeaderRenderer?,+ val musicVisualHeaderRenderer: MusicVisualHeaderRenderer?,+ val musicHeaderRenderer: MusicHeaderRenderer?,+ ) {+ @Serializable+ data class MusicImmersiveHeaderRenderer(+ val title: Runs,+ val description: Runs?,+ val thumbnail: ThumbnailRenderer?,+ val playButton: Button?,+ val startRadioButton: Button?,+ val subscriptionButton: SubscriptionButton?,+ val menu: Menu,+ val subscriptionButton2: SubscriptionButton2?,+ val monthlyListenerCount: Runs? = null,+ ) {+ @Serializable+ data class SubscriptionButton2(+ val subscribeButtonRenderer: SubscribeButtonRenderer?,+ ) {+ @Serializable+ data class SubscribeButtonRenderer(+ val subscriberCountWithSubscribeText: Runs?,+ )+ }+ }++ @Serializable+ data class MusicVisualHeaderRenderer(+ val title: Runs,+ val foregroundThumbnail: ThumbnailRenderer,+ val thumbnail: ThumbnailRenderer?,+ val subscriptionButton: SubscriptionButton?,+ )++ @Serializable+ data class Buttons(+ val menuRenderer: Menu.MenuRenderer?,+ )++ @Serializable+ data class MusicHeaderRenderer(+ val buttons: List<Buttons>?,+ val title: Runs?,+ val thumbnail: MusicThumbnailRenderer?,+ val subtitle: Runs?,+ val secondSubtitle: Runs?,+ val straplineTextOne: Runs?,+ val straplineThumbnail: MusicThumbnailRenderer?,+ )+ @Serializable+ data class MusicThumbnail(+ val url: String?,+ )+ @Serializable+ data class MusicThumbnailRenderer(+ val musicThumbnailRenderer: MusicThumbnailRenderer,+ val thumbnails: List<MusicThumbnail>?,+ )+ }++ @Serializable+ data class Microformat(+ val microformatDataRenderer: MicroformatDataRenderer?,+ ) {+ @Serializable+ data class MicroformatDataRenderer(+ val urlCanonical: String?,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ContinuationResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ContinuationResponse.ktnew file mode 100644index 0000000..782cb89--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ContinuationResponse.kt@@ -0,0 +1,20 @@+package com.metrolist.innertube.models.response++ import com.metrolist.innertube.models.MusicShelfRenderer+ import kotlinx.serialization.Serializable++ @Serializable+ data class ContinuationResponse(+ val onResponseReceivedActions: List<ResponseAction>?,+ ) {++ @Serializable+ data class ResponseAction(+ val appendContinuationItemsAction: ContinuationItems?,+ )++ @Serializable+ data class ContinuationItems(+ val continuationItems: List<MusicShelfRenderer.Content>?,+ )+ }diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/CreatePlaylistResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/CreatePlaylistResponse.ktnew file mode 100644index 0000000..e1f500c--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/CreatePlaylistResponse.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class CreatePlaylistResponse(+ val playlistId: String+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/EditPlaylistResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/EditPlaylistResponse.ktnew file mode 100644index 0000000..759bfd4--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/EditPlaylistResponse.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class EditPlaylistResponse(+ val newHeader: BrowseResponse.Header?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/FeedbackResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/FeedbackResponse.ktnew file mode 100644index 0000000..c78e5b3--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/FeedbackResponse.kt@@ -0,0 +1,13 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class FeedbackResponse(+ val feedbackResponses: List<Status>,+) {+ @Serializable+ data class Status(+ val isProcessed: Boolean,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetQueueResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetQueueResponse.ktnew file mode 100644index 0000000..bb37782--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetQueueResponse.kt@@ -0,0 +1,14 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.PlaylistPanelRenderer+import kotlinx.serialization.Serializable++@Serializable+data class GetQueueResponse(+ val queueDatas: List<QueueData>,+) {+ @Serializable+ data class QueueData(+ val content: PlaylistPanelRenderer.Content,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetSearchSuggestionsResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetSearchSuggestionsResponse.ktnew file mode 100644index 0000000..ee87d69--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetSearchSuggestionsResponse.kt@@ -0,0 +1,14 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.SearchSuggestionsSectionRenderer+import kotlinx.serialization.Serializable++@Serializable+data class GetSearchSuggestionsResponse(+ val contents: List<Content>?,+) {+ @Serializable+ data class Content(+ val searchSuggestionsSectionRenderer: SearchSuggestionsSectionRenderer,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetTranscriptResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetTranscriptResponse.ktnew file mode 100644index 0000000..b26d66c--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/GetTranscriptResponse.kt@@ -0,0 +1,65 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class GetTranscriptResponse(+ val actions: List<Action>?,+) {+ @Serializable+ data class Action(+ val updateEngagementPanelAction: UpdateEngagementPanelAction,+ ) {+ @Serializable+ data class UpdateEngagementPanelAction(+ val content: Content,+ ) {+ @Serializable+ data class Content(+ val transcriptRenderer: TranscriptRenderer,+ ) {+ @Serializable+ data class TranscriptRenderer(+ val body: Body,+ ) {+ @Serializable+ data class Body(+ val transcriptBodyRenderer: TranscriptBodyRenderer,+ ) {+ @Serializable+ data class TranscriptBodyRenderer(+ val cueGroups: List<CueGroup>,+ ) {+ @Serializable+ data class CueGroup(+ val transcriptCueGroupRenderer: TranscriptCueGroupRenderer,+ ) {+ @Serializable+ data class TranscriptCueGroupRenderer(+ val cues: List<Cue>,+ ) {+ @Serializable+ data class Cue(+ val transcriptCueRenderer: TranscriptCueRenderer,+ ) {+ @Serializable+ data class TranscriptCueRenderer(+ val cue: SimpleText,+ val startOffsetMs: Long,+ val durationMs: Long,+ ) {+ @Serializable+ data class SimpleText(+ val simpleText: String,+ )+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ImageUploadResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ImageUploadResponse.ktnew file mode 100644index 0000000..2ed417f--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/ImageUploadResponse.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.models.response++import kotlinx.serialization.Serializable++@Serializable+data class ImageUploadResponse(+ val encryptedBlobId: String+)\ No newline at end of filediff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/NextResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/NextResponse.ktnew file mode 100644index 0000000..a57aa3a--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/NextResponse.kt@@ -0,0 +1,40 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.NavigationEndpoint+import com.metrolist.innertube.models.PlaylistPanelRenderer+import com.metrolist.innertube.models.Tabs+import com.metrolist.innertube.models.YouTubeDataPage+import kotlinx.serialization.Serializable++@Serializable+data class NextResponse(+ val contents: Contents,+ val continuationContents: ContinuationContents?,+ val currentVideoEndpoint: NavigationEndpoint?,+) {+ @Serializable+ data class Contents(+ val singleColumnMusicWatchNextResultsRenderer: SingleColumnMusicWatchNextResultsRenderer?,+ val twoColumnWatchNextResults: YouTubeDataPage.Contents.TwoColumnWatchNextResults?,+ ) {+ @Serializable+ data class SingleColumnMusicWatchNextResultsRenderer(+ val tabbedRenderer: TabbedRenderer?,+ ) {+ @Serializable+ data class TabbedRenderer(+ val watchNextTabbedResultsRenderer: WatchNextTabbedResultsRenderer?,+ ) {+ @Serializable+ data class WatchNextTabbedResultsRenderer(+ val tabs: List<Tabs.Tab>,+ )+ }+ }+ }++ @Serializable+ data class ContinuationContents(+ val playlistPanelContinuation: PlaylistPanelRenderer,+ )+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/PlayerResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/PlayerResponse.ktnew file mode 100644index 0000000..a9c10c1--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/PlayerResponse.kt@@ -0,0 +1,118 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.ResponseContext+import com.metrolist.innertube.models.Thumbnails+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * PlayerResponse with [com.metrolist.innertube.models.YouTubeClient.WEB_REMIX] client+ */+@Serializable+data class PlayerResponse(+ val responseContext: ResponseContext,+ val playabilityStatus: PlayabilityStatus,+ val playerConfig: PlayerConfig?,+ val streamingData: StreamingData?,+ val videoDetails: VideoDetails?,+ @SerialName("playbackTracking")+ val playbackTracking: PlaybackTracking?,+) {+ @Serializable+ data class PlayabilityStatus(+ val status: String,+ val reason: String?,+ )++ @Serializable+ data class PlayerConfig(+ val audioConfig: AudioConfig,+ ) {+ @Serializable+ data class AudioConfig(+ val loudnessDb: Double?,+ val perceptualLoudnessDb: Double?,+ )+ }++ @Serializable+ data class StreamingData(+ val formats: List<Format>?,+ val adaptiveFormats: List<Format>,+ val expiresInSeconds: Int,+ ) {+ @Serializable+ data class Format(+ val itag: Int,+ val url: String?,+ val mimeType: String,+ val bitrate: Int,+ val width: Int?,+ val height: Int?,+ val contentLength: Long?,+ val quality: String,+ val fps: Int?,+ val qualityLabel: String?,+ val averageBitrate: Int?,+ val audioQuality: String?,+ val approxDurationMs: String?,+ val audioSampleRate: Int?,+ val audioChannels: Int?,+ val loudnessDb: Double?,+ val lastModified: Long?,+ val signatureCipher: String?,+ val cipher: String?,+ val audioTrack: AudioTrack?+ ) {+ val isAudio: Boolean+ get() = width == null+ val isOriginal: Boolean+ get() = audioTrack?.isAutoDubbed == null++ @Serializable+ data class AudioTrack(+ val displayName: String?,+ val id: String?,+ val isAutoDubbed: Boolean?,+ )+ }+ }++ @Serializable+ data class VideoDetails(+ val videoId: String,+ val title: String?,+ val author: String?,+ val channelId: String,+ val lengthSeconds: String,+ val musicVideoType: String?,+ val viewCount: String?,+ val thumbnail: Thumbnails,+ )++ @Serializable+ data class PlaybackTracking(+ @SerialName("videostatsPlaybackUrl")+ val videostatsPlaybackUrl: VideostatsPlaybackUrl?,+ @SerialName("videostatsWatchtimeUrl")+ val videostatsWatchtimeUrl: VideostatsWatchtimeUrl?,+ @SerialName("atrUrl")+ val atrUrl: AtrUrl?,+ ) {+ @Serializable+ data class VideostatsPlaybackUrl(+ @SerialName("baseUrl")+ val baseUrl: String?,+ )+ @Serializable+ data class VideostatsWatchtimeUrl(+ @SerialName("baseUrl")+ val baseUrl: String?,+ )+ @Serializable+ data class AtrUrl(+ @SerialName("baseUrl")+ val baseUrl: String?,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/models/response/SearchResponse.kt b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/SearchResponse.ktnew file mode 100644index 0000000..8eca5b2--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/models/response/SearchResponse.kt@@ -0,0 +1,33 @@+package com.metrolist.innertube.models.response++import com.metrolist.innertube.models.Continuation+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.Tabs+import kotlinx.serialization.Serializable++@Serializable+data class SearchResponse(+ val contents: Contents?,+ val continuationContents: ContinuationContents?,+) {+ @Serializable+ data class Contents(+ val tabbedSearchResultsRenderer: Tabs?,+ )++ @Serializable+ data class ContinuationContents(+ val musicShelfContinuation: MusicShelfContinuation,+ ) {+ @Serializable+ data class MusicShelfContinuation(+ val contents: List<Content>,+ val continuations: List<Continuation>?,+ ) {+ @Serializable+ data class Content(+ val musicResponsiveListItemRenderer: MusicResponsiveListItemRenderer,+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/AlbumPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/AlbumPage.ktnew file mode 100644index 0000000..ad1c649--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/AlbumPage.kt@@ -0,0 +1,138 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.MusicResponsiveHeaderRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.getItems+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.response.BrowseResponse+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class AlbumPage(+ val album: AlbumItem,+ val songs: List<SongItem>,+ val otherVersions: List<AlbumItem>,+) {+ companion object {+ fun getPlaylistId(response: BrowseResponse): String? {+ var playlistId = response.microformat?.microformatDataRenderer?.urlCanonical?.substringAfterLast('=')+ if (playlistId == null)+ {+ playlistId = response.header?.musicDetailHeaderRenderer?.menu?.menuRenderer?.topLevelButtons?.firstOrNull()+ ?.buttonRenderer?.navigationEndpoint?.watchPlaylistEndpoint?.playlistId+ }+ return playlistId+ }++ fun getTitle(response: BrowseResponse): String? {+ val title = getHeader(response)?.title ?: response.header?.musicDetailHeaderRenderer?.title+ return title?.runs?.firstOrNull()?.text+ }++ fun getYear(response: BrowseResponse): Int? {+ val title = getHeader(response)?.subtitle ?: response.header?.musicDetailHeaderRenderer?.subtitle+ return title?.runs?.lastOrNull()?.text?.toIntOrNull()+ }++ fun getThumbnail(response: BrowseResponse): String? {+ return response.background?.getThumbnailUrl() ?: response.header?.musicDetailHeaderRenderer?.thumbnail+ ?.getThumbnailUrl()+ }++ fun getArtists(response: BrowseResponse): List<Artist> {+ val artists = getHeader(response)?.straplineTextOne?.runs?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ } ?: response.header?.musicDetailHeaderRenderer?.subtitle?.runs?.splitBySeparator()?.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ } ?: emptyList()++ return artists+ }++ private fun getHeader(response: BrowseResponse): MusicResponsiveHeaderRenderer? {+ val tabs = response.contents?.singleColumnBrowseResultsRenderer?.tabs+ ?: response.contents?.twoColumnBrowseResultsRenderer?.tabs+ val section =+ tabs?.firstOrNull()?.tabRenderer?.content?.sectionListRenderer?.contents?.firstOrNull()+ val header = section?.musicResponsiveHeaderRenderer+ return header+ }++ fun getSongs(response: BrowseResponse, album: AlbumItem): List<SongItem> {+ val tabs = response.contents?.singleColumnBrowseResultsRenderer?.tabs ?: response.contents?.twoColumnBrowseResultsRenderer?.tabs+ val shelfRenderer = tabs?.firstOrNull()?.tabRenderer?.content?.sectionListRenderer?.contents?.firstOrNull()?.musicShelfRenderer ?:+ response.contents?.twoColumnBrowseResultsRenderer?.secondaryContents?.sectionListRenderer?.contents?.firstOrNull()?.musicShelfRenderer++ val songs = shelfRenderer?.contents?.getItems()?.mapNotNull {+ getSong(it, album)+ }+ return songs ?: emptyList()+ }++ fun getSong(renderer: MusicResponsiveListItemRenderer, album: AlbumItem? = null): SongItem? {+ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return SongItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title = PageHelper.extractRuns(renderer.flexColumns, "MUSIC_VIDEO").firstOrNull()?.text ?: return null,+ artists = PageHelper.extractRuns(renderer.flexColumns, "MUSIC_PAGE_TYPE_ARTIST").map{+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ }.ifEmpty {+ // Label-uploaded albums (e.g. "OLAK5uy_…" art tracks) name the performing+ // artist as a plain-text run with no artist link, while the album header+ // strapline is the record label / distributor channel. Prefer that+ // plain-text artist over inheriting the label as the track artist.+ renderer.flexColumns.getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs+ ?.splitBySeparator()?.firstOrNull()?.oddElements()+ ?.map { Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId) }+ ?.filter { it.name.isNotBlank() }+ ?.takeIf { it.isNotEmpty() }+ // Final fallback: inherit the album artist when the row has no artist at all.+ ?: album?.artists ?: emptyList()+ },+ album = album?.let {+ Album(it.title, it.browseId)+ } ?: renderer.flexColumns.getOrNull(2)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!+ )+ }!!,+ duration = renderer.fixedColumns?.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()+ ?.text?.parseTime() ?: return null,+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: album?.thumbnail!!,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsContinuationPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsContinuationPage.ktnew file mode 100644index 0000000..cbcbb8b--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsContinuationPage.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.YTItem++data class ArtistItemsContinuationPage(+ val items: List<YTItem>,+ val continuation: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsPage.ktnew file mode 100644index 0000000..4846189--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistItemsPage.kt@@ -0,0 +1,159 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.splitArtistsByConjunction+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime+import timber.log.Timber++data class ArtistItemsPage(+ val title: String,+ val items: List<YTItem>,+ val continuation: String?,+) {+ companion object {+ fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ val artistRuns = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ ?.getOrNull(0)+ ?.splitArtistsByConjunction()+ ?.filter { it.text.isNotBlank() && it.text != "&" && it.text != "," }+ ?.map { run ->+ Artist(+ name = run.text.trim(),+ id = run.navigationEndpoint?.browseEndpoint?.browseId+ )+ }++ // Extract album from last flexColumn (like SimpMusic does)+ val album = renderer.flexColumns.lastOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs+ ?.firstOrNull()?.let {+ if (it.navigationEndpoint?.browseEndpoint?.browseId != null) {+ Album(+ name = it.text,+ id = it.navigationEndpoint.browseEndpoint.browseId+ )+ } else null+ }++ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return SongItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()?.text ?: return null,+ artists = artistRuns ?: return null,+ album = album,+ duration = renderer.fixedColumns?.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()+ ?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode+ )+ }++ fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {+ return when {+ renderer.isAlbum -> AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId = renderer.thumbnailOverlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.anyWatchEndpoint?.playlistId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = null,+ year = renderer.subtitle?.runs?.lastOrNull()?.text?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )+ // Video+ renderer.isSong -> {+ val title = renderer.title.runs?.firstOrNull()?.text ?: return null+ val videoId = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null+ val subtitleRuns = renderer.subtitle?.runs ?: return null+ val expandedRuns = subtitleRuns.splitArtistsByConjunction()+ val artistRuns = expandedRuns.filter { run ->+ run.text.isNotBlank() && run.text != "&" && run.text != "," &&+ run.navigationEndpoint?.browseEndpoint?.browseId?.startsWith("UC") == true+ }+ val artists = artistRuns.map { run ->+ Artist(+ name = run.text.trim(),+ id = run.navigationEndpoint?.browseEndpoint?.browseId+ )+ }++ if (artists.isEmpty() && renderer.subtitle?.runs != null) {+ Timber.w("ArtistItemsPage.fromMusicTwoRowItemRenderer: Song '$title' (id=$videoId) - SUBTITLE RUNS EXIST but parsing returned EMPTY")+ }++ SongItem(+ id = videoId,+ title = title,+ artists = artists.ifEmpty { null } ?: return null,+ album = null,+ duration = null,+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ endpoint = renderer.navigationEndpoint.watchEndpoint+ )+ }+ renderer.isPlaylist -> PlaylistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId?.removePrefix("VL") ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ songCountText = renderer.subtitle?.runs?.getOrNull(4)?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null+ )+ else -> null+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.ktnew file mode 100644index 0000000..f336624--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ArtistPage.kt@@ -0,0 +1,279 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.BrowseEndpoint+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicCarouselShelfRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicShelfRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.Run+import com.metrolist.innertube.models.SectionListRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.WatchEndpoint+import com.metrolist.innertube.utils.parseTime+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.filterExplicit+import com.metrolist.innertube.models.getItems+import com.metrolist.innertube.models.splitArtistsByConjunction+import com.metrolist.innertube.models.splitBySeparator++data class ArtistSection(+ val title: String,+ val items: List<YTItem>,+ val moreEndpoint: BrowseEndpoint?,+)++data class ArtistPage(+ val artist: ArtistItem,+ val sections: List<ArtistSection>,+ val description: String?,+ val subscriberCountText: String?,+ val monthlyListenerCount: String? = null,+ val descriptionRuns: List<Run>? = null,+ val isSubscribed: Boolean = false,+) {+ companion object {+ fun fromSectionListRendererContent(content: SectionListRenderer.Content): ArtistSection? {+ return when {+ content.musicShelfRenderer != null -> fromMusicShelfRenderer(content.musicShelfRenderer)+ content.musicCarouselShelfRenderer != null -> fromMusicCarouselShelfRenderer(content.musicCarouselShelfRenderer)+ else -> null+ }+ }++ private fun fromMusicShelfRenderer(renderer: MusicShelfRenderer): ArtistSection? {+ return ArtistSection(+ title = renderer.title?.runs?.firstOrNull()?.text ?: "",+ items = renderer.contents?.getItems()?.mapNotNull {+ fromMusicResponsiveListItemRenderer(it)+ }?.ifEmpty { null } ?: return null,+ moreEndpoint = renderer.title?.runs?.firstOrNull()?.navigationEndpoint?.browseEndpoint+ )+ }++ private fun fromMusicCarouselShelfRenderer(renderer: MusicCarouselShelfRenderer): ArtistSection? {+ return ArtistSection(+ title = renderer.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.firstOrNull()?.text ?: return null,+ items = renderer.contents.mapNotNull { content ->+ content.musicTwoRowItemRenderer?.let { twoRowRenderer ->+ fromMusicTwoRowItemRenderer(twoRowRenderer)+ } ?: content.musicResponsiveListItemRenderer?.let { listItemRenderer ->+ fromMusicResponsiveListItemRenderer(listItemRenderer)+ }+ }.ifEmpty { null } ?: return null,+ moreEndpoint = renderer.header.musicCarouselShelfBasicHeaderRenderer.moreContentButton?.buttonRenderer?.navigationEndpoint?.browseEndpoint+ )+ }++ private fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ val subtitleLine = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs++ val subtitleGroups = subtitleLine?.splitBySeparator()++ val artistRuns = subtitleGroups+ ?.getOrNull(0)+ ?.splitArtistsByConjunction()+ ?.filter { it.text.isNotBlank() && it.text != "&" && it.text != "," }+ ?.map { run ->+ Artist(+ name = run.text.trim(),+ id = run.navigationEndpoint?.browseEndpoint?.browseId+ )+ }++ val album = renderer.flexColumns.lastOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs+ ?.firstOrNull()?.let {+ if (it.navigationEndpoint?.browseEndpoint?.browseId != null) {+ Album(+ name = it.text,+ id = it.navigationEndpoint.browseEndpoint.browseId+ )+ } else null+ }++ // Duration is in the last group after "•" separator in the subtitle line+ val durationFromSubtitle = subtitleGroups+ ?.drop(1)+ ?.firstOrNull { group ->+ group.firstOrNull()?.text?.parseTime() != null+ }+ ?.firstOrNull()+ ?.text+ ?.parseTime()++ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return SongItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()+ ?.text ?: return null,+ artists = artistRuns ?: return null,+ album = album,+ duration = durationFromSubtitle+ ?: renderer.fixedColumns?.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()+ ?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken+ )+ }++ private fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {+ return when {+ renderer.isSong -> {+ val subtitleRuns = renderer.subtitle?.runs ?: return null+ val expandedRuns = subtitleRuns.splitArtistsByConjunction()+ val artistRuns = expandedRuns.filter { run ->+ run.text.isNotBlank() && run.text != "&" && run.text != "," &&+ run.navigationEndpoint?.browseEndpoint?.browseId?.startsWith("UC") == true+ }+ val subtitleGroups = subtitleRuns.splitBySeparator()+ SongItem(+ id = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = artistRuns.map { run ->+ Artist(+ name = run.text.trim(),+ id = run.navigationEndpoint?.browseEndpoint?.browseId+ )+ }.ifEmpty { null } ?: return null,+ album = null,+ duration = subtitleGroups.lastOrNull()+ ?.firstOrNull()+ ?.takeIf { it.navigationEndpoint == null }+ ?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )+ }++ renderer.isAlbum -> {+ AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId = renderer.thumbnailOverlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.anyWatchEndpoint?.playlistId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = null,+ year = renderer.subtitle?.runs?.lastOrNull()?.text?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )+ }++ renderer.isPlaylist -> {+ // Playlist from YouTube Music+ PlaylistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId?.removePrefix("VL") ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = Artist(+ name = renderer.subtitle?.runs?.firstOrNull()?.text ?: return null,+ id = null+ ),+ songCountText = null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null+ )+ }++ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.lastOrNull()?.text ?: return null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ channelId = renderer.menu?.menuRenderer?.items?.find {+ it.toggleMenuServiceItemRenderer?.defaultIcon?.iconType == "SUBSCRIBE"+ }?.toggleMenuServiceItemRenderer?.defaultServiceEndpoint?.subscribeEndpoint?.channelIds?.firstOrNull(),+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ )+ }++ renderer.isEpisode -> {+ val videoId = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchEndpoint?.videoId ?: return null+ EpisodeItem(+ id = videoId,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId)+ },+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ endpoint = WatchEndpoint(videoId = videoId),+ publishDateText = renderer.subtitle?.runs?.lastOrNull()?.text,+ )+ }++ renderer.isPodcast -> {+ PodcastItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(name = it.text, id = it.navigationEndpoint?.browseEndpoint?.browseId)+ },+ episodeCountText = renderer.subtitle?.runs?.lastOrNull()?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl(),+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ )+ }++ else -> null+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/BrowseResult.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/BrowseResult.ktnew file mode 100644index 0000000..fca5555--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/BrowseResult.kt@@ -0,0 +1,67 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.filterExplicit+import com.metrolist.innertube.models.filterVideoSongs+import com.metrolist.innertube.models.filterYoutubeShorts++data class BrowseResult(+ val title: String?,+ val items: List<Item>,+) {+ data class Item(+ val title: String?,+ val items: List<YTItem>,+ )++ fun filterExplicit(enabled: Boolean = true) =+ if (enabled) {+ copy(+ items =+ items.mapNotNull {+ it.copy(+ items =+ it.items+ .filterExplicit()+ .ifEmpty { return@mapNotNull null },+ )+ },+ )+ } else {+ this+ }++ fun filterVideoSongs(disableVideos: Boolean = false) =+ if (disableVideos) {+ copy(+ items =+ items.mapNotNull {+ it.copy(+ items =+ it.items+ .filterVideoSongs(true)+ .ifEmpty { return@mapNotNull null },+ )+ },+ )+ } else {+ this+ }++ fun filterYoutubeShorts(enabled: Boolean = false) =+ if (enabled) {+ copy(+ items =+ items.mapNotNull {+ it.copy(+ items =+ it.items+ .filterYoutubeShorts(true)+ .ifEmpty { return@mapNotNull null },+ )+ },+ )+ } else {+ this+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/ChartsPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ChartsPage.ktnew file mode 100644index 0000000..3941b00--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ChartsPage.kt@@ -0,0 +1,18 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.*++data class ChartsPage(+ val sections: List<ChartSection>,+ val continuation: String?+) {+ data class ChartSection(+ val title: String,+ val items: List<YTItem>,+ val chartType: ChartType+ )++ enum class ChartType {+ TRENDING, TOP, GENRE, NEW_RELEASES+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/ExplorePage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ExplorePage.ktnew file mode 100644index 0000000..e4b25f0--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/ExplorePage.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.AlbumItem++data class ExplorePage(+ val newReleaseAlbums: List<AlbumItem>,+ val moodAndGenres: List<MoodAndGenres.Item>,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/HistoryPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HistoryPage.ktnew file mode 100644index 0000000..0b00996--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HistoryPage.kt@@ -0,0 +1,78 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicShelfRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.getItems+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class HistoryPage(+ val sections: List<HistorySection>?,+) {+ data class HistorySection(+ val title: String,+ val songs: List<SongItem>+ )++ companion object {+ fun fromMusicShelfRenderer(renderer: MusicShelfRenderer): HistorySection {+ return HistorySection(+ title = renderer.title?.runs?.firstOrNull()?.text!!,+ songs = renderer.contents?.getItems()?.mapNotNull {+ fromMusicResponsiveListItemRenderer(it)+ }!!+ )+ }++ private fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ // Split the secondary line by bullet separator to separate artists from other metadata (like views)+ val secondaryLineRuns = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()++ return SongItem(+ id = renderer.videoId ?: return null,+ title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()+ ?.text ?: return null,+ artists = secondaryLineRuns?.firstOrNull()?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ } ?: emptyList(),+ album = renderer.flexColumns.getOrNull(3)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return@let null+ )+ },+ duration = renderer.fixedColumns?.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ historyRemoveToken = renderer.menu?.menuRenderer?.items?.find {+ it.menuServiceItemRenderer?.icon?.iconType == "REMOVE_FROM_HISTORY"+ }?.menuServiceItemRenderer?.serviceEndpoint?.feedbackEndpoint?.feedbackToken,+ isEpisode = renderer.isEpisode+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.ktnew file mode 100644index 0000000..03b26e1--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/HomePage.kt@@ -0,0 +1,372 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.BrowseEndpoint+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicCarouselShelfRenderer+import com.metrolist.innertube.models.MusicMultiRowListItemRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.SectionListRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.models.filterExplicit+import com.metrolist.innertube.models.filterVideoSongs+import com.metrolist.innertube.utils.parseTime+import timber.log.Timber++data class HomePage(+ val chips: List<Chip>?,+ val sections: List<Section>,+ val continuation: String? = null,+) {+ data class Chip(+ val title: String,+ val endpoint: BrowseEndpoint?,+ val deselectEndPoint: BrowseEndpoint?,+ ) {+ companion object {+ fun fromChipCloudChipRenderer(renderer: SectionListRenderer.Header.ChipCloudRenderer.Chip): Chip? {+ return Chip(+ title = renderer.chipCloudChipRenderer.text?.runs?.firstOrNull()?.text ?: return null,+ endpoint = renderer.chipCloudChipRenderer.navigationEndpoint?.browseEndpoint,+ deselectEndPoint = renderer.chipCloudChipRenderer.onDeselectedCommand?.browseEndpoint,+ )+ }+ }+ }++ data class Section(+ val title: String,+ val label: String?,+ val thumbnail: String?,+ val endpoint: BrowseEndpoint?,+ val items: List<YTItem>,+ ) {+ companion object {+ fun fromMusicCarouselShelfRenderer(renderer: MusicCarouselShelfRenderer): Section? {+ val title = renderer.header?.musicCarouselShelfBasicHeaderRenderer?.title?.runs?.firstOrNull()?.text+ Timber.d("HomePage section title: $title, contents: ${renderer.contents.size}")++ if (title == null) {+ Timber.d("HomePage section skipped: no title")+ return null+ }++ val twoRowCount = renderer.contents.count { it.musicTwoRowItemRenderer != null }+ val multiRowCount = renderer.contents.count { it.musicMultiRowListItemRenderer != null }+ val responsiveCount = renderer.contents.count { it.musicResponsiveListItemRenderer != null }+ Timber.d("HomePage section '$title': twoRow=$twoRowCount, multiRow=$multiRowCount, responsive=$responsiveCount")++ val items = mutableListOf<YTItem>()++ // Parse musicTwoRowItemRenderer items (songs, albums, playlists, artists, podcasts)+ renderer.contents.mapNotNull { it.musicTwoRowItemRenderer }+ .mapNotNull { fromMusicTwoRowItemRenderer(it) }+ .let { items.addAll(it) }++ // Parse musicMultiRowListItemRenderer items (podcast episodes)+ renderer.contents.mapNotNull { it.musicMultiRowListItemRenderer }+ .mapNotNull { fromMusicMultiRowListItemRenderer(it) }+ .let { items.addAll(it) }++ // Parse musicResponsiveListItemRenderer items (quick picks songs)+ renderer.contents.mapNotNull { it.musicResponsiveListItemRenderer }+ .mapNotNull { fromMusicResponsiveListItemRenderer(it) }+ .let { items.addAll(it) }++ val podcastCount = items.count { it is PodcastItem }+ val episodeCount = items.count { it is EpisodeItem }+ val songCount = items.count { it is SongItem }+ Timber.d("HomePage section '$title': parsed ${items.size} items (podcasts=$podcastCount, episodes=$episodeCount, songs=$songCount)")++ if (items.isEmpty()) {+ Timber.d("HomePage section '$title' skipped: no items")+ return null+ }++ return Section(+ title = title,+ label = renderer.header.musicCarouselShelfBasicHeaderRenderer.strapline?.runs?.firstOrNull()?.text,+ thumbnail = renderer.header.musicCarouselShelfBasicHeaderRenderer.thumbnail?.getThumbnailUrl(),+ endpoint = renderer.header.musicCarouselShelfBasicHeaderRenderer.moreContentButton?.buttonRenderer?.navigationEndpoint?.browseEndpoint,+ items = items+ )+ }++ private fun fromMusicMultiRowListItemRenderer(renderer: MusicMultiRowListItemRenderer): EpisodeItem? {+ val subtitleRuns = renderer.subtitle?.runs?.splitBySeparator()+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return EpisodeItem(+ id = renderer.onTap?.watchEndpoint?.videoId ?: return null,+ title = renderer.title?.runs?.firstOrNull()?.text ?: return null,+ author = null,+ podcast = null,+ duration = subtitleRuns?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ publishDateText = subtitleRuns?.firstOrNull()?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = false,+ endpoint = renderer.onTap.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }++ private fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ // Quick picks uses musicResponsiveListItemRenderer for songs+ if (!renderer.isSong) return null++ val secondaryLine = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ ?: return null++ return SongItem(+ id = renderer.videoId ?: return null,+ title = renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists = secondaryLine.getOrNull(0)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ } ?: return null,+ album = secondaryLine.getOrNull(1)?.firstOrNull()+ ?.takeIf { it.navigationEndpoint?.browseEndpoint != null }+ ?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!+ )+ },+ duration = secondaryLine.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ isEpisode = renderer.isEpisode+ )+ }++ private fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {+ // Debug logging for type detection+ val title = renderer.title.runs?.firstOrNull()?.text ?: "unknown"+ val pageType = renderer.navigationEndpoint.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType+ val hasWatchEndpoint = renderer.navigationEndpoint.watchEndpoint != null++ if (!renderer.isSong && !renderer.isAlbum && !renderer.isPlaylist && !renderer.isArtist && !renderer.isPodcast && !renderer.isEpisode) {+ Timber.d("HomePage twoRow '$title': no type matched - pageType=$pageType, hasWatchEndpoint=$hasWatchEndpoint")+ }++ // Debug for episodes+ if (renderer.isEpisode) {+ val overlayVideoId = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchEndpoint?.videoId+ val browseId = renderer.navigationEndpoint.browseEndpoint?.browseId+ Timber.d("HomePage episode '$title': overlayVideoId=$overlayVideoId, browseId=$browseId")+ }++ return when {+ renderer.isSong -> {+ val subtitleRuns = renderer.subtitle?.runs ?: return null+ val artistRuns = subtitleRuns.filter {+ it.navigationEndpoint?.browseEndpoint?.browseId?.startsWith("MPREb_") != true+ }+ val title = renderer.title.runs?.firstOrNull()?.text ?: return null+ val videoId = renderer.navigationEndpoint.watchEndpoint?.videoId ?: return null+ val artists = PageHelper.extractArtists(artistRuns)++ SongItem(+ id = videoId,+ title = title,+ artists = artists,+ album = subtitleRuns.firstOrNull {+ it.navigationEndpoint?.browseEndpoint?.browseId?.startsWith("MPREb_") == true+ }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return@let null+ )+ },+ duration = null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl()+ ?: return null,+ explicit = renderer.subtitleBadges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true+ )+ }+ renderer.isAlbum -> {+ AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId = renderer.thumbnailOverlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint?.playlistId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = renderer.subtitle?.runs?.oddElements()?.drop(1)?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ year = null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )+ }++ renderer.isPlaylist -> {+ PlaylistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId?.removePrefix("VL") ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = Artist(+ name = renderer.subtitle?.runs?.firstOrNull()?.text ?: return null,+ id = null+ ),+ songCountText = null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint+ )+ }++ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.lastOrNull()?.text ?: return null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ )+ }++ renderer.isPodcast -> {+ PodcastItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ episodeCountText = null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl(),+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ )+ }++ renderer.isEpisode -> {+ val videoId = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchEndpoint?.videoId+ val titleText = renderer.title.runs?.firstOrNull()?.text+ val thumbnail = renderer.thumbnailRenderer.getThumbnailUrl()++ if (videoId == null || titleText == null || thumbnail == null) {+ Timber.d("HomePage episode FAILED: videoId=$videoId, title=$titleText, thumbnail=$thumbnail")+ return null+ }++ val subtitleRuns = renderer.subtitle?.runs?.splitBySeparator()+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ // Find podcast link in subtitle (has isPodcastEndpoint)+ val podcastRun = renderer.subtitle?.runs?.find {+ it.navigationEndpoint?.browseEndpoint?.isPodcastEndpoint == true+ }+ val podcastAlbum = podcastRun?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return@let null+ )+ }++ Timber.d("HomePage episode SUCCESS: '$titleText', podcast: ${podcastAlbum?.name}")+ EpisodeItem(+ id = videoId,+ title = titleText,+ author = subtitleRuns?.firstOrNull()?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ podcast = podcastAlbum,+ duration = subtitleRuns?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ publishDateText = subtitleRuns?.getOrNull(1)?.firstOrNull()?.text,+ thumbnail = thumbnail,+ explicit = renderer.subtitleBadges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true,+ endpoint = renderer.thumbnailOverlay+ .musicItemThumbnailOverlayRenderer.content+ .musicPlayButtonRenderer.playNavigationEndpoint+ .watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }++ else -> null+ }+ }+ }+ }++ fun filterExplicit(enabled: Boolean = true) =+ if (enabled) {+ copy(sections = sections.map {+ it.copy(items = it.items.filterExplicit())+ })+ } else this++ fun filterVideoSongs(disableVideos: Boolean = false) =+ if (disableVideos) {+ copy(sections = sections.map { section ->+ section.copy(items = section.items.filterVideoSongs(true))+ })+ } else this+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryAlbumsPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryAlbumsPage.ktnew file mode 100644index 0000000..74e02ca--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryAlbumsPage.kt@@ -0,0 +1,36 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.utils.parseTime++data class LibraryAlbumsPage(+ val albums: List<AlbumItem>,+ val continuation: String?,+) {+ companion object {+ fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): AlbumItem? {+ return AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId = renderer.thumbnailOverlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint?.playlistId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = null,+ year = renderer.subtitle?.runs?.lastOrNull()?.text?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryContinuationPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryContinuationPage.ktnew file mode 100644index 0000000..a98b8de--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryContinuationPage.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.YTItem++data class LibraryContinuationPage(+ val items: List<YTItem>,+ val continuation: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryPage.ktnew file mode 100644index 0000000..5dd67e5--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/LibraryPage.kt@@ -0,0 +1,292 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.Run+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime+import timber.log.Timber++data class LibraryPage(+ val items: List<YTItem>,+ val continuation: String?,+) {+ companion object {+ fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {+ return when {+ renderer.isAlbum -> AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId = renderer.thumbnailOverlay?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint?.playlistId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ artists = parseArtists(renderer.subtitle?.runs),+ year = renderer.subtitle?.runs?.lastOrNull()?.text?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl()+ ?: return null,+ explicit = renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null+ )++ renderer.isPlaylist -> PlaylistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId?.removePrefix("VL") ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ songCountText = renderer.subtitle?.runs?.lastOrNull()?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ isEditable = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "EDIT"+ } != null+ )++ renderer.isArtist -> ArtistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.lastOrNull()?.text ?: return null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint ?: return null,+ )++ // Podcast host channels use MUSIC_PAGE_TYPE_USER_CHANNEL (not ARTIST)+ renderer.isUserChannel -> ArtistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl(),+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ )++ renderer.isPodcast -> {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)+ PodcastItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ episodeCountText = renderer.subtitle?.runs?.lastOrNull()?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl(),+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }++ renderer.isEpisode || renderer.isSong -> {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)+ val videoId = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchEndpoint?.videoId ?: return null+ val title = renderer.title.runs?.firstOrNull()?.text ?: return null+ val subtitleRuns = renderer.subtitle?.runs?.splitBySeparator()+ val artists = PageHelper.extractArtists(subtitleRuns?.firstOrNull())++ if (artists.isEmpty() && (subtitleRuns?.firstOrNull()?.size ?: 0) > 0) {+ Timber.w("LibraryPage: Song '$title' (id=$videoId) - ARTIST RUNS EXIST but extractArtists returned EMPTY")+ }++ SongItem(+ id = videoId,+ title = title,+ artists = artists,+ album = subtitleRuns?.getOrNull(1)?.firstOrNull()?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: ""+ )+ },+ duration = subtitleRuns?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit = renderer.subtitleBadges?.any {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } == true,+ endpoint = renderer.thumbnailOverlay+ .musicItemThumbnailOverlayRenderer.content+ .musicPlayButtonRenderer.playNavigationEndpoint+ .watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode,+ )+ }++ else -> null+ }+ }++ fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): YTItem? {+ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return when {+ renderer.isSong -> {+ val videoId = renderer.videoId ?: return null+ val title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()?.text ?: return null++ val artistRuns = renderer.flexColumns.getOrNull(1)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.oddElements()++ // For uploaded songs, artists may not have browseEndpoint - make it optional+ val artists = artistRuns?.mapNotNull {+ val browseId = it.navigationEndpoint?.browseEndpoint?.browseId+ // For uploaded songs, use empty string for artist ID if not available+ Artist(name = it.text, id = browseId ?: "")+ } ?: emptyList()++ val albumRun = renderer.flexColumns.getOrNull(2)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()++ // For uploaded songs, album may not have browseEndpoint - make it optional+ val album = albumRun?.let {+ val albumBrowseId = it.navigationEndpoint?.browseEndpoint?.browseId+ Album(name = it.text, id = albumBrowseId ?: "")+ }++ val thumbnailUrl = renderer.thumbnail?.getThumbnailUrl() ?: return null++ // Extract uploadEntityId from delete menu item (for uploaded songs)+ // The entityId is nested in confirmDialogEndpoint -> content -> confirmDialogRenderer ->+ // confirmButton -> buttonRenderer -> command -> musicDeletePrivatelyOwnedEntityCommand -> entityId+ val uploadEntityId = renderer.menu?.menuRenderer?.items?.firstNotNullOfOrNull { item ->+ item.menuNavigationItemRenderer?.navigationEndpoint?.confirmDialogEndpoint+ ?.content?.confirmDialogRenderer?.confirmButton?.buttonRenderer+ ?.command?.musicDeletePrivatelyOwnedEntityCommand?.entityId+ }+ timber.log.Timber.d("Parsed uploaded song: id=$videoId, entityId=$uploadEntityId")++ SongItem(+ id = videoId,+ title = title,+ artists = artists,+ album = album,+ duration = renderer.fixedColumns?.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = thumbnailUrl,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode,+ uploadEntityId = uploadEntityId+ )+ }++ renderer.isArtist -> ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title = renderer.flexColumns.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl()+ ?: return null,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu?.menuRenderer?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint+ )++ // Podcast host channels use MUSIC_PAGE_TYPE_USER_CHANNEL (not ARTIST)+ renderer.isUserChannel -> ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title = renderer.flexColumns.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl(),+ shuffleEndpoint = renderer.menu?.menuRenderer?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu?.menuRenderer?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint+ )++ renderer.isPodcast -> {+ val podcastLibraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)+ PodcastItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title = renderer.flexColumns.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.text+ ?: return null,+ author = renderer.flexColumns.getOrNull(1)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ episodeCountText = renderer.flexColumns.getOrNull(1)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.lastOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl(),+ playEndpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ libraryAddToken = podcastLibraryTokens.addToken,+ libraryRemoveToken = podcastLibraryTokens.removeToken,+ )+ }++ else -> null+ }+ }++ private fun parseArtists(runs: List<Run>?): List<Artist> {+ val artists = mutableListOf<Artist>()++ if (runs != null) {+ for (run in runs) {+ if (run.navigationEndpoint != null) {+ artists.add(+ Artist(+ id = run.navigationEndpoint.browseEndpoint?.browseId!!,+ name = run.text+ )+ )+ }+ }+ }+ return artists+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/MoodAndGenres.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/MoodAndGenres.ktnew file mode 100644index 0000000..29e4b7a--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/MoodAndGenres.kt@@ -0,0 +1,47 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.BrowseEndpoint+import com.metrolist.innertube.models.GridRenderer+import com.metrolist.innertube.models.MusicNavigationButtonRenderer+import com.metrolist.innertube.models.SectionListRenderer++data class MoodAndGenres(+ val title: String,+ val items: List<Item>,+) {+ data class Item(+ val title: String,+ val stripeColor: Long,+ val endpoint: BrowseEndpoint,+ )++ companion object {+ fun fromSectionListRendererContent(content: SectionListRenderer.Content): MoodAndGenres? {+ return MoodAndGenres(+ title =+ content.gridRenderer+ ?.header+ ?.gridHeaderRenderer+ ?.title+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ items =+ content.gridRenderer.items+ .mapNotNull(GridRenderer.Item::musicNavigationButtonRenderer)+ .mapNotNull(::fromMusicNavigationButtonRenderer),+ )+ }++ fun fromMusicNavigationButtonRenderer(renderer: MusicNavigationButtonRenderer): Item? {+ return Item(+ title =+ renderer.buttonText.runs+ ?.firstOrNull()+ ?.text ?: return null,+ stripeColor = renderer.solid?.leftStripeColor ?: return null,+ endpoint = renderer.clickCommand.browseEndpoint ?: return null,+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/NewReleaseAlbumPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/NewReleaseAlbumPage.ktnew file mode 100644index 0000000..d711a75--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/NewReleaseAlbumPage.kt@@ -0,0 +1,44 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator++object NewReleaseAlbumPage {+ fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): AlbumItem? {+ return AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ renderer.subtitle?.runs?.splitBySeparator()?.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ year =+ renderer.subtitle.runs+ .lastOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit =+ renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/NextPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/NextPage.ktnew file mode 100644index 0000000..e1a8fc0--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/NextPage.kt@@ -0,0 +1,77 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.BrowseEndpoint+import com.metrolist.innertube.models.PlaylistPanelVideoRenderer+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.WatchEndpoint+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class NextResult(+ val title: String? = null,+ val items: List<SongItem>,+ val currentIndex: Int? = null,+ val lyricsEndpoint: BrowseEndpoint? = null,+ val relatedEndpoint: BrowseEndpoint? = null,+ val continuation: String?,+ val endpoint: WatchEndpoint, // current or continuation next endpoint+)++object NextPage {+ fun fromPlaylistPanelVideoRenderer(renderer: PlaylistPanelVideoRenderer): SongItem? {+ val longByLineRuns = renderer.longBylineText?.runs?.splitBySeparator() ?: return null++ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return SongItem(+ id = renderer.videoId+ ?: renderer.navigationEndpoint.watchEndpoint?.videoId+ ?: return null,+ title =+ renderer.title+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ longByLineRuns.firstOrNull()?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ album =+ longByLineRuns+ .getOrNull(1)+ ?.firstOrNull()+ ?.takeIf {+ it.navigationEndpoint?.browseEndpoint != null+ }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!,+ )+ },+ duration =+ renderer.lengthText+ ?.runs+ ?.firstOrNull()+ ?.text+ ?.parseTime() ?: return null,+ musicVideoType = renderer.navigationEndpoint.musicVideoType,+ thumbnail =+ renderer.thumbnail.thumbnails+ .lastOrNull()+ ?.url ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/PageHelper.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PageHelper.ktnew file mode 100644index 0000000..3980dff--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PageHelper.kt@@ -0,0 +1,228 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.Menu+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer.FlexColumn+import com.metrolist.innertube.models.Run+import com.metrolist.innertube.models.splitArtistsByConjunction+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime+import timber.log.Timber++object PageHelper {+ // Icon types for library management (YouTube changed these in Feb 2026)+ // Old icons: LIBRARY_ADD (not in library), LIBRARY_SAVED/LIBRARY_REMOVE (in library)+ // New icons: BOOKMARK_BORDER (not in library), BOOKMARK (in library)+ // Note: KEEP/KEEP_OFF are for "Pin to Listen Again" - different from library!+ private val LIBRARY_ADD_ICONS = setOf("LIBRARY_ADD", "BOOKMARK_BORDER")+ private val LIBRARY_SAVED_ICONS = setOf("LIBRARY_SAVED", "BOOKMARK", "LIBRARY_REMOVE")+ private val ALL_LIBRARY_ICONS = LIBRARY_ADD_ICONS + LIBRARY_SAVED_ICONS++ /**+ * Data class to hold both library feedback tokens extracted from a menu+ */+ data class LibraryFeedbackTokens(+ val addToken: String?, // Token to add song to library (from BOOKMARK_BORDER)+ val removeToken: String? // Token to remove song from library (from BOOKMARK)+ )++ /**+ * Check if an icon type is a library-related icon (for filtering menu items)+ * Excludes KEEP/KEEP_OFF which are for "Pin to Listen Again"+ */+ fun isLibraryIcon(iconType: String?): Boolean {+ if (iconType == null) return false+ // Exclude KEEP/KEEP_OFF (Listen Again pins)+ if (iconType == "KEEP" || iconType == "KEEP_OFF") return false+ return iconType in ALL_LIBRARY_ICONS || iconType.startsWith("LIBRARY_")+ }++ /**+ * Check if an icon type indicates the song is NOT in library (add state)+ */+ fun isAddLibraryIcon(iconType: String?): Boolean {+ return iconType in LIBRARY_ADD_ICONS+ }++ /**+ * Check if an icon type indicates the song IS in library (saved/remove state)+ */+ fun isSavedLibraryIcon(iconType: String?): Boolean {+ return iconType in LIBRARY_SAVED_ICONS+ }++ fun extractRuns(columns: List<FlexColumn>, typeLike: String): List<Run> {+ val filteredRuns = mutableListOf<Run>()+ for (column in columns) {+ val runs = column.musicResponsiveListItemFlexColumnRenderer.text?.runs+ ?: continue++ for (run in runs) {+ val typeStr = run.navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType+ ?: run.navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType+ ?: continue++ if (typeLike in typeStr) {+ filteredRuns.add(run)+ }+ }+ }+ return filteredRuns+ }++ /**+ * Extract library feedback tokens from a list of menu items.+ *+ * This function iterates through ALL toggle menu items and extracts tokens+ * based on their icon types, ensuring we don't confuse library tokens with+ * "Pin to Listen Again" tokens (KEEP/KEEP_OFF).+ *+ * YouTube's icon system (Feb 2026):+ * - BOOKMARK_BORDER: Song NOT in library -> defaultToken = ADD, toggledToken = REMOVE+ * - BOOKMARK: Song IS in library -> defaultToken = REMOVE, toggledToken = ADD+ * - KEEP/KEEP_OFF: "Pin to Listen Again" - COMPLETELY DIFFERENT, must be ignored!+ *+ * @param menuItems The list of menu items to search through+ * @return LibraryFeedbackTokens containing both add and remove tokens+ */+ fun extractLibraryTokensFromMenuItems(+ menuItems: List<Menu.MenuRenderer.Item>?+ ): LibraryFeedbackTokens {+ if (menuItems == null) return LibraryFeedbackTokens(null, null)++ var addToken: String? = null+ var removeToken: String? = null++ for (item in menuItems) {+ val toggleRenderer = item.toggleMenuServiceItemRenderer ?: continue+ val iconType = toggleRenderer.defaultIcon.iconType++ // Skip KEEP/KEEP_OFF icons (Pin to Listen Again) - these are NOT library actions+ if (iconType == "KEEP" || iconType == "KEEP_OFF") continue++ // Only process library-related icons+ if (!isLibraryIcon(iconType)) continue++ val defaultToken = toggleRenderer.defaultServiceEndpoint.feedbackEndpoint?.feedbackToken+ val toggledToken = toggleRenderer.toggledServiceEndpoint?.feedbackEndpoint?.feedbackToken++ // Determine which token is which based on icon type+ when {+ isAddLibraryIcon(iconType) -> {+ // BOOKMARK_BORDER or LIBRARY_ADD: default=add, toggled=remove+ if (addToken == null) addToken = defaultToken+ if (removeToken == null) removeToken = toggledToken+ }+ isSavedLibraryIcon(iconType) -> {+ // BOOKMARK or LIBRARY_SAVED/REMOVE: default=remove, toggled=add+ if (removeToken == null) removeToken = defaultToken+ if (addToken == null) addToken = toggledToken+ }+ }+ }++ return LibraryFeedbackTokens(addToken, removeToken)+ }++ /**+ * Extract feedback token for library operations.+ *+ * YouTube's new icon system (Feb 2026):+ * - BOOKMARK_BORDER: Song NOT in library -> defaultToken = ADD, toggledToken = REMOVE+ * - BOOKMARK: Song IS in library -> defaultToken = REMOVE, toggledToken = ADD+ *+ * @param menu The toggle menu renderer containing the feedback tokens+ * @param type "LIBRARY_ADD" to get the add token, "LIBRARY_REMOVE" to get the remove token+ * @return The appropriate feedback token, or null if not found+ */+ fun extractFeedbackToken(menu: Menu.MenuRenderer.Item.ToggleMenuServiceRenderer?, type: String): String? {+ if (menu == null) return null+ val defaultToken = menu.defaultServiceEndpoint.feedbackEndpoint?.feedbackToken+ val toggledToken = menu.toggledServiceEndpoint?.feedbackEndpoint?.feedbackToken+ val iconType = menu.defaultIcon.iconType++ // Determine if the current icon indicates song is NOT in library+ // BOOKMARK_BORDER or LIBRARY_ADD = song is NOT in library (default action is ADD)+ val songNotInLibrary = iconType in LIBRARY_ADD_ICONS++ return when (type) {+ "LIBRARY_ADD" -> {+ // We want the ADD token+ if (songNotInLibrary) {+ // Icon shows "add" state, default action adds to library+ defaultToken+ } else {+ // Icon shows "saved" state, toggled action would add back+ toggledToken+ }+ }+ "LIBRARY_REMOVE", "LIBRARY_SAVED" -> {+ // We want the REMOVE token+ if (songNotInLibrary) {+ // Icon shows "add" state, toggled action would remove+ toggledToken+ } else {+ // Icon shows "saved" state, default action removes from library+ defaultToken+ }+ }+ else -> if (iconType == type) defaultToken else toggledToken+ }+ }++ fun extractArtists(runs: List<Run>?): List<Artist> {+ val sections = runs.orEmpty().splitBySeparator()+ val linkedArtists = sections.flatMap { section ->+ val expandedRuns = section.splitArtistsByConjunction()+ if (expandedRuns.none { it.isArtistRun() }) return@flatMap emptyList()+ expandedRuns.mapNotNull { run ->+ val browseEndpoint = run.navigationEndpoint?.browseEndpoint+ val browseId = browseEndpoint?.browseId+ when {+ browseId?.startsWith("UC") == true || browseEndpoint?.isArtistEndpoint == true ->+ Artist(run.text, browseId)+ browseId == null && !run.text.isMetadataText() -> Artist(run.text.trim(), null)+ else -> null+ }+ }+ }+ if (linkedArtists.isNotEmpty()) return linkedArtists++ return sections.firstNotNullOfOrNull { section ->+ section+ .splitArtistsByConjunction()+ .filter { run ->+ run.navigationEndpoint?.browseEndpoint == null &&+ run.text.isNotBlank() &&+ run.text.trim() != "," &&+ !run.text.isMetadataText()+ }+ .map { Artist(it.text.trim(), null) }+ .takeIf { it.isNotEmpty() }+ }.orEmpty()+ }++ fun extractDuration(runs: List<Run>?): Int? =+ runs.orEmpty().firstNotNullOfOrNull { run ->+ run.text.trim().takeIf { it.isDurationText() }?.parseTime()+ }++ private fun Run.isArtistRun(): Boolean {+ val browseEndpoint = navigationEndpoint?.browseEndpoint+ return browseEndpoint?.browseId?.startsWith("UC") == true || browseEndpoint?.isArtistEndpoint == true+ }++ private fun String.isMetadataText(): Boolean {+ val value = trim()+ val lower = value.lowercase().replace('\u00a0', ' ')+ return value.isDurationText() ||+ value.matches(Regex("""(?:19|20)\d{2}""")) ||+ lower in setOf("song", "video", "single", "album", "episode", "playlist", "podcast") ||+ lower.contains("monthly audience") ||+ lower.matches(Regex("""\d[\d.,]*[kmb]?\s*(?:views?|plays?|likes?|subscribers?)"""))+ }++ private fun String.isDurationText(): Boolean =+ matches(Regex("""\d{1,2}[:.,]\d{2}(?:[:.,]\d{2})?"""))++}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistContinuationPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistContinuationPage.ktnew file mode 100644index 0000000..1f34f22--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistContinuationPage.kt@@ -0,0 +1,8 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.SongItem++data class PlaylistContinuationPage(+ val songs: List<SongItem>,+ val continuation: String?,+)diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistPage.ktnew file mode 100644index 0000000..4c38fcf--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PlaylistPage.kt@@ -0,0 +1,60 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.utils.parseTime+import timber.log.Timber++data class PlaylistPage(+ val playlist: PlaylistItem,+ val songs: List<SongItem>,+ val songsContinuation: String?,+ val continuation: String?,+) {+ companion object {+ fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ val secondaryLineRuns = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs++ val title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()?.text ?: return null++ if (secondaryLineRuns == null) {+ Timber.w("PlaylistPage.fromMusicResponsiveListItemRenderer: Song '$title' - NO SECONDARY LINE (flexColumns[1] is null)")+ }++ val artists = PageHelper.extractArtists(secondaryLineRuns)++ return SongItem(+ id = renderer.videoId ?: return null,+ title = title,+ artists = artists,+ album = renderer.flexColumns.getOrNull(2)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return@let null+ )+ },+ duration = renderer.fixedColumns?.firstOrNull()?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ setVideoId = renderer.playlistSetVideoId ?: return null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/PodcastPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PodcastPage.ktnew file mode 100644index 0000000..893a696--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/PodcastPage.kt@@ -0,0 +1,81 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicMultiRowListItemRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class PodcastPage(+ val podcast: PodcastItem,+ val episodes: List<EpisodeItem>,+ val continuation: String?,+ val isChannelSubscribed: Boolean = false,+) {+ companion object {+ fun fromMusicMultiRowListItemRenderer(+ renderer: MusicMultiRowListItemRenderer,+ podcast: PodcastItem? = null+ ): EpisodeItem? {+ val subtitleRuns = renderer.subtitle?.runs?.splitBySeparator()+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return EpisodeItem(+ id = renderer.onTap?.watchEndpoint?.videoId ?: return null,+ title = renderer.title?.runs?.firstOrNull()?.text ?: return null,+ author = podcast?.author,+ podcast = podcast?.let {+ Album(name = it.title, id = it.id)+ },+ duration = subtitleRuns?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ publishDateText = subtitleRuns?.firstOrNull()?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = false,+ endpoint = renderer.onTap.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }++ fun fromMusicResponsiveListItemRenderer(+ renderer: MusicResponsiveListItemRenderer,+ podcast: PodcastItem? = null+ ): EpisodeItem? {+ val secondaryLineRuns = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ return EpisodeItem(+ id = renderer.videoId ?: return null,+ title = renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text+ ?.runs?.firstOrNull()?.text ?: return null,+ author = podcast?.author ?: secondaryLineRuns?.firstOrNull()?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ podcast = podcast?.let {+ Album(name = it.title, id = it.id)+ },+ duration = secondaryLineRuns?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ publishDateText = secondaryLineRuns?.getOrNull(1)?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit = renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay?.musicItemThumbnailOverlayRenderer?.content?.musicPlayButtonRenderer?.playNavigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/RelatedPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/RelatedPage.ktnew file mode 100644index 0000000..0905524--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/RelatedPage.kt@@ -0,0 +1,203 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.MusicTwoRowItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class RelatedPage(+ val songs: List<SongItem>,+ val albums: List<AlbumItem>,+ val artists: List<ArtistItem>,+ val playlists: List<PlaylistItem>,+) {+ companion object {+ fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): SongItem? {+ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ // Split the secondary line by bullet separator to separate artists from other metadata (like views)+ val secondaryLineRuns = renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()++ return SongItem(+ id = renderer.videoId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ secondaryLineRuns?.firstOrNull()?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ album =+ renderer.flexColumns.getOrNull(2)?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ )+ },+ duration = renderer.fixedColumns?.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer?.text?.runs?.firstOrNull()+ ?.text?.parseTime(),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode+ )+ }++ fun fromMusicTwoRowItemRenderer(renderer: MusicTwoRowItemRenderer): YTItem? {+ return when {+ renderer.isAlbum ->+ AlbumItem(+ browseId = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists = listOfNotNull(Artist(+ name = "",+ id = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "ARTIST"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.browseEndpoint?.browseId,+ )),+ year =+ renderer.subtitle+ ?.runs+ ?.lastOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ explicit =+ renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ renderer.isPlaylist ->+ PlaylistItem(+ id =+ renderer.navigationEndpoint.browseEndpoint+ ?.browseId+ ?.removePrefix("VL") ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = Artist(+ name = renderer.subtitle?.runs?.lastOrNull()?.text ?: return null,+ id = null+ ),+ songCountText = renderer.subtitle.runs.findLast {+ it.text.any { c -> c.isDigit() } && !it.text.contains("view", ignoreCase = true)+ }?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint+ )+ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl() ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MIX"+ }?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }+ renderer.isPodcast -> {+ PodcastItem(+ id = renderer.navigationEndpoint.browseEndpoint?.browseId ?: return null,+ title = renderer.title.runs?.firstOrNull()?.text ?: return null,+ author = renderer.subtitle?.runs?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId+ )+ },+ episodeCountText = renderer.subtitle?.runs?.lastOrNull()?.text,+ thumbnail = renderer.thumbnailRenderer.getThumbnailUrl(),+ playEndpoint = renderer.thumbnailOverlay+ ?.musicItemThumbnailOverlayRenderer?.content+ ?.musicPlayButtonRenderer?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu?.menuRenderer?.items?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer?.navigationEndpoint?.watchPlaylistEndpoint,+ )+ }+ else -> null+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchPage.ktnew file mode 100644index 0000000..6043088--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchPage.kt@@ -0,0 +1,365 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class SearchResult(+ val items: List<YTItem>,+ val continuation: String? = null,+)++object SearchPage {+ fun toYTItem(renderer: MusicResponsiveListItemRenderer): YTItem? {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ ?: return null+ return when {+ // CRITICAL: Check isEpisode BEFORE isSong — both can match isSong (watchEndpoint or+ // null navigationEndpoint), so episodes must be identified first.+ renderer.isEpisode -> {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ // The subtitle line structure differs between filtered and unfiltered search:+ // Unfiltered: ["Episode", "·", "Jan 2025", "·", "Podcast Name", "·", "1:00:00"]+ // → secondaryLine = [["Episode"], ["Jan 2025"], ["Podcast Name"], ["1:00:00"]]+ // Filtered: ["Jan 2025", "·", "Podcast Name"]+ // → secondaryLine = [["Jan 2025"], ["Podcast Name"]]+ //+ // Strategy: locate the podcast section by its PODCAST_SHOW_DETAIL_PAGE link;+ // the date is in the section immediately before it.+ val podcastSectionIndex = secondaryLine.indexOfFirst { section ->+ section.any { run ->+ run.navigationEndpoint?.browseEndpoint+ ?.browseEndpointContextSupportedConfigs+ ?.browseEndpointContextMusicConfig+ ?.pageType == MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE+ }+ }++ val podcast = if (podcastSectionIndex >= 0) {+ secondaryLine[podcastSectionIndex].firstOrNull()?.let { run ->+ Album(+ name = run.text,+ id = run.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ )+ }+ } else null++ val publishDateText = if (podcastSectionIndex > 0)+ secondaryLine.getOrNull(podcastSectionIndex - 1)?.firstOrNull()?.text+ else null++ EpisodeItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = null,+ podcast = podcast,+ duration =+ secondaryLine+ .lastOrNull()+ ?.firstOrNull()+ ?.text+ ?.parseTime(),+ publishDateText = publishDateText,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ // In filtered search the overlay play button may be absent; fall back to the+ // item's own watchEndpoint so the episode is always playable.+ endpoint = renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchEndpoint+ ?: renderer.navigationEndpoint?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }+ renderer.isSong -> {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)+ val metadataRuns = renderer.flexColumns+ .drop(1)+ .flatMap { it.musicResponsiveListItemFlexColumnRenderer.text?.runs.orEmpty() }+ val artists = PageHelper.extractArtists(metadataRuns)++ SongItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists = artists.ifEmpty { return null },+ album =+ secondaryLine.getOrNull(1)?.firstOrNull()?.takeIf { it.navigationEndpoint?.browseEndpoint != null }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!,+ )+ },+ duration = PageHelper.extractDuration(metadataRuns),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode+ )+ }+ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }+ renderer.isUserChannel -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ isProfile = true,+ )+ }+ renderer.isAlbum -> {+ AlbumItem(+ browseId = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.anyWatchEndpoint+ ?.playlistId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ secondaryLine.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ year =+ secondaryLine+ .getOrNull(2)+ ?.firstOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }+ renderer.isPlaylist -> {+ PlaylistItem(+ id =+ renderer.navigationEndpoint+ ?.browseEndpoint+ ?.browseId+ ?.removePrefix("VL") ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author =+ secondaryLine.firstOrNull()?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ songCountText =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.lastOrNull()+ ?.text ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }+ renderer.isPodcast -> {+ PodcastItem(+ id =+ renderer.navigationEndpoint+ ?.browseEndpoint+ ?.browseId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author =+ secondaryLine.firstOrNull()?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ episodeCountText =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.lastOrNull()+ ?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ )+ }+ else -> null+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSuggestionPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSuggestionPage.ktnew file mode 100644index 0000000..c3752d9--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSuggestionPage.kt@@ -0,0 +1,302 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++object SearchSuggestionPage {+ fun fromMusicResponsiveListItemRenderer(renderer: MusicResponsiveListItemRenderer): YTItem? {+ return when {+ renderer.isPodcast -> {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ PodcastItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = secondaryLine?.getOrNull(0)?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ episodeCountText = secondaryLine?.lastOrNull()?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ )+ }+ renderer.isEpisode -> {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ val firstSubtitle = secondaryLine?.getOrNull(0)?.firstOrNull()?.text+ val isUnfilteredSearch = firstSubtitle == "Episode"+ val dateIndex = if (isUnfilteredSearch) 1 else 0+ val podcastIndex = if (isUnfilteredSearch) 2 else 1+ EpisodeItem(+ id = renderer.videoId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = null,+ podcast = secondaryLine?.getOrNull(podcastIndex)?.firstOrNull()?.takeIf {+ it.navigationEndpoint?.browseEndpoint != null+ }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!,+ )+ },+ duration = secondaryLine?.lastOrNull()?.firstOrNull()?.text?.parseTime(),+ publishDateText = secondaryLine?.getOrNull(dateIndex)?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ endpoint = renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchEndpoint,+ libraryAddToken = null,+ libraryRemoveToken = null,+ )+ }+ renderer.isPlaylist -> {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ PlaylistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId+ ?.removePrefix("VL") ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = secondaryLine?.firstOrNull()?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ songCountText = secondaryLine.lastOrNull()?.firstOrNull()?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint = renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint = renderer.menu.menuRenderer.items+ .find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }+ renderer.isSong -> {+ val metadataRuns = renderer.flexColumns+ .drop(1)+ .flatMap { it.musicResponsiveListItemFlexColumnRenderer.text?.runs.orEmpty() }+ val artists = PageHelper.extractArtists(metadataRuns)+ SongItem(+ id = renderer.videoId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists = artists.ifEmpty { return null },+ album =+ renderer.flexColumns+ .getOrNull(+ 2,+ )?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ )+ },+ duration = PageHelper.extractDuration(metadataRuns),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }+ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ radioEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ )+ }+ renderer.isUserChannel -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ )+ }+ renderer.isAlbum -> {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator() ?: return null+ AlbumItem(+ browseId = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find {+ it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE"+ }?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ secondaryLine.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ year =+ secondaryLine+ .lastOrNull()+ ?.firstOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }+ else -> null+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSummaryPage.kt b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSummaryPage.ktnew file mode 100644index 0000000..b9dee24--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/pages/SearchSummaryPage.kt@@ -0,0 +1,583 @@+package com.metrolist.innertube.pages++import com.metrolist.innertube.models.Album+import com.metrolist.innertube.models.AlbumItem+import com.metrolist.innertube.models.Artist+import com.metrolist.innertube.models.ArtistItem+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ALBUM+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_ARTIST+import com.metrolist.innertube.models.BrowseEndpoint.BrowseEndpointContextSupportedConfigs.BrowseEndpointContextMusicConfig.Companion.MUSIC_PAGE_TYPE_USER_CHANNEL+import com.metrolist.innertube.models.EpisodeItem+import com.metrolist.innertube.models.MusicCardShelfRenderer+import com.metrolist.innertube.models.MusicResponsiveListItemRenderer+import com.metrolist.innertube.models.PlaylistItem+import com.metrolist.innertube.models.PodcastItem+import com.metrolist.innertube.models.SongItem+import com.metrolist.innertube.models.YTItem+import com.metrolist.innertube.models.filterExplicit+import com.metrolist.innertube.models.filterVideoSongs+import com.metrolist.innertube.models.filterYoutubeShorts+import com.metrolist.innertube.models.oddElements+import com.metrolist.innertube.models.splitBySeparator+import com.metrolist.innertube.utils.parseTime++data class SearchSummary(+ val title: String,+ val items: List<YTItem>,+)++data class SearchSummaryPage(+ val summaries: List<SearchSummary>,+) {+ fun filterExplicit(enabled: Boolean) =+ if (enabled) {+ SearchSummaryPage(+ summaries.mapNotNull { s ->+ SearchSummary(+ title = s.title,+ items =+ s.items.filterExplicit().ifEmpty {+ return@mapNotNull null+ },+ )+ },+ )+ } else {+ this+ }++ fun filterVideoSongs(disableVideos: Boolean) =+ if (disableVideos) {+ SearchSummaryPage(+ summaries.mapNotNull { s ->+ SearchSummary(+ title = s.title,+ items =+ s.items.filterVideoSongs(true).ifEmpty {+ return@mapNotNull null+ },+ )+ },+ )+ } else {+ this+ }++ fun filterYoutubeShorts(enabled: Boolean = false) =+ if (enabled) {+ SearchSummaryPage(+ summaries.mapNotNull { s ->+ SearchSummary(+ title = s.title,+ items =+ s.items.filterYoutubeShorts(true).ifEmpty {+ return@mapNotNull null+ },+ )+ },+ )+ } else {+ this+ }++ companion object {+ fun fromMusicCardShelfRenderer(renderer: MusicCardShelfRenderer): YTItem? {+ val subtitle = renderer.subtitle.runs?.splitBySeparator()+ return when {+ renderer.onTap.watchEndpoint != null -> {+ SongItem(+ id = renderer.onTap.watchEndpoint.videoId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ subtitle?.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ album =+ subtitle.getOrNull(2)?.firstOrNull()?.takeIf { it.navigationEndpoint?.browseEndpoint != null }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!,+ )+ },+ duration =+ subtitle+ .lastOrNull()+ ?.firstOrNull()+ ?.text+ ?.parseTime(),+ musicVideoType = renderer.onTap.musicVideoType,+ thumbnail = renderer.thumbnail.getThumbnailUrl() ?: return null,+ explicit =+ renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }++ renderer.onTap.browseEndpoint?.isArtistEndpoint == true -> {+ ArtistItem(+ id = renderer.onTap.browseEndpoint.browseId,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ thumbnail = renderer.thumbnail.getThumbnailUrl() ?: return null,+ shuffleEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "MIX" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint ?: return null,+ )+ }++ renderer.onTap.browseEndpoint?.isAlbumEndpoint == true -> {+ AlbumItem(+ browseId = renderer.onTap.browseEndpoint.browseId,+ playlistId =+ renderer.buttons+ .firstOrNull()+ ?.buttonRenderer+ ?.command+ ?.anyWatchEndpoint+ ?.playlistId ?: return null,+ title =+ renderer.title.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ subtitle?.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ year = null,+ thumbnail = renderer.thumbnail.getThumbnailUrl() ?: return null,+ explicit =+ renderer.subtitleBadges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }++ renderer.onTap.browseEndpoint?.isPlaylistEndpoint == true -> {+ PlaylistItem(+ id =+ renderer.onTap.browseEndpoint.browseId+ .removePrefix("VL"),+ title =+ renderer.header?.musicCardShelfHeaderBasicRenderer?.title?.runs+ ?.joinToString(separator = "") { it.text }+ ?: return null,+ author =+ Artist(+ id = null,+ name = renderer.subtitle.runs?.joinToString { it.text } ?: return null,+ ),+ songCountText = null,+ thumbnail = renderer.thumbnail.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "PLAY_ARROW" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint+ ?: return null,+ shuffleEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint+ ?: return null,+ radioEndpoint = null,+ )+ }++ renderer.onTap.browseEndpoint?.isPodcastEndpoint == true -> {+ PodcastItem(+ id = renderer.onTap.browseEndpoint.browseId,+ title =+ renderer.header?.musicCardShelfHeaderBasicRenderer?.title?.runs+ ?.joinToString(separator = "") { it.text }+ ?: return null,+ author =+ Artist(+ id = null,+ name = renderer.subtitle.runs?.joinToString { it.text } ?: return null,+ ),+ episodeCountText = null,+ thumbnail = renderer.thumbnail.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "PLAY_ARROW" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint,+ shuffleEndpoint =+ renderer.buttons+ .find { it.buttonRenderer.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.buttonRenderer+ ?.command+ ?.watchPlaylistEndpoint,+ )+ }++ else -> null+ }+ }++ fun fromMusicResponsiveListItemRenderer(+ renderer: MusicResponsiveListItemRenderer,+ fallbackArtists: List<Artist> = emptyList(),+ ): YTItem? {+ val secondaryLine =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.splitBySeparator()+ ?: return null+ return when {+ // CRITICAL: Check isEpisode BEFORE isSong because both have videoId and no browseEndpoint+ // Episodes are identified by firstSubtitle == "Episode" in unfiltered search+ renderer.isEpisode -> {+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)++ // Check if firstSubtitle is "Episode" (unfiltered) or something else (filtered)+ // Unfiltered: [Episode][date][podcast] -> date at index 1, podcast at index 2+ // Filtered: [date][podcast] -> date at index 0, podcast at index 1+ val firstSubtitle = secondaryLine.getOrNull(0)?.firstOrNull()?.text+ val isUnfilteredSearch = firstSubtitle == "Episode"+ val dateIndex = if (isUnfilteredSearch) 1 else 0+ val podcastIndex = if (isUnfilteredSearch) 2 else 1++ EpisodeItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author = null, // Episodes don't have a separate author - the podcast is the source+ podcast =+ secondaryLine.getOrNull(podcastIndex)?.firstOrNull()?.takeIf {+ it.navigationEndpoint?.browseEndpoint != null+ }?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId!!,+ )+ },+ duration =+ secondaryLine+ .lastOrNull()+ ?.firstOrNull()+ ?.text+ ?.parseTime(),+ publishDateText =+ secondaryLine+ .getOrNull(dateIndex)+ ?.firstOrNull()+ ?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ endpoint = renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchEndpoint,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ )+ }++ renderer.isSong -> {+ // Extract library tokens using the new method that properly handles multiple toggle items+ val libraryTokens = PageHelper.extractLibraryTokensFromMenuItems(renderer.menu?.menuRenderer?.items)+ val metadataRuns = renderer.flexColumns+ .drop(1)+ .flatMap { it.musicResponsiveListItemFlexColumnRenderer.text?.runs.orEmpty() }+ val artists = PageHelper.extractArtists(metadataRuns).ifEmpty { fallbackArtists }+ val albumRun = PageHelper.extractRuns(renderer.flexColumns, "MUSIC_PAGE_TYPE_ALBUM").firstOrNull()++ SongItem(+ id = renderer.playlistItemData?.videoId+ ?: renderer.navigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.overlay?.musicItemThumbnailOverlayRenderer+ ?.content?.musicPlayButtonRenderer+ ?.playNavigationEndpoint?.watchEndpoint?.videoId+ ?: renderer.flexColumns.firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text?.runs?.firstOrNull()+ ?.navigationEndpoint?.watchEndpoint?.videoId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists = artists.ifEmpty { return null },+ album = albumRun?.let {+ Album(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId ?: return@let null,+ )+ },+ duration = PageHelper.extractDuration(metadataRuns),+ musicVideoType = renderer.musicVideoType,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ libraryAddToken = libraryTokens.addToken,+ libraryRemoveToken = libraryTokens.removeToken,+ isEpisode = renderer.isEpisode+ )+ }++ renderer.isArtist -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }++ renderer.isUserChannel -> {+ ArtistItem(+ id = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text+ ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ shuffleEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ radioEndpoint = renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ isProfile = true,+ )+ }++ renderer.isAlbum -> {+ AlbumItem(+ browseId = renderer.navigationEndpoint?.browseEndpoint?.browseId ?: return null,+ playlistId =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint+ ?.playlistId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ artists =+ secondaryLine.getOrNull(1)?.oddElements()?.map {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ year =+ secondaryLine+ .getOrNull(2)+ ?.firstOrNull()+ ?.text+ ?.toIntOrNull(),+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ explicit =+ renderer.badges?.find {+ it.musicInlineBadgeRenderer?.icon?.iconType == "MUSIC_EXPLICIT_BADGE"+ } != null,+ )+ }++ renderer.isPlaylist -> {+ PlaylistItem(+ id =+ renderer.navigationEndpoint+ ?.browseEndpoint+ ?.browseId+ ?.removePrefix("VL") ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author =+ secondaryLine.getOrNull(1)?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ } ?: return null,+ songCountText =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.lastOrNull()+ ?.text ?: return null,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ radioEndpoint =+ renderer.menu.menuRenderer.items+ .find { it.menuNavigationItemRenderer?.icon?.iconType == "MIX" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint ?: return null,+ )+ }++ renderer.isPodcast -> {+ PodcastItem(+ id =+ renderer.navigationEndpoint+ ?.browseEndpoint+ ?.browseId+ ?: return null,+ title =+ renderer.flexColumns+ .firstOrNull()+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.firstOrNull()+ ?.text ?: return null,+ author =+ secondaryLine.getOrNull(0)?.firstOrNull()?.let {+ Artist(+ name = it.text,+ id = it.navigationEndpoint?.browseEndpoint?.browseId,+ )+ },+ episodeCountText =+ renderer.flexColumns+ .getOrNull(1)+ ?.musicResponsiveListItemFlexColumnRenderer+ ?.text+ ?.runs+ ?.lastOrNull()+ ?.text,+ thumbnail = renderer.thumbnail?.getThumbnailUrl() ?: return null,+ playEndpoint =+ renderer.overlay+ ?.musicItemThumbnailOverlayRenderer+ ?.content+ ?.musicPlayButtonRenderer+ ?.playNavigationEndpoint+ ?.watchPlaylistEndpoint,+ shuffleEndpoint =+ renderer.menu+ ?.menuRenderer+ ?.items+ ?.find { it.menuNavigationItemRenderer?.icon?.iconType == "MUSIC_SHUFFLE" }+ ?.menuNavigationItemRenderer+ ?.navigationEndpoint+ ?.watchPlaylistEndpoint,+ )+ }++ else -> null+ }+ }+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/strategy/ContentAwareFallbackStrategy.kt b/innertube/src/main/kotlin/com/metrolist/innertube/strategy/ContentAwareFallbackStrategy.ktnew file mode 100644index 0000000..a559f32--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/strategy/ContentAwareFallbackStrategy.kt@@ -0,0 +1,58 @@+package com.metrolist.innertube.strategy++import com.metrolist.innertube.models.YouTubeClient++data class ContentHints(+ val isExplicit: Boolean? = null,+ val isKidsContent: Boolean? = null,+ val isLive: Boolean? = null,+ val isUploaded: Boolean? = null,+)++class ContentAwareFallbackStrategy {+ fun resolveClients(hints: ContentHints): List<YouTubeClient> =+ when {+ hints.isUploaded == true -> uploadedClients+ hints.isLive == true -> liveClients+ hints.isKidsContent == true -> kidsClients+ hints.isExplicit == true -> explicitClients+ else -> defaultClients+ }++ private companion object {+ val uploadedClients = listOf(+ YouTubeClient.TVHTML5,+ YouTubeClient.WEB_REMIX,+ YouTubeClient.WEB_CREATOR,+ )++ val defaultClients = listOf(+ YouTubeClient.VISIONOS,+ YouTubeClient.ANDROID_VR_1_65_10,+ YouTubeClient.ANDROID_VR_1_43_32,+ YouTubeClient.WEB_REMIX,+ YouTubeClient.TVHTML5,+ YouTubeClient.TVHTML5_SIMPLY,+ )++ val explicitClients = listOf(+ YouTubeClient.VISIONOS,+ YouTubeClient.TVHTML5,+ YouTubeClient.WEB_REMIX,+ )++ val kidsClients = listOf(+ YouTubeClient.TVHTML5,+ YouTubeClient.WEB_REMIX,+ YouTubeClient.TVHTML5_SIMPLY,+ YouTubeClient.WEB_CREATOR,+ )++ val liveClients = listOf(+ YouTubeClient.TVHTML5,+ YouTubeClient.WEB_REMIX,+ YouTubeClient.WEB_CREATOR,+ YouTubeClient.TVHTML5_SIMPLY,+ )+ }+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/utils/Utils.kt b/innertube/src/main/kotlin/com/metrolist/innertube/utils/Utils.ktnew file mode 100644index 0000000..ed7ab70--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/utils/Utils.kt@@ -0,0 +1,113 @@+package com.metrolist.innertube.utils++import com.metrolist.innertube.YouTube+import com.metrolist.innertube.pages.LibraryPage+import com.metrolist.innertube.pages.PlaylistPage+import java.security.MessageDigest++@JvmName("completedLibrary")+suspend fun Result<PlaylistPage>.completed(): Result<PlaylistPage> = runCatching {+ val page = getOrThrow()+ val songs = page.songs.toMutableList()+ var continuation = page.songsContinuation+ val seenContinuations = mutableSetOf<String>()+ var requestCount = 0+ val maxRequests = 50+ var consecutiveEmptyResponses = 0++ while (continuation != null && requestCount < maxRequests) {+ if (continuation in seenContinuations) {+ break+ }+ seenContinuations.add(continuation)+ requestCount++++ val continuationPage = YouTube.playlistContinuation(continuation).getOrNull() ?: break++ if (continuationPage.songs.isEmpty()) {+ consecutiveEmptyResponses+++ if (consecutiveEmptyResponses >= 2) break+ } else {+ consecutiveEmptyResponses = 0+ songs += continuationPage.songs+ }++ continuation = continuationPage.continuation+ }+ PlaylistPage(+ playlist = page.playlist,+ songs = songs,+ songsContinuation = null,+ continuation = page.continuation+ )+}++@JvmName("completedPlaylist")+suspend fun Result<LibraryPage>.completed(): Result<LibraryPage> = runCatching {+ val page = getOrThrow()+ val items = page.items.toMutableList()+ var continuation = page.continuation+ val seenContinuations = mutableSetOf<String>()+ var requestCount = 0+ val maxRequests = 50+ var consecutiveEmptyResponses = 0++ while (continuation != null && requestCount < maxRequests) {+ if (continuation in seenContinuations) {+ break+ }+ seenContinuations.add(continuation)+ requestCount++++ val continuationPage = YouTube.libraryContinuation(continuation).getOrNull() ?: break++ if (continuationPage.items.isEmpty()) {+ consecutiveEmptyResponses+++ if (consecutiveEmptyResponses >= 2) break+ } else {+ consecutiveEmptyResponses = 0+ items += continuationPage.items+ }++ continuation = continuationPage.continuation+ }+ LibraryPage(+ items = items,+ continuation = null+ )+}++fun ByteArray.toHex(): String = joinToString(separator = "") { eachByte -> "%02x".format(eachByte) }++fun sha1(str: String): String = MessageDigest.getInstance("SHA-1").digest(str.toByteArray()).toHex()++fun parseCookieString(cookie: String): Map<String, String> =+ cookie.split("; ")+ .filter { it.isNotEmpty() }+ .mapNotNull { part ->+ val splitIndex = part.indexOf('=')+ if (splitIndex == -1) null+ else part.substring(0, splitIndex) to part.substring(splitIndex + 1)+ }+ .toMap()++fun String.parseTime(): Int? {+ try {+ // YouTube Music returns duration with locale-dependent separators+ // (":" en-US, "." some locales, "," EU). Accept all.+ val parts = split(Regex("[:.,]")).map { it.toInt() }+ if (parts.size == 2) {+ return parts[0] * 60 + parts[1]+ }+ if (parts.size == 3) {+ return parts[0] * 3600 + parts[1] * 60 + parts[2]+ }+ } catch (e: Exception) {+ return null+ }+ return null+}++fun isPrivateId(browseId: String): Boolean {+ return browseId.contains("privately")+}diff --git a/innertube/src/main/kotlin/com/metrolist/innertube/utils/YouTubeUrlParser.kt b/innertube/src/main/kotlin/com/metrolist/innertube/utils/YouTubeUrlParser.ktnew file mode 100644index 0000000..569677a--- /dev/null+++ b/innertube/src/main/kotlin/com/metrolist/innertube/utils/YouTubeUrlParser.kt@@ -0,0 +1,171 @@+package com.metrolist.innertube.utils++import com.metrolist.innertube.models.WatchEndpoint++/**+ * Utility class for parsing YouTube and YouTube Music URLs.+ * Extracts video IDs, playlist IDs, and creates WatchEndpoints from URLs.+ */+object YouTubeUrlParser {+ /**+ * Represents the type of YouTube link parsed.+ */+ sealed class ParsedUrl {+ abstract val id: String++ data class Video(+ override val id: String,+ ) : ParsedUrl()++ data class Playlist(+ override val id: String,+ ) : ParsedUrl()++ data class Album(+ override val id: String,+ ) : ParsedUrl()++ data class Artist(+ override val id: String,+ ) : ParsedUrl()+ }++ /**+ * Pattern for matching YouTube video URLs.+ * Matches:+ * - https://www.youtube.com/watch?v=VIDEO_ID+ * - https://music.youtube.com/watch?v=VIDEO_ID+ * - https://youtu.be/VIDEO_ID+ * - https://www.youtube.com/shorts/VIDEO_ID+ */+ private val VIDEO_URL_PATTERNS =+ listOf(+ Regex("""(?:https?://)?(?:www\.)?(?:music\.)?youtube\.com/watch\?.*v=([a-zA-Z0-9_-]{11})"""),+ Regex("""(?:https?://)?(?:www\.)?(?:music\.)?youtube\.com/watch\?v=([a-zA-Z0-9_-]{11})"""),+ Regex("""(?:https?://)?youtu\.be/([a-zA-Z0-9_-]{11})"""),+ Regex("""(?:https?://)?(?:www\.)?youtube\.com/shorts/([a-zA-Z0-9_-]{11})"""),+ )++ /**+ * Pattern for matching YouTube playlist URLs.+ * Matches:+ * - https://www.youtube.com/playlist?list=PLAYLIST_ID+ * - https://music.youtube.com/playlist?list=PLAYLIST_ID+ */+ private val PLAYLIST_URL_PATTERN =+ Regex(+ """(?:https?://)?(?:www\.)?(?:music\.)?youtube\.com/playlist\?.*list=([a-zA-Z0-9_-]+)""",+ )++ /**+ * Pattern for matching YouTube Music album URLs.+ * Albums are essentially playlists with specific browse IDs.+ * Matches:+ * - https://music.youtube.com/playlist?list=PLAYLIST_ID+ */+ private val ALBUM_URL_PATTERN =+ Regex(+ """(?:https?://)?(?:www\.)?music\.youtube\.com/playlist\?.*list=([a-zA-Z0-9_-]+)""",+ )++ /**+ * Pattern for matching YouTube Music artist URLs.+ * Matches:+ * - https://music.youtube.com/channel/CHANNEL_ID+ * - https://music.youtube.com/browse/MPREb_... (artist browse ID)+ */+ private val ARTIST_URL_PATTERNS =+ listOf(+ Regex("""(?:https?://)?(?:www\.)?music\.youtube\.com/channel/([a-zA-Z0-9_-]+)"""),+ Regex("""(?:https?://)?(?:www\.)?music\.youtube\.com/browse/(MPRE[a-zA-Z0-9_-]+)"""),+ )++ /**+ * Checks if the given text is a YouTube URL.+ */+ fun isYouTubeUrl(text: String): Boolean = parse(text) != null++ /**+ * Parses a YouTube URL and returns the parsed result.+ *+ * @param url The URL to parse+ * @return ParsedUrl if valid, null otherwise+ */+ fun parse(url: String): ParsedUrl? {+ val trimmedUrl = url.trim()++ // Check for video URLs+ for (pattern in VIDEO_URL_PATTERNS) {+ pattern.find(trimmedUrl)?.let { matchResult ->+ matchResult.groupValues.getOrNull(1)?.let { videoId ->+ return ParsedUrl.Video(videoId)+ }+ }+ }++ // Check for playlist URLs (non-music.youtube.com)+ if (!trimmedUrl.contains("music.youtube.com")) {+ PLAYLIST_URL_PATTERN.find(trimmedUrl)?.let { matchResult ->+ matchResult.groupValues.getOrNull(1)?.let { playlistId ->+ return ParsedUrl.Playlist(playlistId)+ }+ }+ }++ // Check for album URLs (music.youtube.com playlists)+ if (trimmedUrl.contains("music.youtube.com")) {+ ALBUM_URL_PATTERN.find(trimmedUrl)?.let { matchResult ->+ matchResult.groupValues.getOrNull(1)?.let { playlistId ->+ // Albums on YouTube Music use playlist URLs+ // We'll treat them as albums and let the API determine the actual type+ return ParsedUrl.Album(playlistId)+ }+ }++ // Check for artist URLs+ for (pattern in ARTIST_URL_PATTERNS) {+ pattern.find(trimmedUrl)?.let { matchResult ->+ matchResult.groupValues.getOrNull(1)?.let { artistId ->+ return ParsedUrl.Artist(artistId)+ }+ }+ }+ }++ return null+ }++ /**+ * Extracts video ID from a YouTube URL.+ *+ * @param url The URL to parse+ * @return Video ID if found, null otherwise+ */+ fun extractVideoId(url: String): String? = (parse(url) as? ParsedUrl.Video)?.id++ /**+ * Extracts playlist ID from a YouTube URL.+ *+ * @param url The URL to parse+ * @return Playlist ID if found, null otherwise+ */+ fun extractPlaylistId(url: String): String? {+ val parsed = parse(url)+ return when (parsed) {+ is ParsedUrl.Playlist -> parsed.id+ is ParsedUrl.Album -> parsed.id+ else -> null+ }+ }++ /**+ * Creates a WatchEndpoint from a YouTube video URL.+ *+ * @param url The URL to parse+ * @return WatchEndpoint if valid video URL, null otherwise+ */+ fun createWatchEndpoint(url: String): WatchEndpoint? =+ extractVideoId(url)?.let { videoId ->+ WatchEndpoint(videoId = videoId)+ }+}diff --git a/native/vendor/librespot-core/src/audio_key.rs b/native/vendor/librespot-core/src/audio_key.rsindex 42cad43..3eeba25 100644--- a/native/vendor/librespot-core/src/audio_key.rs+++ b/native/vendor/librespot-core/src/audio_key.rs@@ -78,7 +78,49 @@ impl AudioKeyManager {Ok(())}+ /// LOCAL PATCH: retries a refused or timed-out key before giving up.+ ///+ /// Skipping quickly fires a burst of key requests, and Spotify answers some+ /// of them with `AesKeyError`. Upstream gives up on the first refusal, and+ /// the player then goes on to decode the still-encrypted bytes: the decoder+ /// dies on the garbage, the track ends immediately, the engine advances,+ /// and the next one is refused too. From the listener's side a run of skips+ /// turns into silence with the queue still moving.+ ///+ /// The refusal is rate limiting rather than a verdict on the track, so a+ /// short wait usually clears it. Only the transient failures are retried;+ /// a broken channel or an unexpected packet is structural and repeating it+ /// would just add latency to an error that is not going to change.pub async fn request(&self, track: SpotifyId, file: FileId) -> Result<AudioKey, Error> {+ const ATTEMPTS: usize = 3;+ const FIRST_BACKOFF: Duration = Duration::from_millis(250);++ let mut backoff = FIRST_BACKOFF;+ let mut last = None;++ for attempt in 0..ATTEMPTS {+ match self.request_once(track, file).await {+ Ok(key) => return Ok(key),+ Err(e) => {+ let transient = matches!(+ e.downcast_ref::<AudioKeyError>(),+ Some(AudioKeyError::AesKey) | Some(AudioKeyError::Timeout)+ );+ if !transient || attempt + 1 == ATTEMPTS {+ return Err(e);+ }+ debug!("audio key attempt {} failed, retrying", attempt + 1);+ last = Some(e);+ tokio::time::sleep(backoff).await;+ backoff *= 2;+ }+ }+ }++ Err(last.unwrap_or_else(|| AudioKeyError::Timeout.into()))+ }++ async fn request_once(&self, track: SpotifyId, file: FileId) -> Result<AudioKey, Error> {let (tx, rx) = oneshot::channel();let seq = self.lock(move |inner| {@@ -92,6 +134,9 @@ impl AudioKeyManager {match tokio::time::timeout(KEY_RESPONSE_TIMEOUT, rx).await {Err(_) => {error!("Audio key response timeout");+ // Upstream leaves the entry behind, so a burst of timeouts+ // grows the map for the life of the session.+ self.lock(|inner| inner.pending.remove(&seq));Err(AudioKeyError::Timeout.into())}Ok(k) => k?,diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 042e68b..febe01d 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -17,8 +17,22 @@ dependencyResolutionManagement {repositories {google()mavenCentral()+ // NewPipeExtractor, which powers the YouTube Music backend, publishes+ // nowhere else. Narrowed to that one group so nothing else in the tree+ // can silently start resolving from an unmoderated repository.+ maven("https://jitpack.io") {+ // Its own transitive modules (timeago-parser and friends) are+ // published under `com.github.TeamNewPipe.NewPipeExtractor`, hence+ // the prefix rather than the single group.+ content { includeGroupByRegex("com\\.github\\.TeamNewPipe.*") }+ }+ // Metrolist's extractor fork, which the vendored innertube module needs.+ maven("https://jitpack.io") {+ content { includeGroupByRegex("com\\.github\\.MetrolistGroup.*") }+ }}}rootProject.name = "Spot"include(":app")+include(":innertube")