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
YouTube Music keeps what Spotify keeps: lists, artists, songs on the phone
Lelonio12362a0ee8ac
diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.ktindex 5a597e4..0deadbf 100644--- a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt@@ -184,6 +184,33 @@ interface MusicBackend {suspend fun deletePlaylist(uri: String): Unit =throw UnsupportedOperationException()+ /**+ * The lists a track can be added to: the account's own, and the one that+ * keeps its liked songs where the source files those as a list.+ *+ * Not [playlists]: the library also holds lists somebody else made and the+ * account only saved, and offering those is offering a write that fails.+ * Empty where nothing can be written.+ */+ suspend fun writablePlaylists(): List<CatalogPlaylist> = emptyList()++ /** Whether a track can be taken out of this list by this account. */+ fun canWriteTo(playlistUri: String): Boolean = canEditPlaylists++ /** Appends a track to one of [writablePlaylists]. */+ suspend fun addToPlaylist(playlistUri: String, trackUri: String): Unit =+ throw UnsupportedOperationException()++ /** Takes a track back out of one of them. */+ suspend fun removeFromPlaylist(playlistUri: String, trackUri: String): Unit =+ throw UnsupportedOperationException()++ /** Whether the account follows an artist; null when the source cannot say. */+ suspend fun isFollowing(artistUri: String): Boolean? = null++ suspend fun setFollowing(artistUri: String, follow: Boolean): Unit =+ throw UnsupportedOperationException()+/** Whether this backend's catalogue owns the given URI. */fun owns(uri: String): Booleandiff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.ktindex 43bc333..c5772a5 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt@@ -161,6 +161,7 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {.getOrThrow().items.filterIsInstance<PlaylistItem>()+ .onEach { if (it.isEditable || it.id == LIKED_MUSIC_ID) editable.add(it.id) }.map { item ->CatalogPlaylist(uri = "$PLAYLIST_PREFIX${item.id}",@@ -201,7 +202,7 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {.filterIsInstance<ArtistItem>().map { artist ->SearchItem(- uri = "$ARTIST_PREFIX${artist.id}",+ uri = "$ARTIST_PREFIX${publicArtistId(artist.id)}",title = artist.title,subtitle = "",artworkUrl = artist.thumbnail?.atSize(COVER_SIZE),@@ -385,19 +386,55 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {// 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+ uri.startsWith(ARTIST_PREFIX) -> {+ val page = YouTube.artist(publicArtistId(id)).getOrThrow()+ // Kept for the follow button, which asks right after the page+ // opens: the same response already says both.+ artists[publicArtistId(id)] = ArtistFacts(+ channelId = page.artist.channelId ?: id,+ subscribed = page.isSubscribed,+ )+ page.sections.flatMap { it.items }.filterIsInstance<SongItem>().map(::toCatalogTrack)+ }else -> YouTube.playlist(id).getOrThrow().songs+ .onEach { song ->+ // What taking a song out of this list will need: YouTube+ // removes an entry, not a song, and names the entry here.+ song.setVideoId?.let { entries["$id/${song.id}"] = it }+ }.map(::toCatalogTrack)}}+ /** The lists the library said the account can write to; see [canWriteTo]. */+ private val editable = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()++ override fun canWriteTo(playlistUri: String): Boolean =+ account.isSignedIn && playlistUri.removePrefix(PLAYLIST_PREFIX) in editable++ /** Playlist entry ids, by "playlist/video"; see [removeFromPlaylist]. */+ private val entries = java.util.concurrent.ConcurrentHashMap<String, String>()++ /**+ * The id an artist's public page answers to.+ *+ * The library lists the artists it follows under an id of its own, the+ * channel's with "MPLA" in front, and that page only opens with the+ * account's credentials: opened as it came, it was a 401 in place of the+ * artist. Their public page is the channel itself.+ */+ private fun publicArtistId(id: String): String = id.removePrefix(LIBRARY_ARTIST_PREFIX)++ /** What an artist's page said about following them. */+ private data class ArtistFacts(val channelId: String, val subscribed: Boolean)++ private val artists = java.util.concurrent.ConcurrentHashMap<String, ArtistFacts>()+/*** lossless.wtf first, LrcLib for everything it does not have.*@@ -451,6 +488,81 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {}}+ /**+ * The account's own lists, and its liked songs.+ *+ * Liked songs are a list on YouTube Music like any other, and the one a+ * listener reaches for first, so they are offered here; what writes to them+ * is the like button, see [addToPlaylist].+ */+ override suspend fun writablePlaylists(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {+ if (!account.isSignedIn) return@withContext emptyList()+ YouTube.library(LIKED_PLAYLISTS_BROWSE_ID)+ .getOrThrow()+ .items+ .filterIsInstance<PlaylistItem>()+ .filter { it.isEditable || it.id == LIKED_MUSIC_ID }+ // Liked songs first, as the other source puts its own.+ .sortedBy { if (it.id == LIKED_MUSIC_ID) 0 else 1 }+ .map { item ->+ CatalogPlaylist(+ uri = "$PLAYLIST_PREFIX${item.id}",+ name = item.title,+ artworkUrl = item.thumbnail?.atSize(COVER_SIZE),+ )+ }+ }++ override suspend fun addToPlaylist(playlistUri: String, trackUri: String) {+ withContext(Dispatchers.IO) {+ val playlistId = playlistUri.removePrefix(PLAYLIST_PREFIX)+ val videoId = videoIdOfUri(trackUri)+ if (playlistId == LIKED_MUSIC_ID) {+ YouTube.likeVideo(videoId, like = true).getOrThrow()+ } else {+ YouTube.addToPlaylist(playlistId, videoId).getOrThrow()+ }+ }+ }++ override suspend fun removeFromPlaylist(playlistUri: String, trackUri: String) {+ withContext(Dispatchers.IO) {+ val playlistId = playlistUri.removePrefix(PLAYLIST_PREFIX)+ val videoId = videoIdOfUri(trackUri)+ if (playlistId == LIKED_MUSIC_ID) {+ YouTube.likeVideo(videoId, like = false).getOrThrow()+ return@withContext+ }+ val key = "$playlistId/$videoId"+ // Read again when the list was not read here: the entry id is the+ // only thing YouTube removes by.+ if (entries[key] == null) tracksOf(playlistUri)+ val entry = entries[key] ?: error("no entry for $videoId in $playlistId")+ YouTube.removeFromPlaylist(playlistId, videoId, entry).getOrThrow()+ entries.remove(key)+ }+ }++ override suspend fun isFollowing(artistUri: String): Boolean? = withContext(Dispatchers.IO) {+ if (!account.isSignedIn) return@withContext null+ val id = publicArtistId(artistUri.removePrefix(ARTIST_PREFIX))+ artists[id]?.subscribed ?: runCatching {+ val page = YouTube.artist(id).getOrThrow()+ ArtistFacts(page.artist.channelId ?: id, page.isSubscribed).also { artists[id] = it }+ }.getOrNull()?.subscribed+ }++ override suspend fun setFollowing(artistUri: String, follow: Boolean) {+ withContext(Dispatchers.IO) {+ val id = publicArtistId(artistUri.removePrefix(ARTIST_PREFIX))+ val channel = artists[id]?.channelId+ ?: YouTube.artist(id).getOrThrow().artist.channelId+ ?: id+ YouTube.subscribeChannel(channel, subscribe = follow).getOrThrow()+ artists[id] = ArtistFacts(channel, follow)+ }+ }+override fun owns(uri: String) = uri.startsWith(URI_SCHEME)override fun createPlayer(host: PlaybackHost): Player =@@ -469,6 +581,12 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {private const val FOLLOWED_ARTISTS_BROWSE_ID = "FEmusic_library_corpus_track_artists"private const val NEW_RELEASES_BROWSE_ID = "FEmusic_new_releases"+ /** What the library puts in front of the artists it follows; see publicArtistId. */+ private const val LIBRARY_ARTIST_PREFIX = "MPLA"++ /** YouTube Music's own id for the account's liked songs. */+ private const val LIKED_MUSIC_ID = "LM"+/** How many moods, and how many genres, the Radio tab reads. */private const val RADIO_PER_GROUP = 5diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.ktindex 487eae5..268f1d4 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubePlayerFactory.kt@@ -40,8 +40,13 @@ object YouTubePlayerFactory {.setMediaSourceFactory(DefaultMediaSourceFactory(ResolvingDataSource.Factory(- DefaultHttpDataSource.Factory(),- YouTubeStreamResolver(),+ // Files as well as the network: a kept song resolves to+ // one on the phone, which an HTTP source cannot open.+ androidx.media3.datasource.DefaultDataSource.Factory(+ host.context,+ DefaultHttpDataSource.Factory(),+ ),+ YouTubeStreamResolver(host.context.applicationContext),),),)@@ -128,6 +133,16 @@ object YouTubePlayerFactory {) = androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context).setEnableFloatOutput(enableFloatOutput).setEnableAudioTrackPlaybackParams(false)+ // Karaoke, ahead of Sonic. The default chain was all this sink+ // had, so the dial moved and the voice stayed: the removal is a+ // processor of this app's, and a chain that does not list it+ // does not run it. Before the stretcher, because it works on+ // what the two channels share and a stretched pair shares less.+ .setAudioProcessorChain(+ androidx.media3.exoplayer.audio.DefaultAudioSink.DefaultAudioProcessorChain(+ dev.lelonio.square.playback.VocalAudioProcessor(),+ ),+ ).build()}}@@ -144,20 +159,32 @@ object YouTubePlayerFactory {* Runs on ExoPlayer's loading thread, so blocking here is correct.*/@UnstableApi-private class YouTubeStreamResolver : ResolvingDataSource.Resolver {+private class YouTubeStreamResolver(+ private val context: android.content.Context,+) : ResolvingDataSource.Resolver {override fun resolveDataSpec(dataSpec: DataSpec): DataSpec {val uri = dataSpec.uri.toString()if (!uri.startsWith(YouTubeBackend.TRACK_PREFIX)) return dataSpec+ // A song kept on the phone plays from the phone. Not while the video is+ // showing and there is a network to fetch it over: the file is the+ // sound alone.+ val kept = dev.lelonio.square.download.YouTubeDownloads.fileFor(context, uri)+ if (kept != null &&+ (!YouTubeVideoMode.enabled.value || dev.lelonio.square.playback.OfflineMode.active.value)+ ) {+ return dataSpec.withUri(android.net.Uri.fromFile(kept))+ }+// 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()+ YouTubeStreams.ensureNewPipe()val videoId = YouTubeBackend.videoIdOfUri(uri)- val info = StreamInfo.getInfo(ServiceList.YouTube, "$WATCH_URL$videoId")+ val info = StreamInfo.getInfo(ServiceList.YouTube, "${YouTubeStreams.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@@ -183,18 +210,20 @@ private class YouTubeStreamResolver : ResolvingDataSource.Resolver {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+/** NewPipe's one-time setup, shared by the player and the downloads. */+object YouTubeStreams {+ const val WATCH_URL = "https://www.youtube.com/watch?v="- /** Idempotent: several tracks resolve on the same thread pool. */- @Synchronized- fun ensureNewPipe() {- if (initialised) return- NewPipe.init(NewPipeDownloader.create(), Localization.DEFAULT)- initialised = true- }+ @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/data/DownloadStore.kt b/app/src/main/java/dev/lelonio/square/data/DownloadStore.ktindex d2de12e..3d2b04c 100644--- a/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt+++ b/app/src/main/java/dev/lelonio/square/data/DownloadStore.kt@@ -216,7 +216,7 @@ class DownloadStore(context: Context) {val current = _index.valueval surviving = current.files.filterKeys { uri ->val record = current.files[uri] ?: return@filterKeys false- audioFile(record.trackId).exists()+ hasAudio(uri, record)}if (surviving.size != current.files.size) {publish(current.copy(files = surviving))@@ -600,6 +600,18 @@ class DownloadStore(context: Context) {private fun audioFile(trackId: String): File =File(File(root, "audio"), trackId.take(2)).resolve(trackId.drop(2))+ /**+ * Whether a kept song's audio is still on the phone, wherever its source+ * keeps it: the engine's store for Spotify, a file of its own named after+ * the video for YouTube Music. See YouTubeDownloads.+ */+ private fun hasAudio(trackUri: String, record: FileRecord): Boolean =+ if (trackUri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.TRACK_PREFIX)) {+ File(File(root, YOUTUBE_DIR), "${record.trackId}.${record.format}").exists()+ } else {+ audioFile(record.trackId).exists()+ }+private fun publish(index: Index) {_index.value = index_files.value = index.files@@ -644,6 +656,9 @@ class DownloadStore(context: Context) {const val MAX_ATTEMPTS = 5const val DIR_NAME = "downloads"++ /** Where YouTube Music's kept songs live inside it; see YouTubeDownloads. */+ const val YOUTUBE_DIR = "youtube"private const val INDEX_NAME = "index.json"/** The owner every single track downloaded on its own belongs to. */diff --git a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.ktindex 7139cdd..817e390 100644--- a/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt+++ b/app/src/main/java/dev/lelonio/square/download/DownloadQueue.kt@@ -1,5 +1,7 @@package dev.lelonio.square.download+import dev.lelonio.square.backend.youtube.YouTubeBackend+import android.content.Contextimport android.net.ConnectivityManagerimport android.net.Network@@ -287,11 +289,17 @@ class DownloadQueue(chunk.map { uri ->async {coversTried += uri- val cover = runCatching { NativeBridge.downloadState(uri) }- .getOrNull()- ?.let { runCatching { JSONObject(it).optString("coverUrl") }.getOrNull() }- ?.takeIf { it.isNotBlank() }- ?: return@async+ // A YouTube Music song has no engine record to ask; its+ // cover is the one the store kept with the song.+ val cover = if (uri.startsWith(YouTubeBackend.TRACK_PREFIX)) {+ store.trackOf(uri)?.artworkUrl ?: return@async+ } else {+ runCatching { NativeBridge.downloadState(uri) }+ .getOrNull()+ ?.let { runCatching { JSONObject(it).optString("coverUrl") }.getOrNull() }+ ?.takeIf { it.isNotBlank() }+ ?: return@async+ }DownloadExtras.keep(cover, "art")}}.awaitAll()@@ -329,6 +337,10 @@ class DownloadQueue(for (uri in missing) {extrasTried += uri+ if (uri.startsWith(YouTubeBackend.TRACK_PREFIX)) {+ store.trackOf(uri)?.artworkUrl?.let { runCatching { DownloadExtras.keep(it, "art") } }+ continue+ }// No sidecar is not a reason to skip: it carries the cover url the// engine recorded, and everything else here — the words, the tall// picture — is asked for by name from the index instead.@@ -368,7 +380,13 @@ class DownloadQueue(*/private fun needsExtras(trackUri: String): Boolean =needsCover(trackUri) ||- !DownloadExtras.asked("lyrics", trackUri) ||+ // The rest is Spotify's: its words, its tall pictures and its+ // Canvas are looked up by a Spotify track, and a YouTube Music song+ // would be asked about them on every run and never have them.+ (!trackUri.startsWith(YouTubeBackend.TRACK_PREFIX) && needsSpotifyExtras(trackUri))++ private fun needsSpotifyExtras(trackUri: String): Boolean =+ !DownloadExtras.asked("lyrics", trackUri) ||!DownloadExtras.asked("canvas", trackUri) ||needsArt(trackUri) ||needsClip(trackUri)@@ -392,6 +410,7 @@ class DownloadQueue(private enum class Outcome { DONE, FAILED, NOT_NOW }private suspend fun attempt(trackUri: String): Outcome {+ if (trackUri.startsWith(YouTubeBackend.TRACK_PREFIX)) return attemptYouTube(trackUri)val kbps = settings.quality.value.kbpsval outcome = runCatching {withContext(Dispatchers.IO) { NativeBridge.downloadTrack(trackUri, kbps) }@@ -436,6 +455,38 @@ class DownloadQueue(return Outcome.FAILED}+ /**+ * The same for a YouTube Music song, which is a file of its own rather than+ * the engine's; see YouTubeDownloads. Its cover is kept with it, since it+ * is the one extra this source has.+ */+ private suspend fun attemptYouTube(trackUri: String): Outcome {+ val outcome = runCatching {+ YouTubeDownloads.download(appContext, trackUri) { store.onProgress(trackUri, it) }+ }+ outcome.onSuccess { record ->+ store.onCompleted(trackUri, record)+ store.trackOf(trackUri)?.artworkUrl?.let { runCatching { DownloadExtras.keep(it, "art") } }+ return Outcome.DONE+ }++ val error = outcome.exceptionOrNull()+ store.clearProgress(trackUri)+ return when {+ // The queue itself stopping, which is not this song's doing.+ error is kotlinx.coroutines.CancellationException && !kotlin.coroutines.coroutineContext.isActive ->+ throw error+ // Taken off the list while it was coming.+ error is kotlinx.coroutines.CancellationException -> Outcome.FAILED+ // The network, which is worth another go once it is back.+ error is java.io.IOException -> Outcome.NOT_NOW+ else -> {+ store.onFailed(trackUri, error?.message.orEmpty().ifEmpty { "download failed" })+ Outcome.FAILED+ }+ }+ }+/*** Everything a downloaded song carries besides the song: the sleeve, the* tall picture, the words and the Canvas.diff --git a/app/src/main/java/dev/lelonio/square/download/YouTubeDownloads.kt b/app/src/main/java/dev/lelonio/square/download/YouTubeDownloads.ktnew file mode 100644index 0000000..08cd53b--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/download/YouTubeDownloads.kt@@ -0,0 +1,179 @@+package dev.lelonio.square.download++import android.content.Context+import dev.lelonio.square.backend.youtube.YouTubeBackend+import dev.lelonio.square.backend.youtube.YouTubeStreams+import dev.lelonio.square.data.DownloadStore+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request+import org.schabi.newpipe.extractor.ServiceList+import org.schabi.newpipe.extractor.stream.StreamInfo+import java.io.File+import java.io.FileOutputStream+import java.io.IOException+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.TimeUnit++/**+ * YouTube Music songs kept on the phone.+ *+ * The other source keeps its songs inside its engine; this one has no engine,+ * so a kept song is a file of its own: the same audio the player would stream,+ * fetched once and named after the video. The store that says who wants which+ * song is the same for both, which is what lets a playlist of either keep its+ * songs, share them with another and let them go.+ */+object YouTubeDownloads {++ /** Takes a kept song off the phone, whichever source it belongs to. */+ fun forget(context: Context, trackUri: String) {+ if (trackUri.startsWith(YouTubeBackend.TRACK_PREFIX)) {+ remove(context, trackUri)+ } else {+ dev.lelonio.square.nativecore.NativeBridge.removeDownload(trackUri)+ }+ }++ /** Stops a song that is still coming, whichever source it belongs to. */+ fun stop(trackUri: String) {+ if (trackUri.startsWith(YouTubeBackend.TRACK_PREFIX)) {+ cancel(trackUri)+ } else {+ dev.lelonio.square.nativecore.NativeBridge.cancelDownload(trackUri)+ }+ }++ private val http = OkHttpClient.Builder()+ .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)+ .build()++ /** Songs a removal asked to stop while they were coming. */+ private val cancelled = ConcurrentHashMap.newKeySet<String>()++ /**+ * Inside the store's own folder, so emptying the downloads empties these+ * with the rest; see DownloadStore.clearAll.+ */+ private fun directory(context: Context): File =+ File(File(context.applicationContext.filesDir, DownloadStore.DIR_NAME), DownloadStore.YOUTUBE_DIR)+ .apply { mkdirs() }++ /** The finished file for a song, or null when it is not on the phone. */+ fun fileFor(context: Context, trackUri: String): File? {+ if (!trackUri.startsWith(YouTubeBackend.TRACK_PREFIX)) return null+ val id = YouTubeBackend.videoIdOfUri(trackUri)+ return directory(context).listFiles()?.firstOrNull {+ it.nameWithoutExtension == id && it.extension != PARTIAL+ }+ }++ fun cancel(trackUri: String) {+ cancelled.add(trackUri)+ }++ /** Takes the song off the phone, finished or not. */+ fun remove(context: Context, trackUri: String) {+ if (!trackUri.startsWith(YouTubeBackend.TRACK_PREFIX)) return+ val id = YouTubeBackend.videoIdOfUri(trackUri)+ directory(context).listFiles()+ ?.filter { it.name.startsWith("$id.") }+ ?.forEach { it.delete() }+ }++ /**+ * Fetches a song to the phone.+ *+ * The best audio the video has, as the player picks it. In pieces rather+ * than one request: YouTube slows a single long read of a stream down to+ * the speed it plays at, and asks by range are served at full speed.+ * Written beside its final name and renamed at the end, so a file that is+ * there is a file that is whole.+ *+ * @throws IOException for anything the network did, which is worth trying+ * again; anything else is about the song.+ */+ suspend fun download(+ context: Context,+ trackUri: String,+ onProgress: (Float) -> Unit,+ ): DownloadStore.FileRecord = withContext(Dispatchers.IO) {+ cancelled.remove(trackUri)+ YouTubeStreams.ensureNewPipe()+ val id = YouTubeBackend.videoIdOfUri(trackUri)+ val info = StreamInfo.getInfo(ServiceList.YouTube, YouTubeStreams.WATCH_URL + id)+ val stream = info.audioStreams+ .filter { !it.content.isNullOrEmpty() }+ .maxByOrNull { it.averageBitrate }+ ?: error("no audio for $id")+ val extension = stream.format?.suffix ?: "m4a"++ val dir = directory(context)+ val part = File(dir, "$id.$extension.$PARTIAL")+ val done = File(dir, "$id.$extension")+ var offset = 0L+ var total = -1L+ try {+ FileOutputStream(part, false).use { out ->+ while (total < 0 || offset < total) {+ if (trackUri in cancelled) throw kotlinx.coroutines.CancellationException("removed")+ val request = Request.Builder()+ .url(stream.content)+ .header("Range", "bytes=$offset-${offset + CHUNK_BYTES - 1}")+ .build()+ http.newCall(request).execute().use { response ->+ if (response.code != 200 && response.code != 206) {+ throw IOException("HTTP ${response.code}")+ }+ if (total < 0) {+ total = response.header("Content-Range")+ ?.substringAfterLast('/')+ ?.toLongOrNull()+ ?: -1L+ }+ val body = response.body ?: throw IOException("empty response")+ val before = offset+ body.byteStream().use { input ->+ val buffer = ByteArray(BUFFER_BYTES)+ while (true) {+ val read = input.read(buffer)+ if (read < 0) break+ out.write(buffer, 0, read)+ offset += read+ }+ }+ // The whole file in one answer, or a piece shorter than+ // asked for with no total to go by: either way there is+ // nothing left to ask for.+ if (response.code == 200 ||+ (total < 0 && offset - before < CHUNK_BYTES)+ ) {+ total = offset+ }+ }+ if (total > 0) onProgress((offset.toFloat() / total).coerceIn(0f, 1f))+ }+ }+ if (!part.renameTo(done)) throw IOException("cannot keep $id")+ } catch (t: Throwable) {+ part.delete()+ throw t+ }++ DownloadStore.FileRecord(+ trackId = id,+ format = extension,+ bytes = done.length(),+ kbps = stream.averageBitrate.takeIf { it > 0 } ?: 0,+ downloadedAt = System.currentTimeMillis(),+ )+ }++ private const val PARTIAL = "part"+ private const val READ_TIMEOUT_SECONDS = 30L++ /** Under the size YouTube starts slowing a single read down at. */+ private const val CHUNK_BYTES = 9L * 1024 * 1024+ private const val BUFFER_BYTES = 64 * 1024+}diff --git a/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt b/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.ktindex 11967f4..86ee57f 100644--- a/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt+++ b/app/src/main/java/dev/lelonio/square/playback/MediaBrowseTree.kt@@ -291,7 +291,7 @@ class MediaBrowseTree(} else {app.downloads.removeLiked(uri)app.downloads.pruneOrphans().forEach { orphanUri ->- runCatching { NativeBridge.removeDownload(orphanUri) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.forget(app, orphanUri) }dev.lelonio.square.download.DownloadExtras.forget(orphanUri)}}diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex 829423f..1183fa7 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -1069,6 +1069,27 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {* shows the same picker in its own panel and would otherwise get both.*/fun openAddToPlaylist(trackUri: String?, trackTitle: String, asSheet: Boolean = true) {+ // The other source writes through its own account, to the lists it+ // says can be written to; they are asked for as the sheet opens.+ val backend = container.activeBackend+ if (backend.id != BackendId.SPOTIFY) {+ val writable = trackUri != null && backend.owns(trackUri) && backend.canEditPlaylists+ _addToPlaylist.value = AddToPlaylistState(+ open = asSheet,+ trackUri = trackUri,+ trackTitle = trackTitle,+ error = if (writable) null else string(R.string.track_cannot_be_added),+ )+ if (writable) viewModelScope.launch {+ val lists = runCatching { backend.writablePlaylists() }+ .onFailure { android.util.Log.w(TAG, "writable playlists unavailable: ${describe(it)}") }+ .getOrDefault(emptyList())+ if (_addToPlaylist.value.trackUri == trackUri) {+ _addToPlaylist.value = _addToPlaylist.value.copy(playlists = lists)+ }+ }+ return+ }_addToPlaylist.value = AddToPlaylistState(open = asSheet,trackUri = trackUri,@@ -1103,6 +1124,28 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {if (current.busy != null) returnval id = playlist.uri.substringAfterLast(':')+ if (!playlist.uri.startsWith("spotify:")) {+ _addToPlaylist.value =+ current.copy(busy = playlist.uri, done = null, removed = null, error = null)+ viewModelScope.launch {+ runCatching { container.activeBackend.addToPlaylist(playlist.uri, trackUri) }+ .onSuccess {+ _addToPlaylist.value = _addToPlaylist.value.copy(busy = null, done = playlist.name)+ _inPlaylists.value = _inPlaylists.value + trackUri+ invalidateContext(playlist.uri)+ if (_playlist.value.uri == playlist.uri) openPlaylist(playlist)+ }+ .onFailure {+ android.util.Log.e(TAG, "add to playlist failed: ${chain(it)}", it)+ _addToPlaylist.value = _addToPlaylist.value.copy(+ busy = null,+ error = string(R.string.add_failed, playlist.name),+ )+ }+ }+ return+ }+// Liked Songs is in this list like any other, and is the one entry that// is not a playlist: it is the account's library, saved to by its own// endpoint. Picking it is what puts the heart on the track, and picking@@ -2889,7 +2932,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {} else {container.downloads.removeLiked(trackUri)container.downloads.pruneOrphans().forEach {- runCatching { NativeBridge.removeDownload(it) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.forget(getApplication(), it) }dev.lelonio.square.download.DownloadExtras.forget(it)}}@@ -3061,7 +3104,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {// JNI calls to stop the one or two that are running.val inFlight = container.downloads.progress.value.keys.toList()container.downloads.removeOwner(uri)- inFlight.forEach { runCatching { NativeBridge.cancelDownload(it) } }+ inFlight.forEach { runCatching { dev.lelonio.square.download.YouTubeDownloads.stop(it) } }sweepOrphans()} else {// The page's own cover, kept like the songs are. It is one@@ -3100,7 +3143,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {val singles = container.downloads.owners.value[DownloadStore.SINGLES].orEmpty()if (track.uri in singles) {container.downloads.removeSingle(track.uri)- runCatching { NativeBridge.cancelDownload(track.uri) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.stop(track.uri) }sweepOrphans()} else {container.downloads.addSingle(track)@@ -3124,7 +3167,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {*/private suspend fun sweepOrphans() {container.downloads.pruneOrphans().forEach {- runCatching { NativeBridge.removeDownload(it) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.forget(getApplication(), it) }dev.lelonio.square.download.DownloadExtras.forget(it)}// And whatever is left in the extras that no surviving track can@@ -3141,7 +3184,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {fun clearDownloads() {viewModelScope.launch {container.downloads.progress.value.keys.forEach {- runCatching { NativeBridge.cancelDownload(it) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.stop(it) }}container.downloads.clearAll()}@@ -3451,6 +3494,17 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {try {if (!playlist.uri.startsWith("spotify:")) {+ // Whether the account follows this artist, for the button+ // on their page. After the tracks, which read the same+ // page and leave the answer behind for this to pick up.+ if (kind == DetailKind.ARTIST) launch {+ val following = container.activeBackend.isFollowing(playlist.uri)+ ?: return@launch+ base = base.copy(following = following)+ if (isActive && _playlist.value.uri == playlist.uri) {+ _playlist.value = _playlist.value.copy(following = following)+ }+ }// 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@@ -3766,6 +3820,23 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {*/fun removeFromPlaylist(track: CatalogTrack) {val uri = _playlist.value.uri ?: return+ // The other source removes through its own account; the same+ // optimistic row going and coming back if it refuses.+ if (!uri.startsWith("spotify:") && container.activeBackend.owns(uri)) {+ val before = _playlist.value.tracks+ _playlist.value = _playlist.value.copy(tracks = before.filterNot { it.uri == track.uri })+ invalidateContext(uri)+ viewModelScope.launch {+ runCatching { container.activeBackend.removeFromPlaylist(uri, track.uri) }+ .onFailure {+ android.util.Log.e(TAG, "remove from playlist failed: ${chain(it)}", it)+ if (_playlist.value.uri == uri) {+ _playlist.value = _playlist.value.copy(tracks = before)+ }+ }+ }+ return+ }if (!uri.startsWith("spotify:playlist:")) returnval before = _playlist.value.tracks@@ -3791,6 +3862,26 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {/** Whether the active source lets the account make and change playlists. */val canEditPlaylists: Boolean get() = container.activeBackend.canEditPlaylists+ /** Whether a track can be taken out of this particular list. */+ fun canRemoveFrom(playlistUri: String?): Boolean {+ val uri = playlistUri ?: return false+ return if (uri.startsWith("spotify:")) {+ container.activeBackend.id == BackendId.SPOTIFY+ } else {+ container.activeBackend.owns(uri) && container.activeBackend.canWriteTo(uri)+ }+ }++ /** Whether the active source's pages and songs can be kept on the phone. */+ fun canKeep(uri: String?): Boolean {+ val it = uri ?: return false+ val backend = container.activeBackend+ return backend.owns(it) && when (backend.id) {+ BackendId.SPOTIFY -> it.startsWith("spotify:")+ BackendId.YOUTUBE_MUSIC -> true+ }+ }+/*** Makes a playlist and puts it at the top of the library.*@@ -4809,6 +4900,19 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {_playlist.value = _playlist.value.copy(following = !was)+ // The other source follows through its own account.+ if (!uri.startsWith("spotify:")) {+ runCatching { container.activeBackend.setFollowing(uri, !was) }+ .onSuccess { loadFollowedArtists() }+ .onFailure {+ android.util.Log.e(TAG, "follow failed: ${chain(it)}", it)+ if (_playlist.value.uri == uri) {+ _playlist.value = _playlist.value.copy(following = was)+ }+ }+ return@launch+ }+if (!container.webApi.isReady) {val currentList = _followedArtists.value.toMutableList()if (was) {@@ -4932,6 +5036,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {private fun kindOf(uri: String): DetailKind = when {uri.startsWith("spotify:artist:") -> DetailKind.ARTIST+ // An artist on the other source is an artist too: the page they open on+ // is the one with the follow button, whichever catalogue they are from.+ uri.startsWith(dev.lelonio.square.backend.youtube.YouTubeBackend.ARTIST_PREFIX) ->+ DetailKind.ARTISTuri.startsWith("spotify:album:") -> DetailKind.ALBUMelse -> DetailKind.PLAYLIST}diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex c853283..8712494 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -1875,14 +1875,13 @@ fun SquareApp(trackMenu = TrackMenuRequest(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.+ // something taken out of it, and+ // only one the account can write+ // to: on YouTube Music the library+ // also holds lists it only saved.removable = page.kind ==MainViewModel.DetailKind.PLAYLIST &&- backend ==- dev.lelonio.square.backend.BackendId.SPOTIFY,+ viewModel.canRemoveFrom(page.uri),)},storedSort = trackSort,@@ -1900,14 +1899,12 @@ fun SquareApp(?.let { downloadOwners[it] }?: dev.lelonio.square.data.OwnerState.None,onToggleDownload = { viewModel.toggleDownload(page) },- // The store belongs to the librespot engine,- // so only Spotify pages can be kept — and- // with no network the button would only ever- // queue work that cannot start.- canDownload = backend ==- dev.lelonio.square.backend.BackendId.SPOTIFY &&- page.uri?.startsWith("spotify:") == true &&- !offlineNow,+ // Pages of the source that is playing, on+ // either source now: Spotify's through its+ // engine, YouTube Music's as files of their+ // own. With no network the button would only+ // ever queue work that cannot start.+ canDownload = viewModel.canKeep(page.uri) && !offlineNow,onToggleFollow = viewModel::toggleFollowArtist,onToggleLatestSaved = viewModel::toggleLatestSaved,onToggleSaved = viewModel::toggleSaved,@@ -2986,7 +2983,15 @@ fun SquareApp(asSheet = false,)},- onToggleLike = playback.mediaId?.let { uri ->+ // The heart is Spotify's library. On the other+ // source the button is a plus instead and opens+ // the lists, liked songs among them.+ onToggleLike = playback.mediaId+ ?.takeIf {+ it.startsWith("spotify:") &&+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY+ }+ ?.let { uri ->{viewModel.toggleLike(uri,@@ -2999,7 +3004,9 @@ fun SquareApp(addToPlaylist = addToPlaylist,onPickPlaylist = viewModel::addToPlaylist,playlistEditAvailable =- backend == dev.lelonio.square.backend.BackendId.SPOTIFY,+ backend == dev.lelonio.square.backend.BackendId.SPOTIFY ||+ (viewModel.canEditPlaylists && !offlineNow &&+ playback.mediaId?.startsWith("ytmusic:track:") == true),onWatchVideo = player?.takeIf {// A video is streamed, so there is@@ -3085,17 +3092,16 @@ fun SquareApp(// three you press while listening. This is a decision// about storage, which is what a menu is for.//- // The store belongs to the librespot engine, so only- // Spotify pages can be kept — and with no network the- // entry would only ever queue work that cannot start.+ // Pages of the source that is playing can be kept,+ // and with no network the entry would only ever queue+ // work that cannot start.//// Offered only for the page that is open, because// keeping one means keeping its songs and the track list// is what this reads: the same sheet opens over a// library row, where there is a name and nothing to// fetch yet.- val keepable = backend == dev.lelonio.square.backend.BackendId.SPOTIFY &&- shownPlaylist.uri.startsWith("spotify:") &&+ val keepable = viewModel.canKeep(shownPlaylist.uri) &&playlist.uri == shownPlaylist.uri &&playlist.tracks.isNotEmpty() &&// An artist page has no keep button of its own: its@@ -3234,10 +3240,12 @@ fun SquareApp(trackMenu = nullonEnqueue(menu.track)}- // Writing to a playlist is the Spotify Web API's; on- // another source, or with no network, the entry would- // only ever fail.- if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY && !offlineNow) {+ // Writing to a playlist needs the account: Spotify's+ // Web API, or a signed-in YouTube Music. With no+ // network the entry would only ever fail.+ if ((backend == dev.lelonio.square.backend.BackendId.SPOTIFY ||+ viewModel.canEditPlaylists) && !offlineNow+ ) {TrackSheetAction(stringResource(R.string.add_to_playlist), PhosphorIcons.Regular.Plus) {trackMenu = nullviewModel.openAddToPlaylist(menu.track.uri, menu.track.name)@@ -3260,8 +3268,7 @@ fun SquareApp(}}// Keeping one song, as opposed to keeping the list it- // came from. Spotify only: this is the engine's own- // store, and the other backend streams from elsewhere.+ // came from, on whichever source it belongs to.// Removing is offered only for a song kept on its// own. One that is here because a playlist wants it// cannot be let go of from this menu — the file is@@ -3270,7 +3277,7 @@ fun SquareApp(// worse than no row.val onItsOwn = menu.track.uri in downloadSinglesval here = menu.track.uri in downloadedFiles- if (backend == dev.lelonio.square.backend.BackendId.SPOTIFY &&+ if (viewModel.canKeep(menu.track.uri) &&(onItsOwn || (!here && !offlineNow))) {val kept = onItsOwndiff --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 edfb19e..e0114a1 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@@ -1223,15 +1223,28 @@ fun PlayerScreen(}},) {+ // A heart where a tap likes the song, a plus+ // where the tap opens the lists instead: the+ // picture says what pressing it does.+ val hearts = onToggleLike != nullIcon(- if (inLikedSongs) PhosphorIcons.Fill.Heart else PhosphorIcons.Regular.Heart,+ when {+ !hearts -> PhosphorIcons.Regular.Plus+ inLikedSongs -> PhosphorIcons.Fill.Heart+ else -> PhosphorIcons.Regular.Heart+ },contentDescription = stringResource(- if (inLikedSongs) R.string.remove_from_liked else R.string.liked_songs,+ when {+ !hearts -> R.string.add_to_playlist+ inLikedSongs -> R.string.remove_from_liked+ else -> R.string.liked_songs+ },),tint = when {panel == PlayerPanel.ADD_TO_PLAYLIST ->panelTint(true)- inLikedSongs -> SavedInk+ hearts && inLikedSongs -> SavedInk+ !hearts && alreadySaved -> SavedInkelse -> panelTint(false)},modifier = Modifier.size(20.dp),diff --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 ffb2b97..445c6d4 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@@ -980,7 +980,7 @@ private fun DownloadsSection(backdrop: Backdrop) {scope.launch {store.removeOwner(dev.lelonio.square.data.DownloadStore.LIKED)store.pruneOrphans().forEach { orphanUri ->- runCatching { dev.lelonio.square.nativecore.NativeBridge.removeDownload(orphanUri) }+ runCatching { dev.lelonio.square.download.YouTubeDownloads.forget(context, orphanUri) }dev.lelonio.square.download.DownloadExtras.forget(orphanUri)}}