about summary refs log tree commit diff
path: root/tools/mpd-stats/internal/scrobbler
diff options
context:
space:
mode:
authorFranck Cuny <franck@fcuny.net>2021-10-10 13:01:21 -0700
committerFranck Cuny <franck@fcuny.net>2022-06-11 14:32:08 -0700
commit1a29e26ab8223bdeea6544785a0539d64976f4ab (patch)
tree7817cc9deae9468cbe55d3fb0e848e01a5562e2a /tools/mpd-stats/internal/scrobbler
parentscrobbler: add timestamp to the record (diff)
downloadworld-1a29e26ab8223bdeea6544785a0539d64976f4ab.tar.gz
mpd-stats: pass database path to the scrobbler
When creating a scrobbler, we provide the path to the database. The
scrobbler then get a handler to the database.

When a new record is created, we persist it to the database using the
`save` function.
Diffstat (limited to 'tools/mpd-stats/internal/scrobbler')
-rw-r--r--tools/mpd-stats/internal/scrobbler/scrobbler.go31
1 files changed, 27 insertions, 4 deletions
diff --git a/tools/mpd-stats/internal/scrobbler/scrobbler.go b/tools/mpd-stats/internal/scrobbler/scrobbler.go
index 061b909..a31569e 100644
--- a/tools/mpd-stats/internal/scrobbler/scrobbler.go
+++ b/tools/mpd-stats/internal/scrobbler/scrobbler.go
@@ -1,6 +1,7 @@
 package scrobbler
 
 import (
+	"database/sql"
 	"log"
 
 	"golang.fcuny.net/mpd-stats/internal/mpd"
@@ -8,17 +9,25 @@ import (
 
 type Scrobbler struct {
 	player *mpd.Player
+	db     *sql.DB
 }
 
-func NewScrobbler(net string, addr string) (*Scrobbler, error) {
-	var s Scrobbler
-
+func NewScrobbler(net string, addr string, dbpath string) (*Scrobbler, error) {
 	p, err := mpd.NewPlayer(net, addr)
 	if err != nil {
 		return nil, err
 	}
 
-	s.player = p
+	db, err := opendatabase(dbpath)
+	if err != nil {
+		return nil, err
+	}
+
+	s := Scrobbler{
+		player: p,
+		db:     db,
+	}
+
 	return &s, nil
 }
 
@@ -47,6 +56,7 @@ func (s *Scrobbler) Run() error {
 				}
 				log.Printf("we're playing %s/%s/%s [%s]\n", currentRecord.Artist, currentRecord.Album, currentRecord.Title, currentRecord.Duration)
 				previousRecord = currentRecord
+				s.save(currentRecord)
 				continue
 			}
 
@@ -60,7 +70,20 @@ func (s *Scrobbler) Run() error {
 			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
+				s.save(currentRecord)
 			}
 		}
 	}
 }
+
+func (s *Scrobbler) save(record *Record) error {
+	_, err := s.db.Exec("insert into records(id, title, artist, album, duration, time) values(?, ?, ?, ?, ?, ?)",
+		record.Id,
+		record.Title,
+		record.Artist,
+		record.Album,
+		int(record.Duration.Seconds()),
+		record.Timestamp,
+	)
+	return err
+}