about summary refs log tree commit diff
path: root/tools/mpd-stats/internal/scrobbler/scrobbler.go
blob: a31569edb3b640bcc4ad5df18a3e0f551828f0b9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package scrobbler

import (
	"database/sql"
	"log"

	"golang.fcuny.net/mpd-stats/internal/mpd"
)

type Scrobbler struct {
	player *mpd.Player
	db     *sql.DB
}

func NewScrobbler(net string, addr string, dbpath string) (*Scrobbler, error) {
	p, err := mpd.NewPlayer(net, addr)
	if err != nil {
		return nil, err
	}

	db, err := opendatabase(dbpath)
	if err != nil {
		return nil, err
	}

	s := Scrobbler{
		player: p,
		db:     db,
	}

	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
				s.save(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
				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
}