/
spotify_player.go
395 lines (346 loc) · 10.5 KB
/
spotify_player.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
package songplayer
import (
"encoding/json"
"errors"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/zmb3/spotify"
"golang.org/x/oauth2"
"io/ioutil"
"net/http"
"strings"
)
const (
DEFAULT_AUTHORISE_PORT = 5678
DEFAULT_AUTHORISE_URL = "http://musicbot:5678/authorise/"
MAX_SPOTIFY_PLAYLIST_ITEMS = 1000
)
var ErrNotAuthorised = errors.New("Client has not been authorised yet")
type SpotifyPlayer struct {
sessionKey string
tokenFilePath string
playbackDevice string
client *spotify.Client
user *spotify.PrivateUser
auth *spotify.Authenticator
logger *logrus.Entry
authListeners []func()
}
func NewSpotifyPlayer(spotifyClientID, spotifyClientSecret, tokenFilePath, authoriseRedirectURL string, authoriseHTTPPort int) (p *SpotifyPlayer, authURL string, err error) {
if authoriseRedirectURL == "" {
authoriseRedirectURL = DEFAULT_AUTHORISE_URL
}
if authoriseHTTPPort <= 0 {
authoriseHTTPPort = DEFAULT_AUTHORISE_PORT
}
auth := spotify.NewAuthenticator(authoriseRedirectURL, spotify.ScopeUserReadCurrentlyPlaying, spotify.ScopeUserReadPlaybackState, spotify.ScopeUserModifyPlaybackState, spotify.ScopePlaylistReadCollaborative, spotify.ScopePlaylistReadPrivate)
auth.SetAuthInfo(spotifyClientID, spotifyClientSecret)
p = &SpotifyPlayer{
sessionKey: RandStringBytes(12),
tokenFilePath: tokenFilePath,
auth: &auth,
logger: logrus.WithField("songplayer", "Spotify"),
}
authURL, err = p.init(authoriseHTTPPort)
return
}
func (p *SpotifyPlayer) init(authoriseHTTPPort int) (authURL string, err error) {
// Add our own after authorisation handler
p.AddAuthorisationListener(p.afterAuthorisation)
go func() {
err = http.ListenAndServe(fmt.Sprintf(":%d", authoriseHTTPPort), p)
if err != nil {
p.logger.Errorf("SpotifyPlayer.init: Could not start HTTP server on port %d: %v", authoriseHTTPPort, err)
return
}
}()
token, readErr := p.readToken()
if readErr == nil {
client := p.auth.NewClient(token)
client.AutoRetry = true
var userErr error
p.user, userErr = client.CurrentUser()
if userErr == nil {
p.logger.Info("SpotifyPlayer.init: Reusing previous spotify token")
p.client = &client
p.afterAuthorisation()
return
}
p.logger.Info("SpotifyPlayer.init: Previous token invalid, new authentication needed")
}
authURL = p.auth.AuthURL(p.sessionKey)
p.logger.Infof("SpotifyPlayer.init: Please authorise the MusicBot by visiting the following page in your browser: %s", authURL)
return
}
func (p *SpotifyPlayer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if p.client != nil {
w.WriteHeader(http.StatusPreconditionFailed)
fmt.Fprint(w, "<h1>Already authenticated!</h1>")
return
}
token, err := p.auth.Token(p.sessionKey, r)
if err != nil {
http.Error(w, "Could not get token", http.StatusForbidden)
p.logger.Warnf("SpotifyPlayer.ServeHTTP: Error pulling token from callback: %v", err)
return
}
if st := r.FormValue("state"); st != p.sessionKey {
p.logger.Warnf("SpotifyPlayer.ServeHTTP: State mismatch: %v != %v", st, p.sessionKey)
w.WriteHeader(http.StatusBadRequest)
return
}
// use the token to get an authenticated client
client := p.auth.NewClient(token)
client.AutoRetry = true
p.client = &client
p.user, err = p.client.CurrentUser()
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, "<h1>Login completed as %s</h1>", p.user.ID)
p.writeToken(token)
for _, l := range p.authListeners {
l()
}
}
func (p *SpotifyPlayer) AddAuthorisationListener(listener func()) {
p.authListeners = append(p.authListeners, listener)
}
func (p *SpotifyPlayer) afterAuthorisation() {
p.logger = p.logger.WithField("spotifyUser", p.user.ID)
p.logger.Info("SpotifyPlayer.afterAuthorisation: Successfully authorised")
// Turn repeat off, as it interferes with the musicplayer
repErr := p.client.Repeat("off")
if repErr != nil {
p.logger.Warnf("SpotifyPlayer.afterAuthorisation: Error setting repeat setting: %v", repErr)
}
// Turn shuffle off
shufErr := p.client.Shuffle(false)
p.client.Shuffle(false)
if shufErr != nil {
p.logger.Warnf("SpotifyPlayer.afterAuthorisation: Error setting shuffle setting: %v", shufErr)
}
}
func (p *SpotifyPlayer) writeToken(token *oauth2.Token) (err error) {
if p.tokenFilePath == "" {
err = errors.New("token filepath invalid")
return
}
buf, err := json.Marshal(token)
if err != nil {
p.logger.Warnf("SpotifyPlayer.writeToken: Error marshalling spotify token: %v", err)
return
}
err = ioutil.WriteFile(p.tokenFilePath, buf, 0755)
if err != nil {
p.logger.Warnf("SpotifyPlayer.writeToken: Error writing spotify token: %v", err)
return
}
return
}
func (p *SpotifyPlayer) readToken() (token *oauth2.Token, err error) {
if p.tokenFilePath == "" {
err = errors.New("token filepath invalid")
return
}
buf, err := ioutil.ReadFile(p.tokenFilePath)
if err != nil {
p.logger.Warnf("SpotifyPlayer.readToken: Error reading spotify token: %v", err)
return
}
token = &oauth2.Token{}
err = json.Unmarshal(buf, token)
if err != nil {
p.logger.Warnf("SpotifyPlayer.readToken: Error unmarshalling spotify token: %v", err)
return
}
return
}
func (p *SpotifyPlayer) Name() (name string) {
return "Spotify"
}
func (p *SpotifyPlayer) CanPlay(url string) (canPlay bool) {
_, id, _, err := GetSpotifyTypeAndIDFromURL(url)
canPlay = err == nil && id != ""
return
}
func (p *SpotifyPlayer) GetSongs(url string) (songs []Playable, err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
tp, id, userID, err := GetSpotifyTypeAndIDFromURL(url)
if err != nil {
p.logger.Errorf("SpotifyPlayer.GetSongs: Could not parse URL [%s] %v", url, err)
return
}
switch tp {
case TYPE_TRACK:
var track *spotify.FullTrack
track, err = p.client.GetTrack(spotify.ID(id))
if err != nil {
p.logger.Errorf("SpotifyPlayer.GetSongs: Could not get track data for URL [%s] %v", url, err)
return
}
songs = append(songs,
NewSong(GetSpotifyTrackName(&track.SimpleTrack), track.TimeDuration(), string(track.URI), GetSpotifyAlbumImage(&track.Album)),
)
case TYPE_ALBUM:
var album *spotify.FullAlbum
album, err = p.client.GetAlbum(spotify.ID(id))
if err != nil {
p.logger.Errorf("SpotifyPlayer.GetSongs: Could not get album data for URL [%s] %v", url, err)
return
}
for _, track := range album.Tracks.Tracks {
songs = append(songs,
NewSong(GetSpotifyTrackName(&track), track.TimeDuration(), string(track.URI), GetSpotifyAlbumImage(&album.SimpleAlbum)),
)
}
case TYPE_PLAYLIST:
offset := 0
limit := 50
for {
var listTracks *spotify.PlaylistTrackPage
listTracks, err = p.client.GetPlaylistTracksOpt(userID, spotify.ID(id), &spotify.Options{
Offset: &offset,
Limit: &limit,
}, "")
if err != nil {
p.logger.Errorf("SpotifyPlayer.GetSongs: Could not get playlist data for URL [%s] %v", url, err)
return
}
for _, track := range listTracks.Tracks {
if strings.HasPrefix(string(track.Track.URI), "spotify:local:") {
p.logger.Infof("SpotifyPlayer.GetSongs: Skipping local song %s", track.Track.URI)
continue
}
songs = append(songs,
NewSong(GetSpotifyTrackName(&track.Track.SimpleTrack), track.Track.TimeDuration(), string(track.Track.URI), GetSpotifyAlbumImage(&track.Track.Album)),
)
}
offset += limit
if offset >= listTracks.Total || offset > MAX_SPOTIFY_PLAYLIST_ITEMS {
break
}
}
}
return
}
func (p *SpotifyPlayer) Search(searchType SearchType, searchStr string, limit int) (results []PlayableSearchResult, err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
results, err = GetSpotifySearchResults(p.client, searchType, searchStr, limit)
if err != nil {
p.logger.Errorf("SpotifyPlayer.Search: Error searching [%d | %s | %d] %v", searchType, searchStr, limit)
return
}
return
}
func (p *SpotifyPlayer) SetPlaybackDevice(playbackDevice string) {
logrus.Infof("SpotifyPlayer.SetPlaybackDevice: Setting spotify playback device to [%s]", playbackDevice)
p.playbackDevice = playbackDevice
}
func (p *SpotifyPlayer) setPlaybackDevice() (err error) {
devices, err := p.client.PlayerDevices()
if err != nil {
p.logger.Errorf("SpotifyPlayer.setPlaybackDevice: Error getting devices. %v", err)
return
}
var newDev, oldDev *spotify.PlayerDevice
for i := range devices {
if devices[i].Active {
oldDev = &devices[i]
}
if strings.ToLower(devices[i].Name) == strings.ToLower(p.playbackDevice) {
newDev = &devices[i]
}
}
if newDev == nil {
err = errors.New("device not found")
return
}
if newDev.Active {
// Device is already active, nothing to do
return
}
if newDev.Restricted {
err = errors.New("device is restricted")
return
}
if oldDev != nil {
p.logger.Infof("SpotifyPlayer.setPlaybackDevice: Transferring playback from %s (%s) to %s (%s)", oldDev.Name, oldDev.Type, newDev.Name, newDev.Type)
} else {
p.logger.Infof("SpotifyPlayer.setPlaybackDevice: Transferring playback to %s (%s)", newDev.Name, newDev.Type)
}
err = p.client.TransferPlayback(newDev.ID, true)
if err != nil {
p.logger.Errorf("SpotifyPlayer.setPlaybackDevice: Error transferring playback to %s (%s). %v", newDev.Name, newDev.Type, err)
}
return
}
func (p *SpotifyPlayer) Play(url string) (err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
if p.playbackDevice != "" {
err = p.setPlaybackDevice()
if err != nil {
p.logger.Errorf("SpotifyPlayer.Play: Error setting playback device [%s | %s] %v", p.playbackDevice, url, err)
}
}
URI := spotify.URI(url)
err = p.client.PlayOpt(&spotify.PlayOptions{
URIs: []spotify.URI{URI},
})
if err != nil {
p.logger.Errorf("SpotifyPlayer.Play: Error playing [%s] %v", url, err)
return
}
return
}
func (p *SpotifyPlayer) Seek(positionSeconds int) (err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
err = p.client.Seek(positionSeconds * 1000)
if err != nil {
p.logger.Errorf("SpotifyPlayer.Seek: Error seeking [%d] %v", positionSeconds, err)
return
}
return
}
func (p *SpotifyPlayer) Pause(pauseState bool) (err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
if pauseState {
err = p.client.Pause()
if err != nil {
p.logger.Errorf("SpotifyPlayer.Pause: Error pausing: %v", err)
return
}
return
}
err = p.client.Play()
if err != nil {
p.logger.Errorf("SpotifyPlayer.Pause: Error unpausing: %v", err)
return
}
return
}
func (p *SpotifyPlayer) Stop() (err error) {
if p.client == nil {
err = ErrNotAuthorised
return
}
err = p.client.Pause()
if err != nil {
p.logger.Errorf("SpotifyPlayer.Stop: Error stopping: %v", err)
return
}
return
}