aboutsummaryrefslogtreecommitdiff
path: root/internal/scrobbler/scrobbler.go
diff options
context:
space:
mode:
authorFranck Cuny <franck@fcuny.net>2021-10-10 11:44:47 -0700
committerFranck Cuny <franck@fcuny.net>2021-10-10 11:44:47 -0700
commit6440b7f28190eff567fa411ead2adbd80d2d870e (patch)
tree3407d4f4cc6cddfa58f371ae428960446df4e4b7 /internal/scrobbler/scrobbler.go
parentmpd: export the type Player (diff)
downloadx-6440b7f28190eff567fa411ead2adbd80d2d870e.tar.gz
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.
Diffstat (limited to 'internal/scrobbler/scrobbler.go')
-rw-r--r--internal/scrobbler/scrobbler.go66
1 files changed, 66 insertions, 0 deletions
diff --git a/internal/scrobbler/scrobbler.go b/internal/scrobbler/scrobbler.go
new file mode 100644
index 0000000..061b909
--- /dev/null
+++ b/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
+ }
+ }
+ }
+}