2023-10-01 00:47:07 +04:00
|
|
|
package radio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2023-10-05 17:36:02 +04:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2023-10-01 00:47:07 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Playlist holds a list of paths to a song files.
|
|
|
|
type Playlist struct {
|
2024-05-22 04:07:33 +04:00
|
|
|
sync.Mutex
|
2023-10-01 00:47:07 +04:00
|
|
|
playlist []string
|
|
|
|
cur int
|
|
|
|
repeat bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewPlaylist returns an instance of a Playlist struct with a loaded playlist.
|
2025-01-15 23:35:41 +04:00
|
|
|
// Returns an error if failed to load a playlist.
|
|
|
|
func NewPlaylistFromPlaintext(data []byte, repeat bool) (*Playlist, error) {
|
|
|
|
p := &Playlist{repeat: repeat}
|
|
|
|
return p, p.LoadFromPlaintext(data)
|
2023-10-01 00:47:07 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Next returns the next song to play. Returns an empty string if repeat is
|
|
|
|
// false and the end of a playlist was reached.
|
|
|
|
func (p *Playlist) Next() (song string) {
|
|
|
|
if p.cur == len(p.playlist) {
|
|
|
|
// If the end of a playlist was reached and repeat is set to true,
|
|
|
|
// then go back to the head of it, thus repeating it. Return an empty
|
|
|
|
// string otherwise.
|
|
|
|
if p.repeat {
|
|
|
|
p.cur = 0
|
|
|
|
} else {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
song = p.playlist[p.cur]
|
|
|
|
p.cur++
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2025-01-15 23:35:41 +04:00
|
|
|
// Load accepts a byte array of plaintext data and parses it into an array of strings.
|
|
|
|
// Also resets a cur index to 0 to start over.
|
|
|
|
func (p *Playlist) LoadFromPlaintext(data []byte) error {
|
2023-10-07 23:17:42 +04:00
|
|
|
if len(data) == 0 {
|
2025-01-15 23:35:41 +04:00
|
|
|
return errors.New("an empty playlist array was passed")
|
2023-10-07 23:17:42 +04:00
|
|
|
}
|
|
|
|
|
2023-10-01 00:47:07 +04:00
|
|
|
p.playlist = strings.Split(string(data), "\n")
|
|
|
|
p.cur = 0
|
2023-10-07 23:17:42 +04:00
|
|
|
|
2023-10-01 00:47:07 +04:00
|
|
|
return nil
|
|
|
|
}
|