Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Files on the phone go into Spotify playlists from Square

Lelonio456705ea4a61
diff --git a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
index b0eecb9..be534fe 100644
--- a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
+++ b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
@@ -85,6 +85,17 @@ object LocalLibrary {
fun isSpotifyLocal(uri: String): Boolean = uri.startsWith(SPOTIFY_PREFIX)
+ /**
+ * How a file on this phone is written into a Spotify playlist, the way
+ * Spotify's own apps write one: its tags, each URL-encoded with `+` for a
+ * space, and its length in whole seconds.
+ */
+ fun spotifyUri(file: CatalogTrack): String {
+ fun part(text: String) = java.net.URLEncoder.encode(text, "UTF-8")
+ return SPOTIFY_PREFIX + listOf(file.artist, file.album, file.name).joinToString(":") { part(it) } +
+ ":" + file.durationMs / 1000
+ }
+
/**
* The file on this phone that a playlist's local entry describes, or null.
*
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index 6f97a8f..b892a87 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -210,6 +210,12 @@ object NativeBridge {
*/
fun setLocalFiles(json: String) = nativeSetLocalFiles(json)
+ /**
+ * Appends an item to one of the user's playlists through the playlist
+ * service: how a local file goes in, which the Web API refuses. Blocking.
+ */
+ fun addToPlaylist(playlistUri: String, itemUri: String) = nativeAddToPlaylist(playlistUri, itemUri)
+
/**
* How long a track the listener changes away from dissolves into the one
* they asked for, in milliseconds. Zero cuts, as it always did.
@@ -506,6 +512,7 @@ object NativeBridge {
private external fun nativeSetHoldEnd(enabled: Boolean)
private external fun nativeSetSleepTimer(value: Long)
private external fun nativeSetLocalFiles(json: String)
+ private external fun nativeAddToPlaylist(playlistUri: String, itemUri: String)
private external fun nativeSetSkipFade(ms: Int)
private external fun nativeSetLanguage(language: String, rebuild: Int)
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 6e91155..2ca6517 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -1161,7 +1161,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
playlists = (_state.value as? UiState.Ready)?.playlists.orEmpty(),
liked = trackUri != null && container.likedStore.isLiked(trackUri),
error = when {
- trackUri?.startsWith("spotify:track:") != true ->
+ trackUri == null || !(trackUri.startsWith("spotify:track:") ||
+ LocalLibrary.isLocal(trackUri) || LocalLibrary.isSpotifyLocal(trackUri)) ->
string(R.string.track_cannot_be_added)
!container.webApi.isReady && !container.tokenStore.isLoggedIn ->
string(R.string.connect_app_in_settings)
@@ -1182,6 +1183,54 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
}
+ /**
+ * A file on this phone, or a playlist's local entry, put into a playlist.
+ *
+ * Written as Spotify's own apps write it — a `spotify:local:` entry built
+ * from the file's tags — and through the playlist service, since the Web
+ * API refuses anything that is not a catalogue track. Every device of the
+ * account then shows it, playable wherever there is a matching file.
+ */
+ private fun addLocalToPlaylist(playlist: CatalogPlaylist, trackUri: String) {
+ _addToPlaylist.value = _addToPlaylist.value.copy(busy = playlist.uri, done = null, removed = null, error = null)
+ viewModelScope.launch {
+ runCatching {
+ val entry = if (LocalLibrary.isSpotifyLocal(trackUri)) {
+ trackUri
+ } else {
+ val files = deviceFiles.ifEmpty { LocalLibrary.tracks(getApplication()).also { deviceFiles = it } }
+ val file = files.firstOrNull { it.uri == trackUri } ?: error("$trackUri is not on this phone")
+ LocalLibrary.spotifyUri(file).also { uri ->
+ // Playable at once from the playlist, without waiting
+ // for its page to be matched again.
+ file.localFile?.let { path ->
+ engineLocalFiles[uri] = path
+ runCatching {
+ dev.lelonio.square.nativecore.NativeBridge.setLocalFiles(
+ org.json.JSONObject(engineLocalFiles.toMap()).toString(),
+ )
+ }
+ }
+ }
+ }
+ withContext(Dispatchers.IO) {
+ dev.lelonio.square.nativecore.NativeBridge.addToPlaylist(playlist.uri, entry)
+ }
+ }.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 local file to playlist failed: ${chain(it)}", it)
+ _addToPlaylist.value = _addToPlaylist.value.copy(
+ busy = null,
+ error = string(R.string.add_failed, playlist.name),
+ )
+ }
+ }
+ }
+
fun closeAddToPlaylist() {
_addToPlaylist.value = _addToPlaylist.value.copy(open = false)
}
@@ -1200,6 +1249,13 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (current.busy != null) return
val id = playlist.uri.substringAfterLast(':')
+ if (playlist.uri.startsWith("spotify:playlist:") &&
+ (LocalLibrary.isLocal(trackUri) || LocalLibrary.isSpotifyLocal(trackUri))
+ ) {
+ addLocalToPlaylist(playlist, trackUri)
+ return
+ }
+
if (!playlist.uri.startsWith("spotify:")) {
_addToPlaylist.value =
current.copy(busy = playlist.uri, done = null, removed = null, error = null)
diff --git a/native/src/catalog.rs b/native/src/catalog.rs
index f654191..5a33aa5 100644
--- a/native/src/catalog.rs
+++ b/native/src/catalog.rs
@@ -789,3 +789,76 @@ fn read_first_message_field(bytes: &[u8], field: u32) -> Option<&[u8]> {
}
None
}
+
+/// Appends one item to one of the user's playlists, through the playlist
+/// service rather than the Web API.
+///
+/// For the one kind of item the Web API refuses: a local file, written as
+/// `spotify:local:artist:album:title:seconds`, which is how Spotify's own apps
+/// put one in a playlist. The change is the same ADD those apps send, at the
+/// end of the list and against its current revision.
+pub fn add_to_playlist(playlist_uri: &str, item_uri: &str) -> EngineResult<()> {
+ use librespot_protocol::playlist4_external::{
+ op::Kind, Add, Delta, Item, ItemAttributes, ListChanges, Op,
+ };
+
+ let parsed = SpotifyUri::from_uri(playlist_uri).map_err(|e| format!("bad uri: {e}"))?;
+ let SpotifyUri::Playlist { id, .. } = parsed else {
+ return Err(format!("{playlist_uri} is not a playlist"));
+ };
+ let base62 = id.to_base62().map_err(|e| format!("bad playlist id: {e}"))?;
+
+ let session = with_session(|s| s.clone())?;
+ block_on(async move {
+ let bytes = session
+ .spclient()
+ .get_playlist(&id)
+ .await
+ .map_err(|e| format!("playlist read failed: {e}"))?;
+ let list = SelectedListContent::parse_from_bytes(&bytes)
+ .map_err(|e| format!("playlist was not a SelectedListContent: {e}"))?;
+
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as i64)
+ .unwrap_or_default();
+
+ // Only the moment it went in: who added it is the session's, and the
+ // service fills it in itself. Sent, it was refused as an invalid
+ // argument.
+ let mut attributes = ItemAttributes::new();
+ attributes.set_timestamp(now);
+ let mut item = Item::new();
+ item.set_uri(item_uri.to_string());
+ item.attributes = Some(attributes).into();
+
+ // At the end, said once: an index as well as "last" is two positions.
+ let mut add = Add::new();
+ add.items.push(item);
+ add.set_add_last(true);
+
+ let mut op = Op::new();
+ op.set_kind(Kind::ADD);
+ op.add = Some(add).into();
+
+ let mut delta = Delta::new();
+ delta.ops.push(op);
+
+ let mut changes = ListChanges::new();
+ changes.set_base_revision(list.revision().to_vec());
+ changes.deltas.push(delta);
+ changes.set_want_resulting_revisions(true);
+
+ session
+ .spclient()
+ .request_with_protobuf(
+ &Method::POST,
+ &format!("/playlist/v2/playlist/{base62}/changes"),
+ None,
+ &changes,
+ )
+ .await
+ .map_err(|e| format!("playlist change refused: {e}"))?;
+ Ok(())
+ })
+}
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index c520889..d85e466 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -409,6 +409,23 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePla
guard_string(&mut env, "PlaylistName", || catalog::playlist_name(&uri))
}
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeAddToPlaylist(
+ mut env: JNIEnv,
+ _class: JClass,
+ playlist: JString,
+ item: JString,
+) {
+ let (playlist, item) = match (read_string(&mut env, &playlist), read_string(&mut env, &item)) {
+ (Ok(playlist), Ok(item)) => (playlist, item),
+ (Err(message), _) | (_, Err(message)) => {
+ let _ = env.throw_new(EXCEPTION, message);
+ return;
+ }
+ };
+ guard(&mut env, "AddToPlaylist", || catalog::add_to_playlist(&playlist, &item));
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaylistCover(
mut env: JNIEnv,