aboutsummaryrefslogtreecommitdiff
path: root/spotify.go
blob: e0fcf6517417bf39d4ab51011577671be618e144 (plain)
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
package main

// The spotify backend is based on the librespot-golang code released under MIT
// license.
// Authors of the librespot-golang code are:
// Copyright (c) 2015 Paul Lietar
// Copyright (c) 2015 badfortrains
// Copyright (c) 2018 Guillaume "xplodwild" Lesniak

import (
	"errors"
	"os"
	"strings"

	"github.com/librespot-org/librespot-golang/Spotify"
	"github.com/librespot-org/librespot-golang/librespot"
	"github.com/librespot-org/librespot-golang/librespot/core"
	"github.com/librespot-org/librespot-golang/librespot/utils"

	"muhq.space/go/wrms/llog"
)

const (
	deviceName = "wrms"
)

type SpotifyConfig struct {
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}

type SpotifyBackend struct {
	session *core.Session
}

func NewSpotify(config *SpotifyConfig) (*SpotifyBackend, error) {
	spotify := SpotifyBackend{}
	if config == nil {
		config = &SpotifyConfig{}
	}

	usernameEnv := os.Getenv("WRMS_SPOTIFY_USER")
	if usernameEnv != "" {
		config.Username = usernameEnv
	}

	passwordEnv := os.Getenv("WRMS_SPOTIFY_PASSWORD")
	if passwordEnv != "" {
		config.Password = passwordEnv
	}

	if config.Username == "" || config.Password == "" {
		return nil, errors.New("User and password for spotify must be provided")
	}

	var err error
	spotify.session, err = librespot.Login(config.Username, config.Password, deviceName)
	if err != nil {
		return nil, err
	}

	return &spotify, nil
}

func (_ *SpotifyBackend) OnSongFinished(*Song) {}

func (spotify *SpotifyBackend) Play(song *Song, player *Player) {
	trackID := song.Uri
	session := spotify.session
	llog.Debug("Loading track for play: %v", trackID)

	// Get the track metadata: it holds information about which files and encodings are available
	track, err := session.Mercury().GetTrack(utils.Base62ToHex(trackID))
	if err != nil {
		llog.Error("Error loading track: %s", err)
		return
	}

	// For now, select the OGG 160kbps variant of the track. The "high quality"
	// setting in the official Spotify app is the OGG 320kbps variant.
	var selectedFile *Spotify.AudioFile
	llog.DDebug("Available Formats:")
	for _, file := range track.GetFile() {
		llog.DDebug("- %v", file.GetFormat())
		if file.GetFormat() == Spotify.AudioFile_OGG_VORBIS_160 {
			selectedFile = file
		}
	}

	// Synchronously load the track
	audioFile, err := session.Player().LoadTrack(selectedFile, track.GetGid())
	if err != nil {
		llog.Fatal("Error while loading track: %s\n", err)
	}

	player.PlayData(audioFile)
}

func (spotify *SpotifyBackend) Search(keyword string) []Song {
	session := spotify.session
	resp, err := session.Mercury().Search(keyword, 12, session.Country(), session.Username())

	if err != nil {
		llog.Error("Failed to search: %s", err)
		return []Song{}
	}

	res := resp.Results

	llog.DDebug("Search results for %s", keyword)
	llog.DDebug("=============================")

	if res.Error != nil {
		llog.Error("Search result error: %s", res.Error)
	}

	llog.Debug("\nTracks: %d (total %d)\n", len(res.Tracks.Hits), res.Tracks.Total)

	results := []Song{}
	for _, track := range res.Tracks.Hits {
		uriParts := strings.Split(track.Uri, ":")
		results = append(results, NewSong(track.Name, track.Artists[0].Name,
			"spotify", uriParts[len(uriParts)-1]))
	}

	return results
}