-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
508 lines (439 loc) · 12.4 KB
/
main.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
* Copyright (c) 2023 Savio Sena <savio.sena@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
_ "embed"
"github.com/fhs/gompd/mpd"
"github.com/spf13/viper"
)
const ConfigDir = "mpd-brainz"
const ConfigFile = "mpd-brainz.conf"
const DefaultLogFile = "mpd-brainz.log"
const ListenBrainzURL = "https://api.listenbrainz.org/1/submit-listens"
//go:embed VERSION
var Version string
func version() {
fmt.Printf("mpd-brainz v%s", Version)
os.Exit(0)
}
var Logger *log.Logger = log.New(os.Stdout, "", log.LstdFlags)
func Log(fmt string, args ...any) {
Logger.Printf(fmt+"\n", args...)
}
func Debug(fmt string, args ...any) {
if verbose {
Logger.Printf(fmt+"\n", args...)
}
}
func Error(fmt string, args ...any) {
Logger.Printf("error: "+fmt+"\n", args...)
}
func Fatal(fmt string, args ...any) {
Logger.Fatalf("error: "+fmt+"\n", args...)
}
type Info struct {
MediaPlayer string `json:"media_player,omitempty"`
MusicService string `json:"music_service,omitempty"`
MusicServiceName string `json:"music_service_name,omitempty"`
OriginUrl string `json:"origin_url,omitempty"`
SubmissionClient string `json:"submission_client,omitempty"`
SubmissionClientVersion string `json:"submission_client_version,omitempty"`
Tags []string `json:"tags,omitempty"`
Duration int `json:"duration,omitempty"`
}
type Track struct {
Info Info `json:"additional_info,omitempty"`
ArtistName string `json:"artist_name,omitempty"`
TrackName string `json:"track_name,omitempty"`
ReleaseName string `json:"release_name,omitempty"`
}
type Listen struct {
ListenedAt int64 `json:"listened_at,omitempty"`
Track Track `json:"track_metadata,omitempty"`
}
func (l *Listen) String() string {
return fmt.Sprintf("\"%s - %s\"", l.Track.ArtistName, l.Track.TrackName)
}
type Listens struct {
ListenType string `json:"listen_type,omitempty"`
Payload []Listen `json:"payload,omitempty"`
}
const ListensMaxSize = 500
func NewListens(listenType string) Listens {
return Listens{
ListenType: listenType,
Payload: []Listen{},
}
}
func NewListen(listenType string, artistName string, trackName string,
releaseName string, originUrl string, musicService string, timestamp int64) Listens {
listens := NewListens("single")
listens.Add(artistName, trackName, releaseName, originUrl, musicService, timestamp)
return listens
}
func (l *Listens) Length() int {
return len(l.Payload)
}
func (l *Listens) String() string {
s := ""
n := l.Length()
if n == 1 {
return l.Payload[0].String()
}
for i := 0; i < n; i++ {
t := l.Payload[i].String()
if i != n-1 {
t += ", "
}
s += t
}
return fmt.Sprintf("{%s, [%s]}", l.ListenType, s)
}
func (l *Listens) IsNil() bool {
return l == nil ||
l.Length() == 0 ||
l.Payload[0].Track.ArtistName == "" ||
l.Payload[0].Track.TrackName == ""
}
func (l *Listens) Equal(o Listens) bool {
return l != nil && l.Length() > 0 && o.Length() > 0 &&
l.Payload[0].Track.ArtistName == o.Payload[0].Track.ArtistName &&
l.Payload[0].Track.TrackName == o.Payload[0].Track.TrackName
}
func (l *Listens) Add(artistName string, trackName string, releaseName string,
originUrl string, musicService string, listenedAt int64) {
if listenedAt == 0 {
listenedAt = time.Now().Unix()
}
// When receiving metadata in a unified field, particularly during online
// radio playback, we attempt to parse and interpret it based on our
// discoveries. As there isn't a set standard to ascertain the sequence,
// the order we establish is essentially an inference from the data
// received from these online sources. If inconsistencies arise with the
// established orders, it might be necessary to allow proper customization
// in the configuration file.
if artistName == "" && strings.Contains(trackName, " - ") {
elems := strings.Split(trackName, " - ")
n := len(elems)
switch n {
case 2:
artistName = elems[0]
trackName = elems[1]
case 4:
fallthrough
case 3:
trackName = elems[0]
artistName = elems[1]
releaseName = elems[2]
}
}
l.Payload = append(l.Payload, Listen{
ListenedAt: listenedAt,
Track: Track{
ArtistName: artistName,
TrackName: trackName,
ReleaseName: releaseName,
Info: Info{
SubmissionClient: "mpd-brainz",
SubmissionClientVersion: Version,
MusicService: musicService,
OriginUrl: originUrl,
},
},
})
}
func (l *Listens) Submit(listenType string, token string) error {
jsonData, err := json.MarshalIndent(l, "", " ")
if err != nil {
return err
}
l.ListenType = listenType
if l.ListenType == "playing_now" {
l.Payload[0].ListenedAt = 0
} else if l.ListenType == "import" {
Log("importing %d listens", l.Length())
} else {
Log("submitting listen: %s", l)
}
req, err := http.NewRequest("POST", ListenBrainzURL, bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Authorization", "Token "+token)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
Debug("bad request with data: %s", jsonData)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("error submitting request. status: %s", resp.Status)
}
return nil
}
func getCurrentListen(conn *mpd.Client) (Listens, error) {
currentSong, err := conn.CurrentSong()
if err != nil {
return Listens{}, err
}
artistName := currentSong["Artist"]
trackName := currentSong["Title"]
releaseName := currentSong["Album"]
originUrl := currentSong["file"]
musicService := currentSong["Name"]
return NewListen("single", artistName, trackName, releaseName,
originUrl, musicService, 0), nil
}
var lastListen Listens
func scrobble(conf Config) {
conn, err := mpd.DialAuthenticated("tcp", conf.mpdAddress, conf.mpdPassword)
if err != nil {
Fatal("%s", err)
}
defer conn.Close()
Log("connected to MPD: %s", conf.mpdAddress)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
ticker := time.NewTicker(conf.interval)
defer ticker.Stop()
Debug("scrobbling interval: %s", conf.interval)
for {
select {
case <-ticker.C:
currentListen, err := getCurrentListen(conn)
if err != nil {
Error("error obtaining current song from MPD:", err)
continue
}
if !currentListen.Equal(lastListen) && !currentListen.IsNil() {
err = currentListen.Submit("single", conf.token)
if err != nil {
Error("submitting scrobble to ListenBrainz: %s", err)
continue
}
err = currentListen.Submit("playing_now", conf.token)
if err != nil {
Error("submitting \"playing now\" to ListenBrainz: %s", err)
continue
}
lastListen = currentListen
} else {
}
case <-stop:
return
}
}
}
func skipLine(file *os.File) {
info, err := file.Stat()
if err != nil {
Fatal("reading file stats: %s: %s", file.Name, err)
}
var n int = int(info.Size())
var b []byte = []byte{' '}
for i := 0; i < n; i++ {
_, err = file.Read(b)
if b[0] == '\n' {
break
}
}
}
func dateToUnix(date string) int64 {
t, err := time.Parse("2006-01-02", date)
if err != nil {
Error("parsing date: %s: %s", date, err)
return 0
}
return t.Unix()
}
func shazamBuffListens(reader *csv.Reader, listen *Listens) bool {
for i := 0; i < ListensMaxSize; i++ {
e, err := reader.Read()
if err != nil {
if err.Error() == "EOF" {
return true
}
Error("%s", err)
i -= 1
continue
}
listen.Add(e[3], e[2], "", e[4], "shazam.com", dateToUnix(e[1]))
}
return false
}
func shazam(conf Config) {
file, err := os.Open(importShazam)
if err != nil {
Fatal("opening file: %s", err)
}
defer file.Close()
skipLine(file)
skipLine(file)
reader := csv.NewReader(file)
for {
listens := NewListens("import")
finished := shazamBuffListens(reader, &listens)
err = listens.Submit("import", conf.token)
if err != nil {
Fatal("submitting \"import\" to ListenBrainz: %s", err)
}
if finished {
break
}
}
}
func setLog(rootDir string, logConf string) {
if logPath == "" {
if logConf == "" {
logPath = filepath.Join(rootDir, DefaultLogFile)
} else {
logPath = logConf
}
}
var logFile *os.File
var err error
if logPath == "-" {
logFile = os.Stdout
} else {
logFile, err = os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
Error("opening log file: %s", err)
logFile = os.Stdout
}
}
Debug("writing logs to file: %s", logFile.Name())
Logger = log.New(logFile, "", log.LstdFlags)
if Logger == nil {
Fatal("failed creating logger: %s", logPath)
}
}
type Config struct {
mpdAddress string
mpdPassword string
interval time.Duration
token string
}
func findConfig() (string, string) {
configRoot := ""
configFile := ConfigFile
if configPath == "" {
configRoot = filepath.Join(os.Getenv("XDG_CONFIG_HOME"), ConfigDir)
if configRoot == ConfigDir {
configRoot = filepath.Join(os.Getenv("HOME"), ".config", ConfigDir)
}
err := os.Chdir(configRoot)
if err == os.ErrNotExist {
err = os.Mkdir(configRoot, 0700)
}
if err != nil {
Error("can't access config directory: %s", configRoot)
configRoot = ""
}
} else {
configAbs, err := filepath.Abs(configPath)
if err != nil {
Error("invalid file path: %s", configPath)
} else {
configPath = configAbs
}
configRoot = filepath.Dir(configPath)
configFile = filepath.Base(configPath)
}
return configRoot, configFile
}
func config() Config {
configRoot, configFile := findConfig()
viper.AddConfigPath(configRoot)
viper.SetConfigName(configFile)
viper.SetConfigType("yaml")
viper.SetDefault("mpd_address", "localhost:6600")
viper.SetDefault("mpd_password", "")
viper.SetDefault("polling_interval_seconds", 10)
viper.SetDefault("listenbrainz_token", "")
viper.SetDefault("log_file", "")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
Fatal("invalid configuration file: %s: %s", viper.ConfigFileUsed(), err)
} else {
Error("opening configuration file: %s: %s", viper.ConfigFileUsed(), err)
}
}
Debug("loading configuration: %s", viper.ConfigFileUsed())
var conf Config
conf.mpdAddress = viper.GetString("mpd_address")
conf.mpdPassword = viper.GetString("mpd_password")
conf.interval = viper.GetDuration("polling_interval_seconds") * time.Second
conf.token = viper.GetString("listenbrainz_token")
if conf.token == "" {
conf.token = os.Getenv("LISTENBRAINZ_TOKEN")
}
if conf.token == "" {
Fatal(fmt.Sprintln("ListenBrainz token not found.",
"Either define LISTENBRAINZ_TOKEN or set listenbrainz_token in",
viper.ConfigFileUsed()+"."))
}
setLog(configRoot, viper.GetString("log_file"))
return conf
}
var (
verbose bool
printVersion bool
importShazam string
configPath string
logPath string
)
func optarg() {
flag.BoolVar(&verbose, "v", false, "Enable debug logs.")
flag.BoolVar(&printVersion, "V", false, "Print version number.")
flag.StringVar(&importShazam, "i", "", "Import Shazam Library.")
flag.StringVar(&logPath, "l", "", "Set log file.")
flag.StringVar(&configPath, "c", "", "Config file.")
flag.Parse()
}
func main() {
optarg()
if printVersion {
version()
}
conf := config()
if importShazam != "" {
shazam(conf)
} else {
scrobble(conf)
}
}