package bragi import ( "bytes" "errors" "fmt" "image" "io" "path" "strconv" "strings" "sync" "time" _ "image/gif" // GIF codec _ "image/jpeg" // JPEG codec _ "image/png" // PNG codec "github.com/fhs/gompd/v2/mpd" "github.com/sirupsen/logrus" ) type mpdSource struct { addr string password string quit chan struct{} events chan Event playlistMutex sync.RWMutex playlist map[string]*Track } func NewMPD(addr string) Source { s := &mpdSource{ addr: addr, quit: make(chan struct{}, 1), events: make(chan Event), playlist: make(map[string]*Track), } go s.connect() return s } func (s *mpdSource) Name() string { return "MPD" } func (s *mpdSource) Events() <-chan Event { return s.events } func (s *mpdSource) log() *logrus.Entry { return logrus.WithFields(logrus.Fields{ "source": "MPD", "addr": s.addr, }) } func (s *mpdSource) connect() { var ( log = s.log() c *mpd.Client w *mpd.Watcher attempt int err error ) for { if s.password != "" { log.Debug("connecting to MPD (with password)") c, err = mpd.DialAuthenticated("tcp", s.addr, s.password) } else { log.Debug("connecting to MPD") c, err = mpd.Dial("tcp", s.addr) } if err == nil { log.Debug("connecting to MPD watcher") w, err = mpd.NewWatcher("tcp", s.addr, s.password) } if err != nil { log. WithError(err). WithField("attempt", attempt). Error("failed to connect to MPD") if c != nil { _ = c.Close() } if w != nil { _ = w.Close() } backoff(attempt) attempt++ continue } // Connected. log.Info("connected to MPD") attempt = 0 s.poll(c, w) log.Info("disconnected from MPD; retrying") } } func (s *mpdSource) emit(e Event) { select { case s.events <- e: default: logrus.Warn("dropped event") } } func (s *mpdSource) poll(c *mpd.Client, w *mpd.Watcher) { log := s.log() log.Trace("polling MPD events") ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for { select { case <-s.quit: log.Info("disconnecting from MPD") _ = c.Close() _ = w.Close() return case <-ticker.C: if err := s.sendStatus(c); err != nil { log. WithError(err). Error("failed to get MPD status") _ = c.Close() _ = w.Close() return } case subsystem := <-w.Event: if err := s.onSubsystemUpdate(c, subsystem); errors.Is(err, io.EOF) { log.Info("MPD subsystem update EOF; disconnecting") _ = c.Close() w = nil // don't close w, it's already closed on EOF return } else if err != nil { log.WithError(err).Error("MPD subsystem update error") } case err := <-w.Error: log. WithError(err). Error("MPD watcher error") _ = c.Close() _ = w.Close() return } } } func (s *mpdSource) onSubsystemUpdate(c *mpd.Client, subsystem string) error { log := s.log() log. WithField("subsystem", subsystem). Info("MPD subsystem update") switch subsystem { case "": return io.EOF case "player": if err := s.sendStatus(c); err != nil { return fmt.Errorf("mpd: failed to get status: %w", err) } case "playlist": if err := s.updatePlaylist(c); err != nil { return fmt.Errorf("mpd: failed to get playlist: %w", err) } default: log. WithField("subsystem", subsystem). Info("unhandled MPD subsystem update") } return nil } func (s *mpdSource) sendStatus(c *mpd.Client) error { log := s.log() log.Debug("getting MPD status") status, err := c.Status() if err != nil { return err } if v := status["state"]; v == "play" || v == "pause" { if len(s.playlist) == 0 { if err = s.updatePlaylist(c); err != nil { return err } } } e := &Status{ source: s, Audio: status["audio"], } s.playlistMutex.RLock() { e.Track = s.playlist[status["songid"]] } s.playlistMutex.RUnlock() e.Bitrate, _ = strconv.Atoi(status["bitrate"]) e.Volume, _ = strconv.Atoi(status["volume"]) e.Elapsed, _ = time.ParseDuration(status["elapsed"] + "s") e.ElapsedPercentage, _ = strconv.ParseFloat(status["elapsedpercentage"], 64) if err = s.updateTrackImage(c, e.Track); err != nil { log.WithError(err).Error("failed to update track image") } s.emit(NewStatusEvent(s, e)) return nil } func (s *mpdSource) updatePlaylist(c *mpd.Client) error { log := s.log() log.Debug("getting MPD playlist") playlist := make(map[string]*Track) info, err := c.PlaylistInfo(-1, -1) if err != nil { return err } log.Infof("got %d tracks in playlist", len(info)) for _, track := range info { logrus.WithField("track", track).Trace("got track") playlist[track["Id"]] = parseMPDTrack(track) } s.playlistMutex.Lock() { s.playlist = playlist } s.playlistMutex.Unlock() return nil } func parseMPDTrack(track mpd.Attrs) *Track { t := &Track{ Artist: track["Artist"], Title: track["Title"], Album: track["Album"], Label: track["Label"], Format: track["Format"], Genre: strings.Split(track["Genre"], ","), } t.Track, _ = strconv.Atoi(track["Track"]) t.Disc, _ = strconv.Atoi(track["Disc"]) t.Duration, _ = time.ParseDuration(track["Time"] + "s") t.Date, _ = time.Parse("2006-01-02", track["Date"]) t.Path = track["file"] return t } func (s *mpdSource) updateTrackImage(c *mpd.Client, t *Track) error { if t == nil || t.Image != nil || t.Path == "" { return nil } log := s.log(). WithField("track", t). WithField("path", path.Dir(t.Path)) log.Debug("updating track image") t.Image = image.Black var trackImageData []byte // First we try to read the picture from the track. if trackImage, err := c.ReadPicture(t.Path); err == nil { log.WithField("size", len(trackImage)).Debug("read picture data as track image") trackImageData = trackImage // If that fails, we try to read the picture from the album. } else { dir := path.Dir(t.Path) try := []string{ path.Join(dir, "discart.png"), path.Join(dir, "discart.jpg"), path.Join(dir, "cover.png"), path.Join(dir, "cover.jpg"), } for _, p := range try { b, err := c.AlbumArt(p) if err != nil { logrus.WithError(err).Error("failed to read picture") continue } log.WithField("size", len(b)).Debug("read picture data as track image") trackImageData = b break } } if trackImageData != nil { img, kind, err := image.Decode(bytes.NewBuffer(trackImageData)) if err != nil { return err } log.WithField("kind", kind).Debugf("decoded %s picture data as track image", img.Bounds().Size()) t.Image = img } return nil }