From 3dc1f1d4652aba2986c540bcc2a22c1b21e89e98 Mon Sep 17 00:00:00 2001 From: Franck Cuny Date: Sun, 10 Oct 2021 11:44:47 -0700 Subject: scrobbler: add functions to create and run it Add a new function to create a scrobbler. The function takes care of creating the mpd client. Add a function to run the scrobbler, which takes care of creating a new record when needed. This will simplify the interface for the caller, as all they really care about is: create the scrobbler, close it when we're done, and collect songs information while we listen to our music. --- tools/mpd-stats/internal/scrobbler/scrobbler.go | 66 +++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 tools/mpd-stats/internal/scrobbler/scrobbler.go (limited to 'tools/mpd-stats') diff --git a/tools/mpd-stats/internal/scrobbler/scrobbler.go b/tools/mpd-stats/internal/scrobbler/scrobbler.go new file mode 100644 index 0000000..061b909 --- /dev/null +++ b/tools/mpd-stats/internal/scrobbler/scrobbler.go @@ -0,0 +1,66 @@ +package scrobbler + +import ( + "log" + + "golang.fcuny.net/mpd-stats/internal/mpd" +) + +type Scrobbler struct { + player *mpd.Player +} + +func NewScrobbler(net string, addr string) (*Scrobbler, error) { + var s Scrobbler + + p, err := mpd.NewPlayer(net, addr) + if err != nil { + return nil, err + } + + s.player = p + return &s, nil +} + +func (s *Scrobbler) Close() error { + return s.player.Close() +} + +func (s *Scrobbler) Run() error { + var ( + currentRecord *Record + previousRecord *Record + ) + + for { + e := <-s.player.Watcher.Event + if e != "" { + attrs, err := s.player.Client.CurrentSong() + if err != nil { + log.Fatalf("could not get current song: %v", err) + } + + if currentRecord == nil { + currentRecord, err = NewRecord(attrs) + if err != nil { + log.Fatalf("could not create a log: %v", err) + } + log.Printf("we're playing %s/%s/%s [%s]\n", currentRecord.Artist, currentRecord.Album, currentRecord.Title, currentRecord.Duration) + previousRecord = currentRecord + continue + } + + if currentRecord.Title != attrs["Title"] || currentRecord.Artist != attrs["Artist"] || currentRecord.Album != attrs["Album"] { + currentRecord, err = NewRecord(attrs) + if err != nil { + log.Fatalf("could not create a log: %v", err) + } + } + + if currentRecord.Id != previousRecord.Id { + log.Printf("we're playing %s/%s/%s [%s]\n", currentRecord.Artist, currentRecord.Album, currentRecord.Title, currentRecord.Duration) + previousRecord = currentRecord + } + } + } +} -- cgit 1.4.1