about summary refs log tree commit diff
path: root/tools
diff options
context:
space:
mode:
authorFranck Cuny <franck@fcuny.net>2021-10-10 11:44:47 -0700
committerFranck Cuny <franck@fcuny.net>2022-06-11 14:32:07 -0700
commit3dc1f1d4652aba2986c540bcc2a22c1b21e89e98 (patch)
tree5953d3362b85c580b744ffa92419534b664ca7a5 /tools
parentmpd: export the type Player (diff)
downloadworld-3dc1f1d4652aba2986c540bcc2a22c1b21e89e98.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 'tools')
-rw-r--r--tools/mpd-stats/internal/scrobbler/scrobbler.go66
1 files changed, 66 insertions, 0 deletions
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
+			}
+		}
+	}
+}