client

package
v0.0.0-...-d2e4998 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: GPL-2.0 Imports: 20 Imported by: ? 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 client is the public Go SDK for MusOak.

Everything the server does is an API call, so the CLI, a Discord bot or any other tool is a plain client: authenticate, search, prepare media, queue it in a room and follow the host's playback state. Nothing reaches into server internals.

Index

Constants

View Source
const (
	MediaNone        = "none"
	MediaDownloading = "downloading"
	MediaReady       = "ready"
	MediaFailed      = "failed"
)

Media states.

View Source
const (
	// MediaStageDownload means bytes are arriving from the provider.
	MediaStageDownload = "download"
	// MediaStageConvert means the fetched source is being written as the stored
	// rendition, so Bytes/TotalBytes are milliseconds there.
	MediaStageConvert = "convert"
	// MediaStageStore means the finished file is being probed and put in place.
	MediaStageStore = "store"
)

Media stages: what a download is doing between "downloading" and "ready".

View Source
const (
	EventMemberJoined = "member_joined"
	EventMemberLeft   = "member_left"
	EventHostChanged  = "host_changed"
	EventQueueUpdated = "queue_updated"
	EventPlayback     = "playback"
	EventRoomClosed   = "room_closed"
)

Event types.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout bounds a single API request, not a media transfer.

View Source
const MaxQueueBatch = 500

MaxQueueBatch is how many tracks one add may carry. The server holds the room lock across a batch, so it refuses more; QueueMany splits longer runs.

Variables

View Source
var ErrRoomClosed = errors.New("musoak: the room closed")

ErrRoomClosed is what Run returns when the room closed under it. It is distinct from a plain nil, which means the connection to the room dropped: the room is still there and following it again is worthwhile.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to v, for RadioOptions.Save.

func IsConflict

func IsConflict(err error) bool

IsConflict reports whether err is a 409 from the server.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a 404 from the server.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is a 401 from the server.

Types

type APIError

type APIError struct {
	Status  int
	Message string
}

APIError is a non-2xx response.

func (*APIError) Error

func (e *APIError) Error() string

type Album

type Album struct {
	ID         string         `json:"id"`
	Title      string         `json:"title"`
	Artists    []string       `json:"artists"`
	Year       string         `json:"year,omitempty"`
	TrackCount int            `json:"trackCount"`
	Providers  []string       `json:"providers"`
	Variants   []AlbumVariant `json:"variants,omitempty"`
	Tracks     []Track        `json:"tracks,omitempty"`
}

Album is a canonical album; providers lists the sources that know it.

type AlbumVariant

type AlbumVariant struct {
	ID              string   `json:"id"`
	Provider        string   `json:"provider"`
	ProviderAlbumID string   `json:"providerAlbumId"`
	Title           string   `json:"title"`
	Artists         []string `json:"artists"`
	Year            string   `json:"year,omitempty"`
	TrackCount      int      `json:"trackCount,omitempty"`
}

AlbumVariant is one provider's release of a canonical album.

type Artist

type Artist struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Providers []string        `json:"providers"`
	Variants  []ArtistVariant `json:"variants,omitempty"`
	Albums    []Album         `json:"albums,omitempty"`
}

Artist is a canonical artist.

type ArtistVariant

type ArtistVariant struct {
	ID               string `json:"id"`
	Provider         string `json:"provider"`
	ProviderArtistID string `json:"providerArtistId"`
	Name             string `json:"name"`
}

ArtistVariant is one provider's page for a canonical artist.

type Auth

type Auth struct {
	Token string `json:"token"`
	User  User   `json:"user"`
}

Auth is the response to register or login.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache is the client-side media cache. It keeps renditions on disk, remembers what it has in an index file, and never downloads the same variant twice. Each room member uses its own cached or downloaded rendition.

func OpenCache

func OpenCache(dir string) (*Cache, error)

OpenCache opens (creating if needed) a media cache directory.

func (*Cache) Dir

func (c *Cache) Dir() string

Dir is where cached renditions live.

func (*Cache) Entries

func (c *Cache) Entries() []CacheEntry

Entries lists everything the cache holds.

func (*Cache) Fetch

func (c *Cache) Fetch(ctx context.Context, api *Client, variantID string) (CacheEntry, error)

Fetch makes sure a variant is on disk and returns its entry. Concurrent calls for the same variant share one download: two transfers of one rendition would otherwise race onto the same temp path and could rename a half-written file into place as if it were the whole thing.

func (*Cache) Lookup

func (c *Cache) Lookup(variantID string) (CacheEntry, bool)

Lookup returns the entry for a variant if its file is still present.

func (*Cache) LookupTrack

func (c *Cache) LookupTrack(trackID string) (CacheEntry, bool)

LookupTrack returns a cached rendition of a track, if there is one. The track index answers in one step, and the file is checked outside the lock so a stat cannot hold up a download or an index write.

func (*Cache) Path

func (c *Cache) Path(variantID string) string

Path is where a variant's file would live.

func (*Cache) Put

func (c *Cache) Put(entry CacheEntry) error

Put indexes a file the caller already has (for example after importing a local file), so it is never downloaded again.

type CacheEntry

type CacheEntry struct {
	VariantID    string    `json:"variantId"`
	TrackID      string    `json:"trackId"`
	Path         string    `json:"path"`
	DurationMs   int64     `json:"durationMs"`
	SHA256       string    `json:"sha256,omitempty"`
	Bytes        int64     `json:"bytes,omitempty"`
	DownloadedAt time.Time `json:"downloadedAt"`
}

CacheEntry is one cached rendition.

type Capabilities

type Capabilities struct {
	Search   bool `json:"search"`
	Download bool `json:"download"`
}

Capabilities describes what a provider can do.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to one MusOak server.

func New

func New(baseURL string, opts ...Option) *Client

New returns a client for a server, e.g. "http://localhost:4420".

func (*Client) AddFavorite

func (c *Client) AddFavorite(ctx context.Context, trackID string, rating ...float64) error

AddFavorite favorites a track with a decimal rating (0.1 to 5.0).

func (*Client) AddPlaylistTracks

func (c *Client) AddPlaylistTracks(ctx context.Context, playlistID string, trackIDs ...string) (*PlaylistDetail, error)

AddPlaylistTracks appends tracks to a playlist.

func (*Client) Album

func (c *Client) Album(ctx context.Context, albumID string) (*Album, error)

Album fetches one album with its tracklist.

func (*Client) Artist

func (c *Client) Artist(ctx context.Context, artistID string) (*Artist, error)

Artist fetches one artist with their albums.

func (*Client) BaseURL

func (c *Client) BaseURL() string

BaseURL is the server this client talks to.

func (*Client) Clock

func (c *Client) Clock(ctx context.Context) (int64, error)

Clock reports the server clock in milliseconds.

func (*Client) ClockOffset

func (c *Client) ClockOffset(ctx context.Context, samples int) (time.Duration, error)

ClockOffset estimates the offset between the server clock and this machine's clock: add it to a local millisecond timestamp to get server time.

It takes NTP-style samples over the event socket and keeps the one with the lowest round trip, because that is the sample with the least network noise.

func (*Client) CreatePlaylist

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

CreatePlaylist makes an empty playlist.

func (*Client) CreateRoom

func (c *Client) CreateRoom(ctx context.Context, name, controls string) (*RoomClient, error)

CreateRoom opens a room; the caller becomes its host.

func (*Client) DeletePlaylist

func (c *Client) DeletePlaylist(ctx context.Context, playlistID string) error

DeletePlaylist removes a playlist.

func (*Client) DownloadMedia

func (c *Client) DownloadMedia(ctx context.Context, variantID string, w io.Writer) (int64, error)

DownloadMedia writes a ready variant's audio to w.

func (*Client) Events

func (c *Client) Events(ctx context.Context, roomID string) (<-chan Event, error)

Events subscribes to room events; pass an empty roomID for every room. The channel closes when ctx ends or the connection drops.

func (*Client) Favorites

func (c *Client) Favorites(ctx context.Context) ([]Track, error)

Favorites lists the caller's favorited tracks, including saved ratings.

func (*Client) ImportDir

func (c *Client) ImportDir(ctx context.Context, dir string) (*ImportResult, error)

ImportDir adds every audio file under a directory to the library.

func (*Client) ImportPath

func (c *Client) ImportPath(ctx context.Context, path string) (*ImportResult, error)

ImportPath adds one local file to the library.

func (*Client) JoinRoom

func (c *Client) JoinRoom(ctx context.Context, roomID string) (*RoomClient, error)

JoinRoom joins a room, generating a guest identity when needed.

func (*Client) Login

func (c *Client) Login(ctx context.Context, username, password string) (*Auth, error)

Login authenticates and stores the session token on the client.

func (*Client) Logout

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

Logout revokes the current session.

func (*Client) Me

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

Me describes the caller: account, guest or login-required.

func (*Client) MediaStatus

func (c *Client) MediaStatus(ctx context.Context, variantID string) (*MediaStatus, error)

MediaStatus reports a variant's download progress.

func (*Client) MediaURL

func (c *Client) MediaURL(variantID string, startMs int64) string

MediaURL is the URL a variant's stored file is served from, the same URL the media GET uses. A player that speaks HTTP (mpv does) can be handed it directly. The server answers only for a rendition it has finished storing: for one it has not, the request is refused and the caller must download it first (Cache.Fetch does that).

startMs, when positive, asks the file to be served from that far into the track: a listener joining a song already under way hears the rest of it rather than its head. Zero is the whole file from the beginning.

func (*Client) MemberID

func (c *Client) MemberID() string

MemberID returns the guest member id, empty when none is set.

func (*Client) OpenMedia

func (c *Client) OpenMedia(ctx context.Context, variantID string) (io.ReadCloser, error)

OpenMedia streams a ready variant's audio. The caller closes the reader.

func (*Client) Playlist

func (c *Client) Playlist(ctx context.Context, playlistID string) (*PlaylistDetail, error)

Playlist returns one playlist with its tracks.

func (*Client) PlaylistByName

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

PlaylistByName resolves a playlist by name; it reports the candidates when the name is ambiguous.

func (*Client) PlaylistFromAlbum

func (c *Client) PlaylistFromAlbum(ctx context.Context, albumID, name string) (*PlaylistDetail, error)

PlaylistFromAlbum stores an album's tracklist as a new playlist.

func (*Client) Playlists

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

Playlists lists the caller's playlists.

func (*Client) Providers

func (c *Client) Providers(ctx context.Context) ([]Provider, error)

Providers lists the enabled providers.

func (*Client) Radio

func (c *Client) Radio(ctx context.Context, seedTrackID string, opts RadioOptions) (*RadioResult, error)

Radio starts a station from a seed track, mixing the providers it names.

func (*Client) Ranking

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

Ranking reports the caller's ranking, the aggregate and the default.

func (*Client) Register

func (c *Client) Register(ctx context.Context, username, password string) (*Auth, error)

Register creates an account and stores the session token on the client.

func (*Client) RemoveFavorite

func (c *Client) RemoveFavorite(ctx context.Context, trackID string) error

RemoveFavorite removes a track from the caller's favorites.

func (*Client) RemovePlaylistItem

func (c *Client) RemovePlaylistItem(ctx context.Context, playlistID string, position int) (*PlaylistDetail, error)

RemovePlaylistItem drops the entry at a position.

func (*Client) RenamePlaylist

func (c *Client) RenamePlaylist(ctx context.Context, playlistID, name string) (*Playlist, error)

RenamePlaylist changes a playlist's name.

func (*Client) ReorderPlaylist

func (c *Client) ReorderPlaylist(ctx context.Context, playlistID string, order []int) (*PlaylistDetail, error)

ReorderPlaylist applies a new order, given as the current positions.

func (*Client) ResolveTrack

func (c *Client) ResolveTrack(ctx context.Context, trackID string) ([]Variant, bool, error)

ResolveTrack makes sure a track has a downloadable variant, matching one from a downloadable provider when it only has metadata-only renditions. The bool reports whether the track is now playable.

func (*Client) Rooms

func (c *Client) Rooms(ctx context.Context) ([]Room, error)

Rooms lists every room.

func (*Client) Search

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

Search runs a merged, cross-provider search.

func (*Client) SearchAlbums

func (c *Client) SearchAlbums(ctx context.Context, query string, limit int) ([]Album, []ProviderError, error)

SearchAlbums searches every provider that can browse albums.

func (*Client) SearchArtists

func (c *Client) SearchArtists(ctx context.Context, query string, limit int) ([]Artist, []ProviderError, error)

SearchArtists searches every provider that can browse artists.

func (*Client) SetMemberID

func (c *Client) SetMemberID(memberID string)

SetMemberID replaces the guest room member id.

func (*Client) SetRanking

func (c *Client) SetRanking(ctx context.Context, providers []string) (*Ranking, error)

SetRanking replaces the caller's provider order.

func (*Client) SetToken

func (c *Client) SetToken(token string)

SetToken replaces the bearer token (after login or logout).

func (*Client) StartDownload

func (c *Client) StartDownload(ctx context.Context, variantID string) (*MediaStatus, error)

StartDownload asks the server to prepare a variant. It returns immediately; call MediaStatus or WaitForMedia to follow progress.

func (*Client) StartDownloadAndWait

func (c *Client) StartDownloadAndWait(ctx context.Context, variantID string) (*MediaStatus, error)

StartDownloadAndWait asks the server to prepare a variant and blocks until it is ready, failed or ctx ends.

func (*Client) SyncAlbum

func (c *Client) SyncAlbum(ctx context.Context, albumID string, opts SyncOptions) (*SyncResult, error)

SyncAlbum pulls an album's provider tracklists into the library.

func (*Client) SyncArtist

func (c *Client) SyncArtist(ctx context.Context, artistID string, opts SyncOptions) (*SyncResult, error)

SyncArtist records an artist's provider pages and pulls their albums.

func (*Client) Token

func (c *Client) Token() string

Token returns the current bearer token, empty for a guest.

func (*Client) Track

func (c *Client) Track(ctx context.Context, trackID string) (*Track, error)

Track fetches one canonical track.

func (*Client) TrackVariants

func (c *Client) TrackVariants(ctx context.Context, trackID string) ([]Variant, error)

TrackVariants lists every rendition of a track.

func (*Client) WaitForMedia

func (c *Client) WaitForMedia(ctx context.Context, variantID string) (*MediaStatus, error)

WaitForMedia polls until the variant is ready or failed.

type ClockSample

type ClockSample struct {
	OffsetMs int64
	RTTMs    int64
}

ClockSample is one ping round trip.

type Event

type Event struct {
	Type   string          `json:"type"`
	RoomID string          `json:"roomId,omitempty"`
	Seq    int64           `json:"seq,omitempty"`
	AtMs   int64           `json:"atMs,omitempty"`
	Data   json.RawMessage `json:"data,omitempty"`
}

Event is one message from the room event stream. Seq is per-room: a gap in it means events were missed, and the snapshot is the way back.

func (Event) DecodeData

func (e Event) DecodeData(v any) error

DecodeData decodes the event payload into v.

type HostChangedEvent

type HostChangedEvent struct {
	Host string `json:"host"`
	Was  string `json:"was"`
}

HostChangedEvent is the payload of host_changed.

type ImportResult

type ImportResult struct {
	Imported []Imported `json:"imported"`
	Failures []string   `json:"failures,omitempty"`
}

ImportResult reports what a library import did.

type Imported

type Imported struct {
	Track   Track   `json:"track"`
	Variant Variant `json:"variant"`
}

Imported is one file added to the library.

type Me

type Me struct {
	Authenticated    bool  `json:"authenticated"`
	Guest            bool  `json:"guest"`
	User             *User `json:"user,omitempty"`
	RequireLogin     bool  `json:"requireLogin"`
	RegistrationOpen bool  `json:"registrationOpen"`
}

Me describes the caller.

type MediaStatus

type MediaStatus struct {
	VariantID string `json:"variantId"`
	State     string `json:"state"`
	// Stage is what the download is doing right now, one of the Media stages,
	// and empty when nothing is running.
	Stage string `json:"stage,omitempty"`
	// Progress is the fraction of the current stage that is done, and -1 when
	// there is nothing to count: a length the provider never reported, or a
	// stage with no bytes. A -1 is a caller's cue to show the stage's own
	// numbers instead of a percentage.
	Progress float64 `json:"progress"`
	Error    string  `json:"error,omitempty"`
	// DurationMs is the finished rendition's length, once it is known.
	DurationMs int64 `json:"durationMs,omitempty"`
	// Bytes and TotalBytes are the current stage's own numbers: bytes for the
	// download stage, milliseconds for the conversion. TotalBytes <= 0 means
	// unknown.
	Bytes      int64 `json:"bytes,omitempty"`
	TotalBytes int64 `json:"totalBytes,omitempty"`
}

MediaStatus is a variant's download state.

type Option

type Option func(*Client)

Option configures a Client.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient replaces the underlying HTTP client; media transfers need an http.Client without a short timeout.

func WithMemberID

func WithMemberID(memberID string) Option

WithMemberID sets the room member id used as a guest.

func WithToken

func WithToken(token string) Option

WithToken authenticates every request with a bearer token.

type Participant

type Participant struct {
	OnEvent func(Event)
	OnTrack func(SinkTrack)
	// contains filtered or unexported fields
}

Participant follows a room on behalf of one member. The server is the room's clock: this client plays the room's current song, corrects itself to the room's position when it drifts more than two seconds, and advances to the next song on its own when its own file ends. It never reports a position; the server's once-a-second state is only ever a correction.

func NewParticipant

func NewParticipant(room *RoomClient, cache *Cache, sink Sink, logger *slog.Logger) *Participant

NewParticipant returns a participant for a room.

func (*Participant) ClockOffset

func (p *Participant) ClockOffset() time.Duration

ClockOffset is the current estimate of (server clock - local clock).

func (*Participant) LocalPosition

func (p *Participant) LocalPosition(ctx context.Context) (int64, bool)

LocalPosition reports where this client's own player is in the song, when its sink can say so.

func (*Participant) MemberID

func (p *Participant) MemberID() string

MemberID is who this participant is in the room.

func (*Participant) Position

func (p *Participant) Position() int64

Position reports where the room should be right now, on the server clock.

func (*Participant) Room

func (p *Participant) Room() *RoomClient

Room exposes the room client this participant follows.

func (*Participant) Run

func (p *Participant) Run(ctx context.Context) error

Run follows the room until ctx ends, the room closes, or the connection to it drops.

func (*Participant) SetDriftTolerance

func (p *Participant) SetDriftTolerance(ms int64)

SetDriftTolerance sets how far this client may sit from the room's position before it seeks back, in milliseconds.

It belongs to the caller's pipeline: a client that keeps a second of audio buffered ahead of the wire is a second behind by design, and correcting that is correcting the buffer, not the playback. A caller that buffers should set this past its buffer - otherwise every beat is a correction.

func (*Participant) StopPlayback

func (p *Participant) StopPlayback(ctx context.Context) error

StopPlayback stops this client's audio without leaving the room.

func (*Participant) Vote

func (p *Participant) Vote(ctx context.Context, score float64, autoSkip ...bool) error

Vote scores the current track from 0.1 (bad) to 5.0 (great).

type Pauser

type Pauser interface {
	Pause(ctx context.Context) error
	Resume(ctx context.Context) error
}

Pauser is implemented by sinks that can pause in place.

type PlaybackEvent

type PlaybackEvent struct {
	Current *RoomPlayback `json:"current"`
}

PlaybackEvent is the payload of playback: the whole current state, or a null current when the room has nothing playing.

type Playlist

type Playlist struct {
	ID         string    `json:"id"`
	Name       string    `json:"name"`
	TrackCount int       `json:"trackCount"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
}

Playlist is one of the caller's playlists.

type PlaylistDetail

type PlaylistDetail struct {
	Playlist
	Items []PlaylistItem `json:"items"`
}

PlaylistDetail is a playlist with its tracks.

type PlaylistItem

type PlaylistItem struct {
	Position int   `json:"position"`
	Track    Track `json:"track"`
}

PlaylistItem is one entry of a playlist.

type Positioner

type Positioner interface {
	PositionMs(ctx context.Context) (int64, error)
}

Positioner reports the local playhead for drift correction against the room's position.

type Provider

type Provider struct {
	Name         string       `json:"name"`
	Capabilities Capabilities `json:"capabilities"`
	MissingDeps  []string     `json:"missingDeps,omitempty"`
}

Provider is one configured music source.

type ProviderError

type ProviderError struct {
	Provider string `json:"provider"`
	Error    string `json:"error"`
}

ProviderError reports one provider's failure during a search.

type QueueEvent

type QueueEvent struct {
	MemberID    string      `json:"memberId"`
	MemberQueue []QueueItem `json:"memberQueue"`
	Gone        bool        `json:"gone"`
	// Master is the room's play order after the change. The server is its only
	// author, so a follower can take it as it comes; nil means an older server
	// that leaves the order to be derived or refetched.
	Master []QueueItem `json:"master,omitempty"`
}

QueueEvent is the payload of queue_updated: one member's queue, or notice that they left and their queue is gone.

type QueueItem

type QueueItem struct {
	ID         string   `json:"id"`
	TrackID    string   `json:"trackId"`
	Title      string   `json:"title"`
	AddedBy    string   `json:"addedBy"`
	AddedAtMs  int64    `json:"addedAtMs"`
	DurationMs int64    `json:"durationMs,omitempty"`
	ArtworkURL string   `json:"artworkUrl,omitempty"`
	ArtistIDs  []string `json:"artistIds,omitempty"`
	// Artists is the names in credit order, the same "artists" a track
	// response carries: the row shows them under the title.
	Artists []string `json:"artists,omitempty"`
}

QueueItem is one entry of a room's queue.

type RadioOptions

type RadioOptions struct {
	// Providers selects what the station is made of; empty means every enabled
	// provider that can build one.
	Providers []string
	// Length is how many tracks the station should hold; zero means the
	// server's default.
	Length int
	// Save stores the station as a playlist. It is a pointer so that "unset"
	// (the server default: save) is distinguishable from an explicit false.
	Save *bool
	// Name overrides the playlist name.
	Name string
}

RadioOptions tunes a station.

type RadioResult

type RadioResult struct {
	Seed           Track           `json:"seed"`
	Providers      []string        `json:"providers"`
	Tracks         []Track         `json:"tracks"`
	ProviderErrors []ProviderError `json:"providerErrors,omitempty"`
	// Playlist is set when the station was saved.
	Playlist *Playlist `json:"playlist,omitempty"`
}

RadioResult is a generated station.

type Ranking

type Ranking struct {
	Ranking   []string `json:"ranking"`
	Effective []string `json:"effective"`
	Aggregate []string `json:"aggregate"`
	Default   []string `json:"default"`
}

Ranking is a user's provider order with the aggregate and default around it.

type Room

type Room struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Host        string                 `json:"host"`
	Controls    string                 `json:"controls"`
	CreatedAtMs int64                  `json:"createdAtMs"`
	Members     []RoomMember           `json:"members"`
	MemberCount int                    `json:"memberCount"`
	Queues      map[string][]QueueItem `json:"queues"`
	MasterQueue []QueueItem            `json:"masterQueue"`
	Current     *RoomPlayback          `json:"current,omitempty"`
	ServerNowMs int64                  `json:"serverNowMs"`
	Seq         int64                  `json:"seq"`
	Skip        RoomSkipRules          `json:"skip"`
}

func (*Room) HasMember

func (r *Room) HasMember(memberID string) bool

RoomMemberID reports which member id this client joined as.

func (*Room) Pending

func (r *Room) Pending() []QueueItem

Pending is the play order with the current song taken out: what the room will play after this one.

type RoomClient

type RoomClient struct {
	RoomID   string
	MemberID string
	// contains filtered or unexported fields
}

RoomClient is a room seen through this client's membership.

func (*RoomClient) Client

func (r *RoomClient) Client() *Client

Client exposes the underlying client (for auth state and media helpers).

func (*RoomClient) Events

func (r *RoomClient) Events(ctx context.Context) (<-chan Event, error)

Events subscribes to this room's event stream.

func (*RoomClient) Leave

func (r *RoomClient) Leave(ctx context.Context) error

Leave removes this member from the room.

func (*RoomClient) Pause

func (r *RoomClient) Pause(ctx context.Context) (*Room, error)

Pause freezes the room.

func (*RoomClient) Queue

func (r *RoomClient) Queue(ctx context.Context, trackID string) (*Room, error)

Queue appends a track.

func (*RoomClient) QueueMany

func (r *RoomClient) QueueMany(ctx context.Context, trackIDs []string) (*Room, error)

QueueMany appends a run of tracks as one edit: a playlist added to a room is one change, not one per song. Each song on its own is a round trip that answers with the whole room, so a run of them is a run of whole rooms.

func (*RoomClient) Remove

func (r *RoomClient) Remove(ctx context.Context, itemID string) (*Room, error)

Remove drops a queued item.

func (*RoomClient) Reorder

func (r *RoomClient) Reorder(ctx context.Context, itemIDs []string) (*Room, error)

Reorder rearranges the queue.

func (*RoomClient) Resume

func (r *RoomClient) Resume(ctx context.Context) (*Room, error)

Resume continues a paused room.

func (*RoomClient) Seek

func (r *RoomClient) Seek(ctx context.Context, positionMs int64) (*Room, error)

Seek moves the room position; clients correct their drift with small seeks.

func (*RoomClient) Skip

func (r *RoomClient) Skip(ctx context.Context) (*Room, error)

Skip advances past the current track.

func (*RoomClient) Snapshot

func (r *RoomClient) Snapshot(ctx context.Context) (*Room, error)

Snapshot fetches the room state.

func (*RoomClient) Vote

func (r *RoomClient) Vote(ctx context.Context, score float64, autoSkip ...bool) (*Room, error)

Vote scores the current track from 0.1 (bad) to 5.0 (great).

type RoomMember

type RoomMember struct {
	ID          string `json:"id"`
	UserID      string `json:"userId,omitempty"`
	Name        string `json:"name"`
	JoinedAtMs  int64  `json:"joinedAtMs"`
	IconURL     string `json:"iconUrl,omitempty"`
	IconVersion int    `json:"iconVersion,omitempty"`
}

RoomMember is one participant in a room. UserID is empty for guests.

type RoomPlayback

type RoomPlayback struct {
	Item       QueueItem          `json:"item"`
	PositionMs int64              `json:"positionMs"`
	AtMs       int64              `json:"atMs"`
	Started    bool               `json:"started"`
	Paused     bool               `json:"paused"`
	DurationMs int64              `json:"durationMs"`
	Votes      map[string]float64 `json:"votes"`
	MeanScore  float64            `json:"meanScore"`
}

RoomPlayback is the room's current song and where the server says it is. PositionMs is at AtMs on the server clock, so a client can extrapolate between the once-a-second updates.

func (*RoomPlayback) PositionAt

func (p *RoomPlayback) PositionAt(serverNowMs int64) int64

PositionAt is where the room should be at serverNowMs.

type RoomSkipRules

type RoomSkipRules struct {
	SkipThreshold        float64 `json:"skipThreshold"`
	MinVotersForSkip     int     `json:"minVotersForSkip"`
	VoterFractionForSkip float64 `json:"voterFractionForSkip"`
}

RoomSkipRules are the tunables shown next to the vote buttons.

type SearchGroup

type SearchGroup struct {
	Track    Track     `json:"track"`
	Variants []Variant `json:"variants"`
}

SearchGroup is a canonical track with the variants that matched onto it.

type SearchResult

type SearchResult struct {
	Query          string          `json:"query"`
	Groups         []SearchGroup   `json:"groups"`
	ProviderErrors []ProviderError `json:"providerErrors,omitempty"`
}

SearchResult is a merged fan-out search.

type Seeker

type Seeker interface {
	Seek(ctx context.Context, positionMs int64) error
}

Seeker is implemented by sinks that can jump to a position.

type Sink

type Sink interface {
	// Play starts the file the track names and returns when it finishes or ctx
	// ends. What is handed over is always a file on this machine: a rendition
	// the server has not stored is fetched first, never played from the provider.
	// The participant advances to the next song itself when Play returns.
	Play(ctx context.Context, track SinkTrack) error
	Stop(ctx context.Context) error
}

Sink plays a file. The CLI's sink drives a local player; a Discord bot's sink pushes the file into a voice channel. Nothing in this package cares which.

type SinkTrack

type SinkTrack struct {
	TrackID   string
	VariantID string
	// Title is the song's name, for a sink that says what it is playing.
	Title string
	// Path is the file on disk to play.
	Path string
	// DurationMs is the song's length: the file's own once it is here, and the
	// length the room reports when the file's own is still unknown.
	DurationMs int64
	// PositionMs is where in the song playback should begin; a sink seeks there.
	PositionMs int64
}

SinkTrack is one rendition handed to a Sink: a file this client holds.

type SyncOptions

type SyncOptions struct {
	// Providers selects what to sync from; empty means every known release.
	Providers []string
	// Resolve also makes sure each track has something playable.
	Resolve bool
	// SyncAlbums (artist syncs) fetches each album's tracklist too.
	SyncAlbums bool
}

SyncOptions tunes a collection sync.

type SyncResult

type SyncResult struct {
	AlbumID        string          `json:"albumId,omitempty"`
	ArtistID       string          `json:"artistId,omitempty"`
	Providers      []string        `json:"providers"`
	Added          int             `json:"added"`
	Tracks         []Track         `json:"tracks,omitempty"`
	Albums         []Album         `json:"albums,omitempty"`
	ProviderErrors []ProviderError `json:"providerErrors,omitempty"`
}

SyncResult reports what a sync added.

type Track

type Track struct {
	ID         string    `json:"id"`
	Title      string    `json:"title"`
	DurationMs int64     `json:"durationMs"`
	Artists    []string  `json:"artists"`
	Albums     []string  `json:"albums"`
	CreatedAt  time.Time `json:"createdAt"`
	Rating     float64   `json:"rating"`
}

Track is a canonical song.

type User

type User struct {
	ID       string `json:"id"`
	Username string `json:"username"`
}

User is an account.

type Variant

type Variant struct {
	ID              string   `json:"id"`
	TrackID         string   `json:"trackId"`
	Provider        string   `json:"provider"`
	ProviderTrackID string   `json:"providerTrackId"`
	Title           string   `json:"title"`
	Artists         []string `json:"artists"`
	Album           string   `json:"album"`
	DurationMs      int64    `json:"durationMs"`
	Downloadable    bool     `json:"downloadable"`
	ISRC            string   `json:"isrc,omitempty"`
	// Slot is the account-order position this rendition fills when it is not a
	// provider's own: "self" for the caller's upload, "uploaded" for somebody
	// else's. Empty for a provider rendition, whose position is its provider.
	Slot  string      `json:"slot,omitempty"`
	Media MediaStatus `json:"media"`
}

Variant is one provider's rendition of a track.

Jump to

Keyboard shortcuts

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