webspotify

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: GPL-3.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package webspotify implements Spotify's documented OAuth and Web API flows without depending on the desktop player's private services.

Index

Constants

View Source
const (
	SDKReady          = "ready"
	SDKNotReady       = "not_ready"
	SDKStateChanged   = "player_state_changed"
	SDKInitError      = "initialization_error"
	SDKAuthError      = "authentication_error"
	SDKAccountError   = "account_error"
	SDKPlaybackError  = "playback_error"
	SDKAutoplayFailed = "autoplay_failed"
)
View Source
const (
	DefaultAPIBase = "https://api.spotify.com/v1"
	AuthorizeURL   = "https://accounts.spotify.com/authorize"
	TokenURL       = "https://accounts.spotify.com/api/token"
)

Variables

View Source
var ErrAuthState = errors.New("spotify auth: state check failed")
View Source
var ErrNoToken = errors.New("spotify auth: no refreshable token")
View Source
var Scopes = []string{
	"playlist-read-private",
	"playlist-read-collaborative",
	"user-read-private",
	"user-library-read",
	"user-library-modify",
	"user-read-recently-played",
	"user-read-playback-state",
	"user-modify-playback-state",
	"streaming",
}

Scopes is the documented access needed for browsing and Connect playback.

Functions

func MapSDKError

func MapSDKError(kind, message string) model.Event

MapSDKError gives SDK errors a predictable app-level kind, including Premium-account failures.

func MapSDKState

func MapSDKState(state SDKState) []model.Event

MapSDKState converts a browser player state into the same events used by the desktop player. It has no DOM or syscall/js dependency.

func PKCEChallenge

func PKCEChallenge(verifier string) string

PKCEChallenge returns the RFC 7636 S256 challenge for verifier.

Types

type API

type API struct {
	Auth          *Auth
	Transport     Transport
	BaseURL       string
	Now           func() time.Time
	Wait          func(context.Context, time.Duration) error
	Max429Retries int
}

API is an OAuth-authorized Spotify Web API client.

func NewAPI

func NewAPI(auth *Auth, transport Transport) *API

func (*API) AddToQueue

func (c *API) AddToQueue(ctx context.Context, deviceID, uri string) error

func (*API) Album

func (c *API) Album(ctx context.Context, uri string) (catalog.AlbumDetails, error)

Album loads a documented album resource and its track listing.

func (*API) Artist

func (c *API) Artist(ctx context.Context, uri string) (catalog.ArtistOverview, error)

Artist loads artist metadata. The Web API's artist top-tracks endpoint is unavailable to current Development Mode apps, so no unofficial substitute is queried.

func (*API) ContextTracks

func (c *API) ContextTracks(ctx context.Context, uri string) (model.Listing, error)

ContextTracks reads saved tracks, album tracks, or playlist items. The playlist endpoint is the documented /items route.

func (*API) Home

func (c *API) Home(ctx context.Context) (catalog.HomeFeed, error)

Home builds a small documented Home shelf from the user's own playlists.

func (*API) Liked

func (c *API) Liked(ctx context.Context, uris []string) ([]bool, error)

Liked reports whether each track URI is saved, using the URI-based contains endpoint.

func (*API) LikedTracks

func (c *API) LikedTracks(ctx context.Context, offset, limit int) (catalog.SavedTracksPage, error)

LikedTracks returns one documented page of saved tracks.

func (*API) Next

func (c *API) Next(ctx context.Context, deviceID string) error

func (*API) Pause

func (c *API) Pause(ctx context.Context, deviceID string) error

func (*API) PlaybackState

func (c *API) PlaybackState(ctx context.Context) (model.Status, string, error)

PlaybackState returns the current documented Web API player state.

func (*API) Playlists

func (c *API) Playlists(ctx context.Context) ([]model.Playlist, error)

Playlists pages through the signed-in user's playlist library.

func (*API) Previous

func (c *API) Previous(ctx context.Context, deviceID string) error

func (*API) Profile

func (c *API) Profile(ctx context.Context) (id, displayName string, err error)

Profile is the current user's documented profile data.

func (*API) RecentlyPlayed

func (c *API) RecentlyPlayed(ctx context.Context, limit int) ([]model.Played, error)

RecentlyPlayed returns unique contexts ordered by their latest play, using only Spotify's documented recently-played endpoint.

func (*API) Resume

func (c *API) Resume(ctx context.Context, deviceID string) error

func (*API) Search

func (c *API) Search(ctx context.Context, query string, limit int) (catalog.Results, error)

Search searches tracks, albums, artists, and playlists. The Web API's current Development Mode limit is ten results per type per request, so larger app requests are paged with offset.

func (*API) Seek

func (c *API) Seek(ctx context.Context, deviceID string, position time.Duration) error

func (*API) SetLiked

func (c *API) SetLiked(ctx context.Context, uris []string, liked bool) error

SetLiked saves or removes tracks using the current URI-based library API.

func (*API) SetRepeat

func (c *API) SetRepeat(ctx context.Context, deviceID string, repeat model.Repeat) error

func (*API) SetShuffle

func (c *API) SetShuffle(ctx context.Context, deviceID string, enabled bool) error

func (*API) SetVolume

func (c *API) SetVolume(ctx context.Context, deviceID string, percent int) error

func (*API) StartPlayback

func (c *API) StartPlayback(ctx context.Context, deviceID, uri, skipTo string, likedTracks []string) error

StartPlayback starts a playlist, album, artist, or track on deviceID. likedTracks supplies documented track URIs for a saved-library context.

func (*API) TransferPlayback

func (c *API) TransferPlayback(ctx context.Context, deviceID string, play bool) error

type Auth

type Auth struct {
	ClientID    string
	RedirectURI string
	Transport   Transport
	Store       SessionStore
	Now         func() time.Time
	Random      io.Reader
	// contains filtered or unexported fields
}

Auth runs Authorization Code with PKCE and refreshes tokens.

func (*Auth) AccessToken

func (a *Auth) AccessToken(ctx context.Context) (string, error)

AccessToken returns a current access token, refreshing it when it is about to expire.

func (*Auth) Begin

func (a *Auth) Begin() (string, error)

Begin creates PKCE state, stores the verifier, and returns Spotify's authorization URL.

func (*Auth) ExchangeCode

func (a *Auth) ExchangeCode(ctx context.Context, code, state string) error

ExchangeCode validates the OAuth state and exchanges a one-time code.

func (*Auth) Refresh

func (a *Auth) Refresh(ctx context.Context) (string, error)

Refresh forces a refresh after an API 401, even when the token has not reached its recorded expiry.

type Client

type Client struct {
	API  *API
	Auth *Auth
	SDK  SDK
	// contains filtered or unexported fields
}

Client combines the official Web API and Web Playback SDK behind the interfaces consumed by internal/app.

func NewClient

func NewClient(api *API, auth *Auth, sdk SDK) *Client

func (*Client) Album

func (c *Client) Album(ctx context.Context, uri string) (catalog.AlbumDetails, error)

func (*Client) Artist

func (c *Client) Artist(ctx context.Context, uri string) (catalog.ArtistOverview, error)

func (*Client) Configure

func (c *Client) Configure(context.Context, model.Audio) error

func (*Client) ContextTracks

func (c *Client) ContextTracks(ctx context.Context, uri string) (model.Listing, error)

func (*Client) Events

func (c *Client) Events() <-chan model.Event

func (*Client) Home

func (c *Client) Home(ctx context.Context) (catalog.HomeFeed, error)

func (*Client) Liked

func (c *Client) Liked(ctx context.Context, uris []string) ([]bool, error)

func (*Client) LikedTracks

func (c *Client) LikedTracks(ctx context.Context, offset, limit int) (catalog.SavedTracksPage, error)

func (*Client) Next

func (c *Client) Next(ctx context.Context) error

func (*Client) Play

func (c *Client) Play(ctx context.Context, uri, skipTo string) error

func (*Client) PlayPause

func (c *Client) PlayPause(ctx context.Context) error

func (*Client) Playlists

func (c *Client) Playlists(ctx context.Context) ([]model.Playlist, error)

func (*Client) Prev

func (c *Client) Prev(ctx context.Context) error

func (*Client) Queue

func (c *Client) Queue(ctx context.Context, uri string) error

func (*Client) RecentlyPlayed

func (c *Client) RecentlyPlayed(ctx context.Context, _ string, limit int) ([]model.Played, error)

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, limit int) (catalog.Results, error)

Search and catalog methods satisfy the app.Web optional interfaces.

func (*Client) Seek

func (c *Client) Seek(ctx context.Context, position time.Duration) error

func (*Client) SetDeviceName

func (c *Client) SetDeviceName(ctx context.Context, name string) error

func (*Client) SetLiked

func (c *Client) SetLiked(ctx context.Context, uris []string, liked bool) error

func (*Client) SetRepeat

func (c *Client) SetRepeat(ctx context.Context, repeat model.Repeat) error

func (*Client) SetShuffle

func (c *Client) SetShuffle(ctx context.Context, enabled bool) error

func (*Client) SetVolume

func (c *Client) SetVolume(ctx context.Context, volume int) error

func (*Client) SignOut

func (c *Client) SignOut(context.Context) error

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start starts the SDK event loop and connects the browser as a Connect device. It emits Ready so the app can load the account library immediately.

func (*Client) Status

func (c *Client) Status(ctx context.Context) (model.Status, error)

func (*Client) SupportsRadio

func (c *Client) SupportsRadio() bool

Song Radio depends on an endpoint Spotify currently marks deprecated; keep the action disabled instead of using a private endpoint.

func (*Client) SupportsSignOut

func (c *Client) SupportsSignOut() bool

type FetchTransport

type FetchTransport struct{}

FetchTransport is available in the js/wasm build and calls window.fetch.

type HTTPError

type HTTPError struct {
	Status     int
	RetryAfter string
	Message    string
}

HTTPError is a documented Web API response failure.

func (HTTPError) Error

func (e HTTPError) Error() string

func (HTTPError) HTTPStatus

func (e HTTPError) HTTPStatus() int

func (HTTPError) RetryAfterValue

func (e HTTPError) RetryAfterValue() string

type HTTPTransport

type HTTPTransport struct{ Client *http.Client }

HTTPTransport is used by native tests and API client tooling.

func (HTTPTransport) Do

func (h HTTPTransport) Do(ctx context.Context, request Request) (Response, error)

type PendingAuth

type PendingAuth struct {
	Verifier string `json:"verifier"`
	State    string `json:"state"`
}

type Request

type Request struct {
	Method string
	URL    string
	Header map[string]string
	Body   []byte
}

Request and Response are the small transport boundary shared by native tests and the browser fetch implementation.

type Response

type Response struct {
	Status int
	Header map[string]string
	Body   []byte
}

type SDK

type SDK interface {
	Events() <-chan SDKEvent
	Connect(context.Context) error
	Disconnect() error
	ActivateElement() error
	SetName(context.Context, string) error
}

SDK is the browser-only Web Playback SDK bridge.

type SDKEvent

type SDKEvent struct {
	Type     string
	DeviceID string
	State    SDKState
	Message  string
}

SDKEvent is an SDK callback after the JS boundary has extracted its values.

type SDKState

type SDKState struct {
	Track      model.Track
	ContextURI string
	Position   time.Duration
	Duration   time.Duration
	Paused     bool
	Empty      bool
}

SDKState is the DOM-free portion of Web Playback SDK state used by Smolify.

type SessionStore

type SessionStore interface {
	LoadToken() (Token, error)
	SaveToken(Token) error
	ClearToken() error
	SavePending(PendingAuth) error
	LoadPending() (PendingAuth, error)
	ClearPending() error
}

SessionStore keeps only short-lived OAuth state and tokens.

type Token

type Token struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	TokenType    string    `json:"token_type"`
	Scope        string    `json:"scope"`
	ExpiresAt    time.Time `json:"expires_at"`
}

Token is kept by a host session store; browser hosts should use sessionStorage rather than persistent storage.

type Transport

type Transport interface {
	Do(context.Context, Request) (Response, error)
}

Transport sends a request using the current host's HTTP implementation.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL