sdk

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2022 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package sdk implements a lightweight wrapper for the Spotify API.

Index

Constants

View Source
const (
	// BaseURLWeb is the api URL for the Spotify Web API.
	BaseURLWeb = "https://api.spotify.com/v1"

	// BaseURLOAuth is the api URL for the Spotify OAuth API.
	BaseURLOAuth = "https://accounts.spotify.com"
)
View Source
const (
	ArtistAlbumFilter       = "album"
	ArtistSingleFilter      = "single"
	ArtistAppearsOnFilter   = "appears_on"
	ArtistCompilationFilter = "compilation"
)
View Source
const (
	RedirectPort = ":8888"
	RedirectPath = "/token"
	RedirectURI  = "http://localhost" + RedirectPort + RedirectPath
)
View Source
const (
	AppAccessTokenKey  = ContextKey("aat")
	UserAccessTokenKey = ContextKey("uat")
)
View Source
const (
	ArtistSearch   = "artist"
	AlbumSearch    = "album"
	TrackSearch    = "track"
	PlaylistSearch = "playlist"
	ShowSearch     = "show"
	EpisodeSearch  = "episode"
)
View Source
const (
	AuthScopes = "playlist-read-private,playlist-modify-private,playlist-read-collaborative,playlist-modify-public"
)
View Source
const (
	SelfClosingHTML = `` /* 146-byte string literal not displayed */

)

Full credit to https://gist.github.com/lamielle/3345183

Variables

This section is empty.

Functions

func BuildQuery

func BuildQuery(params ...QueryParams) string

BuildQuery builds a query string, given a dynamic number of QueryParams values.

func OpenURL

func OpenURL(url string) error

OpenURL opens the given URL using the default browser. Full credit to https://gist.github.com/hyg/9c4afcd91fe24316cbf0

Types

type Album

type Album struct {
	Id                   string      `json:"id"`
	URI                  string      `json:"uri"`
	Name                 string      `json:"name"`
	AlbumType            string      `json:"album_type"`
	TotalTracks          int         `json:"total_tracks"`
	ReleaseDate          string      `json:"release_date"`
	ReleaseDatePrecision string      `json:"release_date_precision"`
	Restrictions         string      `json:"restrictions"`
	Images               []Image     `json:"images"`
	Artists              []Reference `json:"artists"`
}

Album represents an album on Spotify.

type Artist

type Artist struct {
	Id         string         `json:"id"`
	URI        string         `json:"uri"`
	Name       string         `json:"name"`
	Genres     []string       `json:"genres"`
	Images     []Image        `json:"images"`
	Popularity int            `json:"popularity"`
	Followers  FollowersStats `json:"followers"`
}

Artist represents an artist on Spotify.

type ArtistAlbumFilters

type ArtistAlbumFilters []string

func (*ArtistAlbumFilters) Set

func (a *ArtistAlbumFilters) Set(v string) error

Set parses an input string containing artist album filters and incorporates them.

func (*ArtistAlbumFilters) String

func (a *ArtistAlbumFilters) String() string

type AudioFeatures

type AudioFeatures struct {
	TrackId          string  `json:"id"`
	Acousticness     float64 `json:"acousticness"`
	Danceability     float64 `json:"danceability"`
	Energy           float64 `json:"energy"`
	Instrumentalness float64 `json:"instrumentalness"`
	Liveness         float64 `json:"liveness"`
	Loudness         float64 `json:"loudness"`
	Speechiness      float64 `json:"speechiness"`
	TimeSignature    int     `json:"time_signature"`
	Valence          float64 `json:"valence"`
	Mode             int     `json:"mode"`
	Tempo            float64 `json:"tempo"`
	Key              int     `json:"key"`
}

AudioFeatures holds the audio analysis results, for a track.

type ContextKey

type ContextKey string

type DynamicParams

type DynamicParams struct {
	Mapping map[string]string
}

DynamicParams implements the QueryParams interface while maintaining a dynamic list of params.

func NewDynamicParams

func NewDynamicParams() *DynamicParams

NewDynamicParams sets up and then returns a DynamicParams.

func (DynamicParams) AddToQuery

func (p DynamicParams) AddToQuery(q url.Values)

AddToQuery adds the query params from a DynamicParams to a url.Values value.

type ErrRateLimited

type ErrRateLimited struct {
	RetryAfter int
}

ErrRateLimited represents the rate-limiting of the app.

func (ErrRateLimited) Error

func (e ErrRateLimited) Error() string

type ErrTransient

type ErrTransient struct {
	Code int
}

ErrTransient represents an error that should disappear after some time.

func (ErrTransient) Error

func (e ErrTransient) Error() string

type FollowersStats

type FollowersStats struct {
	Total int `json:"total"`
}

A FollowersStats holds statistics regarding followers.

type Image

type Image struct {
	URL    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

Image represents an image resource served by the Spotify API.

type PaginatedCollection

type PaginatedCollection[T any] struct {
	Items []T `json:"items"`

	Offset int `json:"offset"`
	Limit  int `json:"limit"`
	Total  int `json:"total"`

	Next     string `json:"next"`
	Previous string `json:"previous"`
}

A PaginatedCollection holds the results of a paginated call.

type PaginationParams

type PaginationParams struct {
	Offset int
	Limit  int
}

A PaginationParams describes parameters that can be used when paginating requests.

func (PaginationParams) AddToQuery

func (p PaginationParams) AddToQuery(q url.Values)

AddToQuery adds the query params from a PaginationParams to a url.Values value.

type Playlist

type Playlist struct {
	Id            string         `json:"id"`
	URI           string         `json:"uri"`
	Name          string         `json:"name"`
	Description   string         `json:"description"`
	Collaborative bool           `json:"collaborative"`
	Public        bool           `json:"public"`
	Images        []Image        `json:"images"`
	Followers     FollowersStats `json:"followers"`
}

Playlist represents a playlist on Spotify.

type PlaylistAddTracksData

type PlaylistAddTracksData struct {
	URIs     []string `json:"uris"`
	Position int      `json:"position"`
}

PlaylistAddTracksData holds data used to make a request to add tracks to a playlist.

type PlaylistDetailsData

type PlaylistDetailsData struct {
	Name          string `json:"name"`
	Description   string `json:"description"`
	Public        bool   `json:"public"`
	Collaborative bool   `json:"collaborative"`
}

PlaylistDetailsData holds the parameters used in playlist creation.

type PlaylistItem

type PlaylistItem struct {
	Track Track `json:"track"`
}

PlaylistItem wraps a Track record.

type QueryParams

type QueryParams interface {
	AddToQuery(url.Values)
}

A QueryParams holds some query parameters and is able to add them to a url.Values.

type Reference

type Reference struct {
	Id string `json:"id"`
}

Reference represents a reduced version of a resource, containing only its id.

type ResourceRegistry

type ResourceRegistry struct {
	Artists  *SyncedMap[Artist]
	Albums   *SyncedMap[Album]
	Tracks   *SyncedMap[Track]
	Features *SyncedMap[AudioFeatures]
}

ResourceRegistry groups several related synced maps.

func NewResourceRegistry

func NewResourceRegistry() *ResourceRegistry

NewResourceRegistry sets up and then returns a new ResourceRegistry.

func (*ResourceRegistry) Summary

func (r *ResourceRegistry) Summary()

Summary prints a summary line for each resource type the registry holds.

type SearchParams

type SearchParams struct {
	Q    SearchString
	Type SearchType
	Top  int
}

A SearchParams describes parameters that can be used in a search.

func (SearchParams) AddToQuery

func (s SearchParams) AddToQuery(q url.Values)

AddToQuery adds the query params from a SearchParams to a url.Values value.

type SearchResult

type SearchResult struct {
	Artists   PaginatedCollection[Artist]   `json:"artists"`
	Albums    PaginatedCollection[Album]    `json:"albums"`
	Tracks    PaginatedCollection[Track]    `json:"tracks"`
	Playlists PaginatedCollection[Playlist] `json:"playlists"`
}

A SearchResult holds the root-level result of a search.

type SearchString

type SearchString string

func (*SearchString) Set

func (s *SearchString) Set(v string) error

Set uses an input string to populate the current SearchString.

func (*SearchString) String

func (s *SearchString) String() string

type SearchType

type SearchType []string

func (*SearchType) Set

func (s *SearchType) Set(v string) error

Set parses an input string containing search types and incorporates them.

func (*SearchType) String

func (s *SearchType) String() string

type Spotify

type Spotify struct {
	Config      *config.Root
	Context     context.Context
	CurrentUser *User
}

A Spotify is the entrypoint for the Spotify API.

func NewSpotifyClient

func NewSpotifyClient(conf *config.Root) (*Spotify, error)

NewSpotifyClient creates a new Spotify value and sets up its auth token.

func (*Spotify) AddTracksToPlaylist

func (s *Spotify) AddTracksToPlaylist(id string, data *PlaylistAddTracksData) error

AddTracksToPlaylist adds tracks to an existing playlist.

func (*Spotify) BuildSearchRegistry

func (s *Spotify) BuildSearchRegistry(sr *SearchResult) *ResourceRegistry

BuildSearchRegistry builds a new resource registry based on the results of the search.

func (*Spotify) CreatePlaylist

func (s *Spotify) CreatePlaylist(data *PlaylistDetailsData) (*Playlist, error)

CreatePlaylist creates a new playlist for the current user.

func (*Spotify) GetAlbum

func (s *Spotify) GetAlbum(id string) (*Album, error)

GetAlbum fetches a single album.

func (*Spotify) GetAlbumTracks

func (s *Spotify) GetAlbumTracks(id string) ([]Track, error)

GetAlbumTracks fetches all tracks from an album.

func (*Spotify) GetArtist

func (s *Spotify) GetArtist(id string) (*Artist, error)

GetArtist fetches a single artist.

func (*Spotify) GetArtistAlbums

func (s *Spotify) GetArtistAlbums(id string, groups ArtistAlbumFilters) ([]Album, error)

GetArtistAlbums fetches a list of albums that the given artist appears on.

func (*Spotify) GetCurrentUser

func (s *Spotify) GetCurrentUser() (*User, error)

GetCurrentUser fetches the current user.

func (*Spotify) GetMultipleTrackAudioFeatures

func (s *Spotify) GetMultipleTrackAudioFeatures(ids ...string) ([]AudioFeatures, error)

GetMultipleTrackAudioFeatures fetches audio features for up to 100 tracks.

func (*Spotify) GetPlaylist

func (s *Spotify) GetPlaylist(id string) (*Playlist, error)

GetPlaylist fetches a single playlist.

func (*Spotify) GetPlaylistTracks

func (s *Spotify) GetPlaylistTracks(id string) ([]Track, error)

GetPlaylistTracks fetches all tracks from a playlist.

func (*Spotify) GetRelatedArtists

func (s *Spotify) GetRelatedArtists(id string) ([]Artist, error)

GetRelatedArtists fetches a list of artists related to the given artist.

func (*Spotify) GetTrack

func (s *Spotify) GetTrack(id string) (*Track, error)

GetTrack fetches a single track.

func (*Spotify) GetTrackAudioFeatures

func (s *Spotify) GetTrackAudioFeatures(id string) (*AudioFeatures, error)

GetTrackAudioFeatures fetches audio features for a single track.

func (*Spotify) SearchTop

func (s *Spotify) SearchTop(search SearchParams, top int) (*SearchResult, error)

SearchTop queries the API and returns the results.

func (*Spotify) UpdatePlaylist

func (s *Spotify) UpdatePlaylist(id string, data *PlaylistDetailsData) error

UpdatePlaylist updates the details of an existing playlist.

type SyncedMap

type SyncedMap[T any] struct {
	Map   map[string]T
	Mutex *sync.RWMutex
}

SyncedMap implements a map whose access is controlled by a mutex.

func NewSyncedMap

func NewSyncedMap[T any]() *SyncedMap[T]

NewSyncedMap sets up and then returns a NewSyncedMap.

func (*SyncedMap[T]) KeyExists

func (m *SyncedMap[T]) KeyExists(key string) bool

KeyExists checks whether a given key already exists in the synced map.

func (*SyncedMap[T]) Load

func (m *SyncedMap[T]) Load(key string) (T, bool)

Load fetches the data currently stored under the given key, if any.

func (*SyncedMap[T]) Store

func (m *SyncedMap[T]) Store(key string, record T) bool

Store stores the given data under the given key.

type Track

type Track struct {
	Id          string      `json:"id"`
	URI         string      `json:"uri"`
	Name        string      `json:"name"`
	DiscNumber  int         `json:"disc_number"`
	TrackNumber int         `json:"track_number"`
	DurationMs  int         `json:"duration_ms"`
	Popularity  int         `json:"popularity"`
	Explicit    bool        `json:"explicit"`
	IsPlayable  bool        `json:"is_playable"`
	PreviewUrl  string      `json:"preview_url"`
	Album       Reference   `json:"album"`
	Artists     []Reference `json:"artists"`
}

Track represents a track on Spotify.

type User

type User struct {
	Id   string `json:"id"`
	Name string `json:"display_name"`
}

User represents a user on Spotify.

Jump to

Keyboard shortcuts

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