482 lines
10 KiB
Go
482 lines
10 KiB
Go
package mpd
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/textproto"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"go.maze.io/harmon/config"
|
|
"go.maze.io/harmon/internal/util"
|
|
"go.maze.io/harmon/player"
|
|
)
|
|
|
|
func init() {
|
|
player.Register("mpd", func(config config.Player) (player.Player, error) {
|
|
return New(config.Host, config.Password)
|
|
}, Detect, 10)
|
|
}
|
|
|
|
const (
|
|
DefaultPort = "6600"
|
|
DefaultAddr = "localhost:" + DefaultPort
|
|
)
|
|
|
|
type Player struct {
|
|
// Version is the server protocol version.
|
|
Version Version
|
|
|
|
name string
|
|
addr string
|
|
password string
|
|
idleSubsystems []string
|
|
artCache sync.Map // map of path to image
|
|
artRequest chan *artRequest
|
|
commands chan *Command
|
|
errors chan error
|
|
quit chan struct{}
|
|
}
|
|
|
|
type clientConn struct {
|
|
*textproto.Conn
|
|
name string
|
|
}
|
|
|
|
func (c *clientConn) log() *logrus.Entry {
|
|
return logrus.WithFields(logrus.Fields{
|
|
"protocol": "mpd",
|
|
"loop": c.name,
|
|
})
|
|
}
|
|
|
|
// Version number.
|
|
type Version struct {
|
|
Major int
|
|
Minor int
|
|
Patch int
|
|
}
|
|
|
|
func (v Version) String() string {
|
|
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
|
|
}
|
|
|
|
func versionError(s string) error {
|
|
return fmt.Errorf("mpd: unexpected version %q", s)
|
|
}
|
|
|
|
func ParseVersion(s string) (Version, error) {
|
|
part := strings.Split(s, ".")
|
|
if len(part) != 3 {
|
|
return Version{}, versionError(s)
|
|
}
|
|
|
|
var (
|
|
v Version
|
|
err error
|
|
)
|
|
if v.Major, err = strconv.Atoi(part[0]); err != nil {
|
|
return Version{}, err
|
|
}
|
|
if v.Minor, err = strconv.Atoi(part[1]); err != nil {
|
|
return Version{}, err
|
|
}
|
|
if v.Patch, err = strconv.Atoi(part[2]); err != nil {
|
|
return Version{}, err
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
func New(addr, password string) (*Player, error) {
|
|
addr = util.MakeAddr(addr, DefaultAddr)
|
|
if _, err := net.ResolveTCPAddr("tcp", addr); err != nil {
|
|
return nil, err
|
|
}
|
|
p := &Player{
|
|
addr: addr,
|
|
commands: make(chan *Command, 16),
|
|
artRequest: make(chan *artRequest, 16),
|
|
errors: make(chan error, 1),
|
|
quit: make(chan struct{}, 2),
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func newConn(addr, password, kind, name string) (*clientConn, *Version, error) {
|
|
log := logrus.WithFields(logrus.Fields{
|
|
"protocol": "mpd",
|
|
"player": name,
|
|
"addr": addr,
|
|
"conn": kind,
|
|
})
|
|
|
|
if addr == "" {
|
|
addr = DefaultAddr
|
|
}
|
|
|
|
log.Info("connecting to Music Player Daemon")
|
|
conn, err := textproto.Dial("tcp", addr)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
line, err := conn.ReadLine()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
log.WithField("response", line).Trace("reading server hello")
|
|
if !strings.HasPrefix(line, "OK MPD ") {
|
|
_ = conn.Close()
|
|
return nil, nil, fmt.Errorf("mpd: unexpected server greeting %q", line)
|
|
}
|
|
|
|
version, err := ParseVersion(line[7:])
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
return nil, nil, fmt.Errorf("mpd: unexpected server version %q: %w", line[6:], err)
|
|
}
|
|
|
|
if password != "" {
|
|
log.Debug("sending password")
|
|
id, err := conn.Cmd("password %s", password)
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
return nil, nil, err
|
|
}
|
|
conn.StartResponse(id)
|
|
defer conn.EndResponse(id)
|
|
if line, err = conn.ReadLine(); err != nil {
|
|
_ = conn.Close()
|
|
return nil, nil, err
|
|
}
|
|
log.WithField("response", line).Trace("reading server password response")
|
|
if line != "OK" {
|
|
_ = conn.Close()
|
|
return nil, nil, fmt.Errorf("mpd: unexpected response to password: %q", line)
|
|
}
|
|
}
|
|
|
|
return &clientConn{conn, kind}, &version, nil
|
|
}
|
|
|
|
func (Player) Type() string { return "mpd" }
|
|
|
|
func (p *Player) Halt() error {
|
|
for i := 0; i < 2; i++ {
|
|
select {
|
|
case p.quit <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
select {
|
|
case err := <-p.errors:
|
|
return err
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (p *Player) sendCommand(conn *clientConn, format string, args ...interface{}) (err error) {
|
|
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
|
|
log.Trace("sending command")
|
|
|
|
var id uint
|
|
if id, err = conn.Cmd(format, args...); err != nil {
|
|
log.WithError(err).Warn("command failed")
|
|
return
|
|
}
|
|
|
|
log = log.WithField("id", id)
|
|
log.Trace("start response")
|
|
conn.StartResponse(id)
|
|
|
|
for {
|
|
var line string
|
|
if line, err = conn.ReadLine(); err != nil {
|
|
log.WithError(err).Warn("command response read failed")
|
|
break
|
|
}
|
|
|
|
log.WithField("data", line).Trace("command response")
|
|
if line == "OK" {
|
|
break
|
|
}
|
|
}
|
|
|
|
log.Trace("end response")
|
|
conn.EndResponse(id)
|
|
return
|
|
}
|
|
|
|
func (p *Player) sendCommandList(conn *clientConn, commands []Command) (err error) {
|
|
log := conn.log()
|
|
log.Trace("sending command list")
|
|
|
|
if len(commands) == 0 {
|
|
return
|
|
}
|
|
|
|
id := conn.Next()
|
|
conn.StartRequest(id)
|
|
if err = conn.PrintfLine("command_list_begin"); err != nil {
|
|
return
|
|
}
|
|
for _, command := range commands {
|
|
if err = conn.PrintfLine(command.Format, command.Args...); err != nil {
|
|
conn.EndRequest(id)
|
|
return
|
|
}
|
|
}
|
|
if err = conn.PrintfLine("command_list_end"); err != nil {
|
|
return
|
|
}
|
|
conn.EndRequest(id)
|
|
|
|
log = log.WithField("id", id)
|
|
log.Trace("start response")
|
|
conn.StartResponse(id)
|
|
conn.EndResponse(id)
|
|
|
|
return
|
|
}
|
|
|
|
func (p *Player) sendMapCommand(conn *clientConn, format string, args ...interface{}) (kv map[string]string, err error) {
|
|
log := conn.log().WithField("command", fmt.Sprintf(format, args...))
|
|
log.Trace("sending map command")
|
|
|
|
var id uint
|
|
if id, err = conn.Cmd(format, args...); err != nil {
|
|
log.WithError(err).Warn("map command failed")
|
|
return
|
|
}
|
|
|
|
log = log.WithField("id", id)
|
|
log.Trace("start map response")
|
|
conn.StartResponse(id)
|
|
|
|
kv = make(map[string]string)
|
|
for {
|
|
var line string
|
|
if line, err = conn.ReadLine(); err != nil {
|
|
log.WithError(err).Warn("command response read failed")
|
|
break
|
|
}
|
|
|
|
log.WithField("data", line).Trace("command response")
|
|
if line == "OK" {
|
|
break
|
|
} else if i := strings.Index(line, ": "); i > 0 {
|
|
kv[line[:i]] = line[i+2:]
|
|
}
|
|
}
|
|
|
|
log.Trace("end map response")
|
|
conn.EndResponse(id)
|
|
return
|
|
}
|
|
|
|
func (p *Player) run(events chan player.Event) {
|
|
log := logrus.WithFields(logrus.Fields{
|
|
"protocol": "mpd",
|
|
})
|
|
log.Info("starting client")
|
|
|
|
events <- player.NewDisconnectedEvent(p)
|
|
|
|
for {
|
|
main, version, err := newConn(p.addr, p.password, "main", p.name)
|
|
if err != nil {
|
|
log.WithError(err).Warn("connection failed; retrying")
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
main.log().WithField("version", version).Info("connected to Music Player Daemon")
|
|
|
|
idle, _, err := newConn(p.addr, p.password, "idle", p.name)
|
|
if err != nil {
|
|
_ = main.Close()
|
|
log.WithError(err).Warn("connection failed; retrying")
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
|
|
art, _, err := newConn(p.addr, p.password, "art", p.name)
|
|
if err != nil {
|
|
_ = idle.Close()
|
|
_ = main.Close()
|
|
log.WithError(err).Warn("connection failed; retrying")
|
|
time.Sleep(time.Second)
|
|
continue
|
|
}
|
|
|
|
p.commands = make(chan *Command)
|
|
p.errors = make(chan error)
|
|
p.quit = make(chan struct{}, 2)
|
|
|
|
events <- player.NewConnectedEvent(p)
|
|
|
|
go p.idleLoop(idle)
|
|
go p.artLoop(art)
|
|
p.mainLoop(main, events)
|
|
|
|
events <- player.NewDisconnectedEvent(p)
|
|
|
|
_ = idle.Close()
|
|
_ = main.Close()
|
|
close(p.commands)
|
|
close(p.errors)
|
|
}
|
|
|
|
log.Warn("client terminating")
|
|
}
|
|
|
|
func (p *Player) mainLoop(conn *clientConn, events chan player.Event) {
|
|
defer func() {
|
|
_ = conn.Close()
|
|
}()
|
|
|
|
log := conn.log()
|
|
log.Debug("starting loop")
|
|
|
|
ticker := time.NewTicker(time.Second)
|
|
defer ticker.Stop()
|
|
|
|
var err error
|
|
loop:
|
|
for {
|
|
select {
|
|
case command := <-p.commands:
|
|
if command == nil {
|
|
break loop
|
|
}
|
|
if err = p.sendCommand(conn, command.Format, command.Args...); err != nil {
|
|
command.Err <- err
|
|
break loop
|
|
} else {
|
|
command.Err <- nil
|
|
}
|
|
|
|
case <-ticker.C:
|
|
var status map[string]string
|
|
if status, err = p.sendMapCommand(conn, "status"); err != nil {
|
|
log.WithError(err).Error("error retrieving status")
|
|
break loop
|
|
}
|
|
log.WithField("status", status).Debug("status")
|
|
|
|
var track map[string]string
|
|
if track, err = p.sendMapCommand(conn, "currentsong"); err != nil {
|
|
log.WithError(err).Error("error retrieving current song")
|
|
break loop
|
|
}
|
|
|
|
events <- player.NewStatusEvent(p, parseStatus(p, status, track))
|
|
|
|
case <-p.quit:
|
|
break loop
|
|
}
|
|
}
|
|
if err != nil {
|
|
log.WithError(err).Error("main loop terminating")
|
|
select {
|
|
case p.errors <- err:
|
|
default:
|
|
}
|
|
} else {
|
|
log.Info("main loop terminating")
|
|
}
|
|
select {
|
|
case p.quit <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
|
|
func (p *Player) Events() (<-chan player.Event, error) {
|
|
events := make(chan player.Event)
|
|
go p.run(events)
|
|
return events, nil
|
|
}
|
|
|
|
func (Player) Status() *player.Status {
|
|
return nil
|
|
}
|
|
|
|
func (p *Player) Name() string {
|
|
return p.name
|
|
}
|
|
|
|
func (p *Player) Command(format string, args ...interface{}) error {
|
|
command := newCommand(format, args...)
|
|
p.commands <- command
|
|
return <-command.Err
|
|
}
|
|
|
|
func (p *Player) Play() error { return p.Command("play") }
|
|
func (p *Player) Pause() error { return p.Command("pause") }
|
|
func (p *Player) Next() error { return p.Command("next") }
|
|
func (p *Player) Previous() error { return p.Command("previous") }
|
|
func (p *Player) Seek(d time.Duration) error { return p.Command("seekcur %f", d.Seconds()) }
|
|
|
|
type Command struct {
|
|
Format string
|
|
Args []interface{}
|
|
Err chan error
|
|
}
|
|
|
|
func newCommand(format string, args ...interface{}) *Command {
|
|
return &Command{
|
|
Format: format,
|
|
Args: args,
|
|
Err: make(chan error),
|
|
}
|
|
}
|
|
|
|
func parseStatus(p player.Player, status, track map[string]string) *player.Status {
|
|
s := &player.Status{
|
|
Player: p,
|
|
}
|
|
s.Source, _ = player.ParseMPDAudioFormat(status["audio"])
|
|
s.Source.BitRate, _ = strconv.Atoi(status["bitrate"])
|
|
s.Elapsed, _ = time.ParseDuration(status["elapsed"] + "s")
|
|
s.Volume, _ = strconv.Atoi(status["volume"])
|
|
switch status["state"] {
|
|
case "play":
|
|
s.Playing = true
|
|
s.Paused = false
|
|
case "pause":
|
|
s.Playing = true
|
|
s.Paused = false
|
|
}
|
|
s.Repeat = status["repeat"] == "1"
|
|
s.Shuffle = status["shuffle"] == "1"
|
|
|
|
// Parse track information.
|
|
s.Track, s.Source = parseTrack(track)
|
|
|
|
return s
|
|
}
|
|
|
|
func parseTrack(data map[string]string) (*player.Track, player.AudioFormat) {
|
|
track := &player.Track{
|
|
Artist: data["Artist"],
|
|
Title: data["Title"],
|
|
Album: data["Album"],
|
|
Label: data["Label"],
|
|
Genre: strings.Split(data["Genra"], ";"),
|
|
Path: data["file"],
|
|
}
|
|
track.Track, _ = strconv.Atoi(data["Track"])
|
|
track.Disc, _ = strconv.Atoi(data["Disc"])
|
|
track.Date, _ = time.Parse("2006-02-01", data["Date"])
|
|
track.Duration, _ = time.ParseDuration(data["duration"] + "s")
|
|
|
|
audio, _ := player.ParseMPDAudioFormat(data["Format"])
|
|
|
|
return track, audio
|
|
}
|