Store each client's play queue in the database

The queue lived in memory and was shared by all clients, so a restart or a
finished sync cleared it. Every client now has its own queue in the new
queue and queue_song tables (added to the undeployed migration 000006).

The music endpoints return the queue ID in the X-Queue-Id header and expect
it back. A request without an ID, or with an ended one, starts a new queue.
/music/reset ends the queue and returns a new ID, and a sync ends all
running queues. Ended queues are kept as history.

The deprecated legacy routes without the /api/v1 prefix are removed.
This commit is contained in:
Sansan committed 2026-10-07 20:03:03 +02:00
1 parent b5dc42b654
commit a705d7b476
28 files changed
+1103 -320

No files matched your search

+150 -85
View File
@@ -32,23 +32,19 @@ type SongInfo struct {
SongNo int `json:"SongNo"`
}
// MusicService picks songs and keeps track of the shared play queue.
// MusicService picks songs and keeps track of the play queues. Every client has its own queue,
// stored in the database and identified by its UUID.
type MusicService struct {
q repository.Querier
soundCheckPath string
cacheMu sync.Mutex
soundtracks []repository.Soundtrack
// Queue state is shared by all clients and intentionally not locked.
queue []repository.Song
currentSong int
lastFetched repository.Song
}
// NewMusicService creates a MusicService. soundCheckPath is the directory holding sound check songs.
func NewMusicService(q repository.Querier, soundCheckPath string) *MusicService {
return &MusicService{q: q, soundCheckPath: soundCheckPath, currentSong: -1}
return &MusicService{q: q, soundCheckPath: soundCheckPath}
}
func (m *MusicService) allSoundtracks(ctx context.Context) ([]repository.Soundtrack, error) {
@@ -64,10 +60,8 @@ func (m *MusicService) allSoundtracks(ctx context.Context) ([]repository.Soundtr
return m.soundtracks, nil
}
// Reset clears the play queue and reloads the soundtrack list.
func (m *MusicService) Reset(ctx context.Context) error {
m.queue = nil
m.currentSong = -1
// ReloadSoundtracks reloads the soundtrack list.
func (m *MusicService) ReloadSoundtracks(ctx context.Context) error {
m.cacheMu.Lock()
m.soundtracks = nil
m.cacheMu.Unlock()
@@ -75,6 +69,36 @@ func (m *MusicService) Reset(ctx context.Context) error {
return err
}
// ResolveQueue returns the queue with the given ID if it is a running queue.
// Otherwise, for example when id is empty or the queue has ended, it starts a new queue.
func (m *MusicService) ResolveQueue(ctx context.Context, id string) (uuid.UUID, error) {
if queueID, err := uuid.Parse(id); err == nil {
queue, err := m.q.GetQueue(ctx, queueID)
if err == nil && !queue.EndedAt.Valid {
return queue.Uuid, nil
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return uuid.Nil, err
}
}
queue, err := m.q.CreateQueue(ctx)
return queue.Uuid, err
}
// NewQueue ends the given queue and starts a new one.
func (m *MusicService) NewQueue(ctx context.Context, queueID uuid.UUID) (uuid.UUID, error) {
if err := m.q.EndQueue(ctx, queueID); err != nil {
return uuid.Nil, err
}
queue, err := m.q.CreateQueue(ctx)
return queue.Uuid, err
}
// EndAllQueues ends every running queue. Clients get a new queue on their next request.
func (m *MusicService) EndAllQueues(ctx context.Context) error {
return m.q.EndActiveQueues(ctx)
}
// SoundCheckSong returns the path of a random sound check song.
func (m *MusicService) SoundCheckSong() (string, error) {
files, err := os.ReadDir(m.soundCheckPath)
@@ -88,44 +112,53 @@ func (m *MusicService) SoundCheckSong() (string, error) {
return filepath.Join(m.soundCheckPath, files[rand.IntN(len(files))].Name()), nil
}
// AddLatestToQueue appends the last fetched random song to the queue.
func (m *MusicService) AddLatestToQueue() {
if m.lastFetched.Path != "" {
m.currentSong = len(m.queue)
m.queue = append(m.queue, m.lastFetched)
m.lastFetched = repository.Song{}
}
// AddLatestToQueue appends the last fetched random song to the queue and makes it the current song.
func (m *MusicService) AddLatestToQueue(ctx context.Context, queueID uuid.UUID) error {
return m.q.AddLastFetchedToQueue(ctx, queueID)
}
// AddLatestPlayed increments the play counters of the current song.
func (m *MusicService) AddLatestPlayed(ctx context.Context) error {
if !m.validIndex(m.currentSong) {
return nil
func (m *MusicService) AddLatestPlayed(ctx context.Context, queueID uuid.UUID) error {
queue, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return err
}
return m.markPlayed(ctx, m.queue[m.currentSong])
return m.markPlayed(ctx, songs, int(queue.CurrentSong))
}
// SetPlayed increments the play counters of the song at the given queue position.
func (m *MusicService) SetPlayed(ctx context.Context, songNumber int) error {
if !m.validIndex(songNumber) {
return nil
func (m *MusicService) SetPlayed(ctx context.Context, queueID uuid.UUID, songNumber int) error {
_, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return err
}
return m.markPlayed(ctx, m.queue[songNumber])
return m.markPlayed(ctx, songs, songNumber)
}
func (m *MusicService) markPlayed(ctx context.Context, song repository.Song) error {
// markPlayed increments the play counters of songs[songNumber]. Positions outside the queue
// and songs that have been removed from the library are ignored.
func (m *MusicService) markPlayed(ctx context.Context, songs []repository.ListQueueSongsRow, songNumber int) error {
if songNumber < 0 || songNumber >= len(songs) || songs[songNumber].Path == nil {
return nil
}
song := songs[songNumber]
if err := m.q.AddSoundtrackPlayedByUUID(ctx, song.SoundtrackUuid); err != nil {
return err
}
return m.q.AddSongPlayedByUUID(ctx, song.Uuid)
return m.q.AddSongPlayedByUUID(ctx, song.SongUuid)
}
func (m *MusicService) validIndex(i int) bool {
return i >= 0 && i < len(m.queue)
func (m *MusicService) loadQueue(ctx context.Context, queueID uuid.UUID) (repository.Queue, []repository.ListQueueSongsRow, error) {
queue, err := m.q.GetQueue(ctx, queueID)
if err != nil {
return repository.Queue{}, nil, err
}
songs, err := m.q.ListQueueSongs(ctx, queueID)
return queue, songs, err
}
// RandomSong picks a random song from a random soundtrack.
func (m *MusicService) RandomSong(ctx context.Context) (string, error) {
func (m *MusicService) RandomSong(ctx context.Context, queueID uuid.UUID) (string, error) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
return "", err
@@ -134,29 +167,37 @@ func (m *MusicService) RandomSong(ctx context.Context) (string, error) {
for i, s := range soundtracks {
candidates[i] = weightedSoundtrack{soundtrack: s, weight: 1}
}
return m.pickAndRemember(ctx, candidates)
return m.pickAndRemember(ctx, queueID, candidates)
}
// RandomSongLowChance picks a random song, favouring soundtracks played less than average.
func (m *MusicService) RandomSongLowChance(ctx context.Context) (string, error) {
func (m *MusicService) RandomSongLowChance(ctx context.Context, queueID uuid.UUID) (string, error) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
return "", err
}
return m.pickAndRemember(ctx, lowChanceWeights(soundtracks))
return m.pickAndRemember(ctx, queueID, lowChanceWeights(soundtracks))
}
func (m *MusicService) pickAndRemember(ctx context.Context, candidates []weightedSoundtrack) (string, error) {
func (m *MusicService) pickAndRemember(ctx context.Context, queueID uuid.UUID, candidates []weightedSoundtrack) (string, error) {
song, err := m.pickSong(ctx, candidates)
if err != nil {
return "", err
}
m.lastFetched = song
return m.remember(ctx, queueID, song)
}
// remember stores the song as the queue's last fetched song, for AddLatestToQueue.
func (m *MusicService) remember(ctx context.Context, queueID uuid.UUID, song repository.Song) (string, error) {
err := m.q.SetQueueLastFetched(ctx, repository.SetQueueLastFetchedParams{Uuid: queueID, LastFetchedSongUuid: song.Uuid})
if err != nil {
return "", err
}
return song.Path, nil
}
// RandomSongClassic picks a random song where every song has the same chance.
func (m *MusicService) RandomSongClassic(ctx context.Context) (string, error) {
func (m *MusicService) RandomSongClassic(ctx context.Context, queueID uuid.UUID) (string, error) {
for range maxPickAttempts {
row, err := m.q.GetRandomActiveSong(ctx)
if errors.Is(err, pgx.ErrNoRows) {
@@ -171,73 +212,97 @@ func (m *MusicService) RandomSongClassic(ctx context.Context) (string, error) {
}
continue
}
m.lastFetched = row.Song
return row.Song.Path, nil
return m.remember(ctx, queueID, row.Song)
}
return "", ErrNoSongs
}
// SongInfo returns information about the current song in the queue.
func (m *MusicService) SongInfo(ctx context.Context) SongInfo {
if !m.validIndex(m.currentSong) {
return SongInfo{}
func (m *MusicService) SongInfo(ctx context.Context, queueID uuid.UUID) (SongInfo, error) {
queue, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return SongInfo{}, err
}
song := m.queue[m.currentSong]
soundtrack := m.soundtrackFor(ctx, song)
return SongInfo{
SoundtrackUuid: soundtrack.Uuid,
Soundtrack: soundtrack.SoundtrackName,
SoundtrackPlayed: soundtrack.TimesPlayed,
SongUuid: song.Uuid,
Song: song.SongName,
SongPlayed: song.TimesPlayed,
CurrentlyPlaying: true,
SongNo: m.currentSong,
current := int(queue.CurrentSong)
if current < 0 || current >= len(songs) {
return SongInfo{}, nil
}
return m.songInfo(ctx, songs[current], true), nil
}
// PlayedSongs returns all songs in the queue.
func (m *MusicService) PlayedSongs(ctx context.Context) []SongInfo {
songList := []SongInfo{}
for i, song := range m.queue {
soundtrack := m.soundtrackFor(ctx, song)
songList = append(songList, SongInfo{
SoundtrackUuid: soundtrack.Uuid,
Soundtrack: soundtrack.SoundtrackName,
SoundtrackPlayed: soundtrack.TimesPlayed,
SongUuid: song.Uuid,
Song: song.SongName,
SongPlayed: song.TimesPlayed,
CurrentlyPlaying: i == m.currentSong,
SongNo: i,
})
func (m *MusicService) PlayedSongs(ctx context.Context, queueID uuid.UUID) ([]SongInfo, error) {
queue, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return nil, err
}
return songList
songList := []SongInfo{}
for _, song := range songs {
songList = append(songList, m.songInfo(ctx, song, song.SongNo == queue.CurrentSong))
}
return songList, nil
}
// songInfo describes a queued song. Songs removed from the library keep their stored names.
func (m *MusicService) songInfo(ctx context.Context, song repository.ListQueueSongsRow, current bool) SongInfo {
info := SongInfo{
SoundtrackUuid: song.SoundtrackUuid,
Soundtrack: song.SoundtrackName,
SongUuid: song.SongUuid,
Song: song.SongName,
CurrentlyPlaying: current,
SongNo: int(song.SongNo),
}
if song.TimesPlayed != nil {
info.SongPlayed = *song.TimesPlayed
}
if soundtrack, ok := m.soundtrackFor(ctx, song.SoundtrackUuid); ok {
info.Soundtrack = soundtrack.SoundtrackName
info.SoundtrackPlayed = soundtrack.TimesPlayed
}
return info
}
// Song jumps to the given queue position (clamped to the queue) and returns its path.
func (m *MusicService) Song(songNumber int) (string, error) {
if len(m.queue) == 0 {
return "", ErrQueueEmpty
func (m *MusicService) Song(ctx context.Context, queueID uuid.UUID, songNumber int) (string, error) {
_, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return "", err
}
m.currentSong = max(0, min(songNumber, len(m.queue)-1))
return m.queue[m.currentSong].Path, nil
return m.jump(ctx, queueID, songs, songNumber)
}
// NextSong moves to the next song in the queue, staying on the last one at the end.
func (m *MusicService) NextSong() (string, error) {
if len(m.queue) == 0 {
return "", ErrQueueEmpty
func (m *MusicService) NextSong(ctx context.Context, queueID uuid.UUID) (string, error) {
queue, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return "", err
}
return m.Song(m.currentSong + 1)
return m.jump(ctx, queueID, songs, int(queue.CurrentSong)+1)
}
// PreviousSong moves to the previous song in the queue, staying on the first one at the start.
func (m *MusicService) PreviousSong() (string, error) {
if len(m.queue) == 0 {
func (m *MusicService) PreviousSong(ctx context.Context, queueID uuid.UUID) (string, error) {
queue, songs, err := m.loadQueue(ctx, queueID)
if err != nil {
return "", err
}
return m.jump(ctx, queueID, songs, int(queue.CurrentSong)-1)
}
func (m *MusicService) jump(ctx context.Context, queueID uuid.UUID, songs []repository.ListQueueSongsRow, songNumber int) (string, error) {
if len(songs) == 0 {
return "", ErrQueueEmpty
}
return m.Song(m.currentSong - 1)
songNumber = max(0, min(songNumber, len(songs)-1))
err := m.q.SetQueueCurrentSong(ctx, repository.SetQueueCurrentSongParams{Uuid: queueID, CurrentSong: int32(songNumber)})
if err != nil {
return "", err
}
if songs[songNumber].Path == nil {
return "", ErrNotFound
}
return *songs[songNumber].Path, nil
}
// SoundtrackNames returns all soundtrack names in alphabetical order.
@@ -352,16 +417,16 @@ func songIsPlayable(song repository.Song, soundtrackPath string) bool {
return err == nil && !info.IsDir()
}
func (m *MusicService) soundtrackFor(ctx context.Context, song repository.Song) repository.Soundtrack {
func (m *MusicService) soundtrackFor(ctx context.Context, soundtrackUUID uuid.UUID) (repository.Soundtrack, bool) {
soundtracks, err := m.allSoundtracks(ctx)
if err != nil {
logging.GetLogger().Error("Failed to load soundtracks", zap.Error(err))
return repository.Soundtrack{}
return repository.Soundtrack{}, false
}
for _, soundtrack := range soundtracks {
if soundtrack.Uuid == song.SoundtrackUuid {
return soundtrack
if soundtrack.Uuid == soundtrackUUID {
return soundtrack, true
}
}
return repository.Soundtrack{}
return repository.Soundtrack{}, false
}