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.

21.7 KB
Raw Blame
package dev.lelonio.square.data

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.HTTP
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query

/**
 * The subset of the Web API this client uses.
 *
 * The Web API supplies every piece of metadata — search, library, playlists,
 * artwork. It cannot supply audio; that is the native engine's job. Keeping the
 * two strictly separated is what stops the "metadata says one thing, player says
 * another" desync that plagues the existing clients.
 */
interface SpotifyApi {

    @GET("v1/me")
    suspend fun me(): UserDto

    /**
     * Whether each of these tracks is in the account's Liked Songs.
     *
     * The answers come back in the order asked, as bare booleans.
     */
    @GET("v1/me/tracks/contains")
    suspend fun tracksAreSaved(@Query("ids") ids: String): List<Boolean>

    @GET("v1/me/tracks")
    suspend fun savedTracks(
        @Query("limit") limit: Int = 50,
        @Query("offset") offset: Int = 0,
    ): PageDto<SavedTrackDto>

    /** The albums the account has saved, which the library shows beside playlists. */
    @GET("v1/me/albums")
    suspend fun savedAlbums(
        @Query("limit") limit: Int = 50,
        @Query("offset") offset: Int = 0,
    ): PageDto<SavedAlbumDto>

    @GET("v1/me/playlists")
    suspend fun playlists(
        @Query("limit") limit: Int = 50,
        @Query("offset") offset: Int = 0,
    ): PageDto<PlaylistDto>

    /**
     * A page of a playlist's tracks.
     *
     * `market` is not optional in practice. Without it the response carries each
     * track's *original* URI, and a large share of the catalogue is region-split:
     * the original is not playable here and the engine skips straight past it —
     * which looks exactly like a player that will not play anything. With a
     * market Spotify relinks each track to the copy licensed for this account,
     * and `is_playable` becomes meaningful.
     */
    // `/items` since Spotify's migration of March 2026, which took `/tracks`
    // away from Development Mode apps; see PlaylistTrackDto for the field that
    // moved with it.
    @GET("v1/playlists/{id}/items")
    suspend fun playlistTracks(
        @Path("id") playlistId: String,
        @Query("limit") limit: Int = 100,
        @Query("offset") offset: Int = 0,
        @Query("market") market: String = "from_token",
    ): PageDto<PlaylistTrackDto>

    /**
     * The playlist's version stamp, and nothing else.
     *
     * `snapshot_id` changes whenever the contents do, so this one small request
     * answers "is the copy on disk still right?" — which is what lets a
     * thousand-track playlist open without re-reading a dozen pages of it.
     * `fields` keeps the response to the two values that matter instead of the
     * whole playlist with its first hundred tracks inside.
     */
    @GET("v1/playlists/{id}")
    suspend fun playlistSnapshot(
        @Path("id") playlistId: String,
        @Query("fields") fields: String = "snapshot_id,tracks(total)",
    ): PlaylistSnapshotDto

    /**
     * Albums and singles released recently.
     *
     * Not personalised — Spotify's own recommendation endpoints were closed to
     * new applications, so this is the closest thing still open, and it is the
     * catalogue's front page rather than the user's. What makes the home feed
     * personal is what surrounds it: their own top artists, their playlists and
     * what they actually played.
     */
    @GET("v1/browse/new-releases")
    suspend fun newReleases(
        @Query("limit") limit: Int = 12,
        /** Fifty at a time is this endpoint's maximum, so more means paging. */
        @Query("offset") offset: Int = 0,
    ): NewReleasesDto

    /** Needs the `user-top-read` scope; 403 without it. */
    @GET("v1/me/top/artists")
    suspend fun topArtists(
        @Query("limit") limit: Int = 12,
        /** `short_term` is roughly the last month, which is what "lately" means. */
        @Query("time_range") timeRange: String = "short_term",
    ): PageDto<ArtistDto>

    /**
     * The account's own most-played tracks. Same scope as the artists above.
     *
     * The time range is the whole point of having both: `short_term` is what is
     * on repeat now, `long_term` is what the account has always come back to,
     * and they are rarely the same list.
     */
    @GET("v1/me/top/tracks")
    suspend fun topTracks(
        @Query("limit") limit: Int = 20,
        @Query("time_range") timeRange: String = "short_term",
    ): PageDto<TrackDto>

    /**
     * What the account played last, wherever it played it.
     *
     * Different from the app's own recent list, which only knows what was
     * played here: this is the phone, the desktop and the speaker together.
     * Needs `user-read-recently-played`.
     */
    @GET("v1/me/player/recently-played")
    suspend fun recentlyPlayed(
        @Query("limit") limit: Int = 30,
        @Query("before") before: Long? = null,
    ): PageDto<PlayHistoryDto>

    /**
     * An artist's most-played tracks.
     *
     * The access point serves playlists and albums as contexts, but an artist is
     * not a context — there is no track list to resolve — so this one has to go
     * through the Web API and therefore needs the user's own application.
     *
     * `from_token` picks the market from the logged-in account; without a market
     * the endpoint answers 400.
     */
    @GET("v1/artists/{id}/top-tracks")
    suspend fun artistTopTracks(
        @Path("id") artistId: String,
        @Query("market") market: String,
    ): TopTracksDto

    @GET("v1/artists/{id}/albums")
    suspend fun artistAlbums(
        @Path("id") artistId: String,
        @Query("include_groups") groups: String = "album,single",
        @Query("limit") limit: Int = 20,
        @Query("market") market: String? = null,
        @Query("offset") offset: Int = 0,
    ): PageDto<AlbumDto>

    @GET("v1/artists/{id}/related-artists")
    suspend fun artistRelatedArtists(@Path("id") artistId: String): RelatedArtistsDto

    /**
     * The three below exist for one field each: the picture at the top of a
     * page opened by name alone.
     *
     * Most of the app reaches a playlist or an artist through a row that
     * already carries its image. A tap on the player's own text does not: all
     * it has is the URI, so the page has to go and ask.
     */
    @GET("v1/artists/{id}")
    suspend fun artist(@Path("id") artistId: String): ArtistDto

    @GET("v1/albums/{id}")
    suspend fun album(@Path("id") albumId: String): AlbumDto

    /**
     * One track, for the record it is on.
     *
     * The access point names a track's album but does not always address it —
     * and a queue resolved before the app started keeping that address has none
     * at all. This is the way back to it from the track alone.
     */
    @GET("v1/tracks/{id}")
    suspend fun track(@Path("id") trackId: String): TrackDto

    @GET("v1/playlists/{id}")
    suspend fun playlist(
        @Path("id") playlistId: String,
        @Query("fields") fields: String = "id,uri,name,images,description",
    ): PlaylistDto

    /**
     * Every device the account can currently play on.
     *
     * The Web API rather than the access point: librespot's Connect state keeps
     * the cluster — which is exactly this list — inside its own event loop, with
     * no public accessor, so reading it there would mean patching the crate.
     *
     * Needs `user-read-playback-state`.
     */
    @GET("v1/me/player/devices")
    suspend fun devices(): DevicesDto

    /** Moves playback to another device. Needs `user-modify-playback-state`. */
    @PUT("v1/me/player")
    suspend fun transferPlayback(@Body request: TransferRequestDto)

    /**
     * Resumes on a named device.
     *
     * The device is named rather than assumed. Spotify's play endpoint acts on
     * "the active device", and just after a handover there is a moment where
     * the account has not settled on one: the request then answers 404, whose
     * message is the same for "device not found" and "nothing is active".
     * Saying which device removes the question.
     */
    @PUT("v1/me/player/play")
    suspend fun play(@Query("device_id") deviceId: String)

    /**
     * Appends tracks to a playlist. Needs `playlist-modify-private` for the
     * user's own private playlists and `playlist-modify-public` for their
     * public ones — which one applies is the playlist's visibility, not the
     * caller's, so both are asked for.
     */
    @POST("v1/playlists/{id}/items")
    suspend fun addToPlaylist(
        @Path("id") playlistId: String,
        @Body request: AddTracksRequestDto,
    )

    /**
     * Removes every occurrence of the given tracks from a playlist.
     *
     * Every occurrence: pinning it to one position needs the playlist's
     * snapshot id, and a playlist holding the same track twice is rare enough
     * that carrying snapshot state around for it is not worth the failure modes.
     *
     * `@HTTP` rather than `@DELETE` because this one carries a body, which
     * Retrofit's `@DELETE` does not allow.
     *
     * `/items`, and `items` in the body, since the migration of March 2026. The
     * old address still answers 200 to a Development Mode app and takes nothing
     * out, which is how a song ticked off in the player stayed in the list.
     */
    @HTTP(method = "DELETE", path = "v1/playlists/{id}/items", hasBody = true)
    suspend fun removeFromPlaylist(
        @Path("id") playlistId: String,
        @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

    /**
     * Replaces a playlist's cover with a JPEG, sent as base64 text of at most
     * 256 KB. Needs `ugc-image-upload`, which an application connected before
     * Square asked for it does not have: that answers 401 or 403.
     */
    @PUT("v1/playlists/{id}/images")
    @retrofit2.http.Headers("Content-Type: image/jpeg")
    suspend fun uploadPlaylistCover(
        @Path("id") playlistId: String,
        @Body jpegBase64: okhttp3.RequestBody,
    )

    /** 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)

    /**
     * Following an artist, exactly as the green button does.
     *
     * Needs `user-follow-modify`, and its sibling below needs
     * `user-follow-read`. An account connected before those existed keeps
     * working everywhere else and is told to reconnect only here, where the
     * permission is actually missing.
     */
    @PUT("v1/me/following")
    suspend fun followArtists(
        @Query("type") type: String = "artist",
        @Query("ids") ids: String,
        @Body request: IdsDto = IdsDto(ids.split(",").map { it.trim() }),
    )

    @HTTP(method = "DELETE", path = "v1/me/following", hasBody = true)
    suspend fun unfollowArtists(
        @Query("type") type: String = "artist",
        @Query("ids") ids: String,
        @Body request: IdsDto = IdsDto(ids.split(",").map { it.trim() }),
    )

    @GET("v1/me/following/contains")
    suspend fun isFollowing(
        @Query("type") type: String = "artist",
        @Query("ids") ids: String,
    ): List<Boolean>

    /**
     * The artists the account follows.
     *
     * Cursor-paged rather than offset-paged, alone among the endpoints this app
     * reads: the answer carries the id to continue after.
     */
    @GET("v1/me/following")
    suspend fun followedArtists(
        @Query("type") type: String = "artist",
        @Query("limit") limit: Int = 50,
        @Query("after") after: String? = null,
    ): FollowedArtistsDto

    /**
     * Keeping a playlist, and keeping an album, which Spotify calls two
     * different things: a playlist is followed and an album is saved. Same
     * button on the page, two endpoints underneath.
     */
    @PUT("v1/playlists/{id}/followers")
    suspend fun followPlaylist(
        @Path("id") playlistId: String,
        @Body request: FollowPlaylistRequestDto = FollowPlaylistRequestDto(),
    )

    @GET("v1/playlists/{id}/followers/contains")
    suspend fun playlistIsFollowed(
        @Path("id") playlistId: String,
        @Query("ids") userIds: String,
    ): List<Boolean>

    companion object {
        val EMPTY_BODY: RequestBody = ByteArray(0).toRequestBody("application/json".toMediaType())
    }

    /** Unified Spotify Library endpoints (matching fastpotify) */
    @PUT("v1/me/library")
    suspend fun saveToLibrary(
        @Query("uris") uris: String,
        @Body body: RequestBody = EMPTY_BODY,
    )

    @DELETE("v1/me/library")
    suspend fun removeFromLibrary(@Query("uris") uris: String)

    @GET("v1/me/library/contains")
    suspend fun libraryContains(@Query("uris") uris: String): List<Boolean>

    /** Saves tracks to Liked Songs (Canciones que te gustan). */
    @PUT("v1/me/tracks")
    suspend fun saveTracks(
        @Query("ids") ids: String,
        @Body body: RequestBody = EMPTY_BODY,
    )

    @PUT("v1/me/tracks")
    suspend fun saveTracksWithBody(
        @Body request: IdsDto,
    )

    /** And takes them out again. */
    @DELETE("v1/me/tracks")
    suspend fun removeSavedTracks(
        @Query("ids") ids: String,
    )

    @HTTP(method = "DELETE", path = "v1/me/tracks", hasBody = true)
    suspend fun removeSavedTracksWithBody(
        @Body request: IdsDto,
    )

    @PUT("v1/me/albums")
    suspend fun saveAlbums(
        @Query("ids") ids: String,
        @Body body: RequestBody = EMPTY_BODY,
    )

    @DELETE("v1/me/albums")
    suspend fun removeAlbums(
        @Query("ids") ids: String,
    )

    @GET("v1/me/albums/contains")
    suspend fun albumsAreSaved(@Query("ids") ids: String): List<Boolean>

    @GET("v1/search")
    suspend fun search(
        @Query("q") query: String,
        @Query("type") type: String = "track,album,artist,playlist",
        /** Fifty is this endpoint's maximum, and the fallback should not be thinner. */
        @Query("limit") limit: Int = 40,
        /** Where the page starts, for a second helping of the same search. */
        @Query("offset") offset: Int = 0,
    ): SearchDto
}


@Serializable
data class IdsDto(val ids: List<String>)

@Serializable
data class FollowPlaylistRequestDto(val public: Boolean = false)

@Serializable
data class AddTracksRequestDto(val uris: List<String>)

/** What a playlist is created or renamed with. */
@Serializable
data class PlaylistDetailsDto(
    val name: String,
    /**
     * Null to leave it as it is. Not a plain false: a value equal to its
     * default is not written out, and Spotify reads a missing `public` on a
     * new playlist as true, so "private" used to make a public one.
     */
    @SerialName("public") val isPublic: Boolean? = null,
    /** Null to leave it as it is; empty to clear it. */
    val description: String? = null,
)

@Serializable
data class RemoveTracksRequestDto(@SerialName("items") val tracks: List<TrackUriDto>)

@Serializable
data class TrackUriDto(val uri: String)

@Serializable
data class PageDto<T>(
    val items: List<T>,
    val total: Int = 0,
    val next: String? = null,
)

@Serializable
data class UserDto(
    val id: String,
    @SerialName("display_name") val displayName: String? = null,
    /** `premium` or `free`; the engine only works for the former. */
    val product: String? = null,
    val country: String? = null,
    val images: List<ImageDto> = emptyList(),
)

@Serializable
data class SavedTrackDto(
    @SerialName("added_at") val addedAt: String? = null,
    val track: TrackDto,
)

@Serializable
data class PlaylistSnapshotDto(
    @SerialName("snapshot_id") val snapshotId: String? = null,
    val tracks: TotalDto? = null,
)

@Serializable
data class TotalDto(val total: Int = 0)

@Serializable
data class PlaylistTrackDto(
    /**
     * Null for episodes and for tracks removed from the catalogue.
     *
     * `item` on the wire since the migration of March 2026, where `track` was
     * left behind as a boolean saying whether the item is one.
     */
    @SerialName("item") val track: TrackDto? = null,
    /** ISO-8601, and absent on playlists old enough to predate the field. */
    @SerialName("added_at") val addedAt: String? = null,
)

@Serializable
data class TrackDto(
    val id: String? = null,
    val uri: String,
    val name: String,
    @SerialName("duration_ms") val durationMs: Long = 0,
    @SerialName("is_playable") val isPlayable: Boolean? = null,
    val explicit: Boolean = false,
    val artists: List<ArtistDto> = emptyList(),
    val album: AlbumDto? = null,
)

@Serializable
data class ArtistDto(
    val id: String? = null,
    val uri: String? = null,
    val name: String,
    val images: List<ImageDto> = emptyList(),
    /** How many accounts follow them; the number under the name. */
    val followers: FollowersDto? = null,
    /** Spotify's own labels for them, lowercase and often several. */
    val genres: List<String> = emptyList(),
)

@Serializable
data class FollowersDto(val total: Int = 0)

/** The cursor-paged shape `me/following` answers with, and nothing else does. */
@Serializable
data class FollowedArtistsDto(val artists: ArtistCursorPageDto = ArtistCursorPageDto())

@Serializable
data class ArtistCursorPageDto(
    val items: List<ArtistDto> = emptyList(),
    val total: Int = 0,
    val cursors: CursorsDto? = null,
)

@Serializable
data class CursorsDto(val after: String? = null)

/** One row of `me/albums`: the album, plus when it was saved. */
@Serializable
data class SavedAlbumDto(
    val album: AlbumDto,
    @SerialName("added_at") val addedAt: String? = null,
)

@Serializable
data class AlbumDto(
    val id: String? = null,
    val uri: String? = null,
    val name: String,
    val images: List<ImageDto> = emptyList(),
    /**
     * Which shelf it belongs on for the artist it was asked about: `album`,
     * `single`, `compilation` or `appears_on`. Only `artists/{id}/albums`
     * fills it, which is the one place it is needed.
     */
    @SerialName("album_group") val albumGroup: String? = null,
    @SerialName("album_type") val albumType: String? = null,
    /** ISO date, and not always a full one — Spotify returns bare years too. */
    @SerialName("release_date") val releaseDate: String? = null,
    @SerialName("total_tracks") val totalTracks: Int = 0,
    /** Present on browse and search results, absent when an album is nested in a track. */
    val artists: List<ArtistDto> = emptyList(),
)

@Serializable
data class TopTracksDto(val tracks: List<TrackDto> = emptyList())

@Serializable
data class RelatedArtistsDto(val artists: List<ArtistDto> = emptyList())

/** One entry of the account's play history: the track and where it was played from. */
@Serializable
data class PlayHistoryDto(
    val track: TrackDto,
    @SerialName("played_at") val playedAt: String? = null,
    val context: PlayContextDto? = null,
)

@Serializable
data class PlayContextDto(val uri: String? = null, val type: String? = null)

@Serializable
data class NewReleasesDto(val albums: PageDto<AlbumDto>? = null)

@Serializable
data class DevicesDto(val devices: List<DeviceDto> = emptyList())

@Serializable
data class DeviceDto(
    /** Null for a device the account can see but not address, which is not playable. */
    val id: String? = null,
    val name: String,
    /** `Computer`, `Smartphone`, `Speaker`, `TV`, … */
    val type: String = "",
    @SerialName("is_active") val isActive: Boolean = false,
    @SerialName("is_restricted") val isRestricted: Boolean = false,
    @SerialName("volume_percent") val volumePercent: Int? = null,
)

@Serializable
data class TransferRequestDto(
    @SerialName("device_ids") val deviceIds: List<String>,
    /**
     * Keeps playing after the move. False would transfer *and* pause, which is
     * never what picking a device from a player means.
     */
    val play: Boolean = true,
)

@Serializable
data class PlaylistDto(
    val id: String,
    val uri: String,
    val name: String,
    val description: String? = null,
    val images: List<ImageDto> = emptyList(),
    /** Asked for only where it matters; see MusicBackend.playlistDetails. */
    val public: Boolean? = null,
    val tracks: PlaylistTracksRefDto? = null,
    /**
     * Who made it. The one field that tells "This Is Fabri Fibra", which
     * Spotify itself built, from a playlist a stranger named the same thing.
     */
    val owner: OwnerDto? = null,
)

@Serializable
data class OwnerDto(
    val id: String? = null,
    @SerialName("display_name") val displayName: String? = null,
)

@Serializable
data class PlaylistTracksRefDto(val total: Int = 0)

@Serializable
data class ImageDto(val url: String, val width: Int? = null, val height: Int? = null)

@Serializable
data class SearchDto(
    val tracks: PageDto<TrackDto>? = null,
    val albums: PageDto<AlbumDto>? = null,
    val artists: PageDto<ArtistDto>? = null,
    val playlists: PageDto<PlaylistDto?>? = null,
)