feat(music): persist live playback state to postgres
The queue and now-playing state only ever lived in the bot's memory, so the dashboard had nothing real to show and a restart silently wiped whatever was queued. Adds a musicrepo package and a syncState call after every queue-changing action (play, skip, pause, volume, stop, track end) that mirrors the current track and queue into music_now_playing and music_queue. No user-visible change yet, this is groundwork for the dashboard queue/now-playing view.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package musicrepo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QueueEntry struct {
|
||||
Title string
|
||||
URL string
|
||||
RequestedBy int64
|
||||
}
|
||||
|
||||
type Repo struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewRepo(db *sql.DB) *Repo {
|
||||
return &Repo{db: db}
|
||||
}
|
||||
|
||||
func (r *Repo) SetNowPlaying(ctx context.Context, guildID int64, title, url string, durationSeconds int, startedAt time.Time, paused bool, volume int) error {
|
||||
const q = `INSERT INTO music_now_playing (guild_id, track_title, track_url, duration_seconds, started_at, paused, volume) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (guild_id) DO UPDATE SET track_title = $2, track_url = $3, duration_seconds = $4, started_at = $5, paused = $6, volume = $7`
|
||||
_, err := r.db.ExecContext(ctx, q, guildID, title, url, durationSeconds, startedAt, paused, volume)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repo) ClearNowPlaying(ctx context.Context, guildID int64) error {
|
||||
const q = `DELETE FROM music_now_playing WHERE guild_id = $1`
|
||||
_, err := r.db.ExecContext(ctx, q, guildID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Repo) ReplaceQueue(ctx context.Context, guildID int64, entries []QueueEntry) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
const q = `DELETE FROM music_queue WHERE guild_id = $1`
|
||||
_, err = tx.ExecContext(ctx, q, guildID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, entry := range entries {
|
||||
const q = `INSERT INTO music_queue (guild_id, track_title, track_url, requested_by, position) VALUES ($1, $2, $3, $4, $5)`
|
||||
_, err = tx.ExecContext(ctx, q, guildID, entry.Title, entry.URL, entry.RequestedBy, i)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
Reference in New Issue
Block a user