-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathapi_server.go
More file actions
718 lines (611 loc) · 18.9 KB
/
api_server.go
File metadata and controls
718 lines (611 loc) · 18.9 KB
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
librespot "github.com/devgianlu/go-librespot"
metadatapb "github.com/devgianlu/go-librespot/proto/spotify/metadata"
"github.com/rs/cors"
)
const timeout = 10 * time.Second
type ApiServer interface {
Emit(ev *ApiEvent)
Receive() <-chan ApiRequest
}
type ConcreteApiServer struct {
log librespot.Logger
allowOrigin string
certFile string
keyFile string
close bool
listener net.Listener
requests chan ApiRequest
clients []*websocket.Conn
clientsLock sync.RWMutex
}
var (
ErrNoSession = errors.New("no session")
ErrBadRequest = errors.New("bad request")
ErrForbidden = errors.New("forbidden")
ErrNotFound = errors.New("not found")
ErrMethodNotAllowed = errors.New("method not allowed")
ErrTooManyRequests = errors.New("the app has exceeded its rate limits")
)
type ApiRequestType string
const (
ApiRequestTypeWebApi ApiRequestType = "web_api"
ApiRequestTypeStatus ApiRequestType = "status"
ApiRequestTypeResume ApiRequestType = "resume"
ApiRequestTypePause ApiRequestType = "pause"
ApiRequestTypePlayPause ApiRequestType = "playpause"
ApiRequestTypeSeek ApiRequestType = "seek"
ApiRequestTypePrev ApiRequestType = "prev"
ApiRequestTypeNext ApiRequestType = "next"
ApiRequestTypePlay ApiRequestType = "play"
ApiRequestTypeGetVolume ApiRequestType = "get_volume"
ApiRequestTypeSetVolume ApiRequestType = "set_volume"
ApiRequestTypeSetRepeatingContext ApiRequestType = "repeating_context"
ApiRequestTypeSetRepeatingTrack ApiRequestType = "repeating_track"
ApiRequestTypeSetShufflingContext ApiRequestType = "shuffling_context"
ApiRequestTypeAddToQueue ApiRequestType = "add_to_queue"
ApiRequestTypeToken ApiRequestType = "token"
)
type ApiEventType string
const (
ApiEventTypePlaying ApiEventType = "playing"
ApiEventTypeNotPlaying ApiEventType = "not_playing"
ApiEventTypeWillPlay ApiEventType = "will_play"
ApiEventTypePaused ApiEventType = "paused"
ApiEventTypeActive ApiEventType = "active"
ApiEventTypeInactive ApiEventType = "inactive"
ApiEventTypeMetadata ApiEventType = "metadata"
ApiEventTypeVolume ApiEventType = "volume"
ApiEventTypeSeek ApiEventType = "seek"
ApiEventTypeStopped ApiEventType = "stopped"
ApiEventTypeRepeatTrack ApiEventType = "repeat_track"
ApiEventTypeRepeatContext ApiEventType = "repeat_context"
ApiEventTypeShuffleContext ApiEventType = "shuffle_context"
)
type ApiRequest struct {
Type ApiRequestType
Data any
resp chan apiResponse
}
func (r *ApiRequest) Reply(data any, err error) {
r.resp <- apiResponse{data, err}
}
type ApiRequestDataSeek struct {
Position int64 `json:"position"`
Relative bool `json:"relative"`
}
type ApiRequestDataVolume struct {
Volume int32 `json:"volume"`
Relative bool `json:"relative"`
}
type ApiRequestDataWebApi struct {
Method string
Path string
Query url.Values
}
type ApiRequestDataPlay struct {
Uri string `json:"uri"`
SkipToUri string `json:"skip_to_uri"`
Paused bool `json:"paused"`
}
type ApiRequestDataNext struct {
Uri *string `json:"uri"`
}
type apiResponse struct {
data any
err error
}
type ApiResponseStatusTrack struct {
Uri string `json:"uri"`
Name string `json:"name"`
ArtistNames []string `json:"artist_names"`
AlbumName string `json:"album_name"`
AlbumCoverUrl *string `json:"album_cover_url"`
Position int64 `json:"position"`
Duration int `json:"duration"`
ReleaseDate string `json:"release_date"`
TrackNumber int `json:"track_number"`
DiscNumber int `json:"disc_number"`
}
func getBestImageIdForSize(images []*metadatapb.Image, size string) []byte {
if len(images) == 0 {
return nil
}
imageSize := metadatapb.Image_Size(metadatapb.Image_Size_value[strings.ToUpper(size)])
dist := func(a metadatapb.Image_Size) int {
diff := int(a) - int(imageSize)
if diff < 0 {
return -diff
}
return diff
}
// Find an image with the exact requested size.
// If no exact match, return the closest image to the requested size.
var bestImage *metadatapb.Image
for _, img := range images {
if img.Size == nil {
continue
}
if *img.Size == imageSize {
return img.FileId
}
// Find the image with the closest size. This logic works because the
// metadatapb.Image_Size enum values are ordered from smallest to largest.
if bestImage == nil || dist(*img.Size) < dist(*bestImage.Size) {
bestImage = img
}
}
if bestImage != nil {
return bestImage.FileId
}
// Fallback to the first image if none have size information.
return images[0].FileId
}
func (p *AppPlayer) newApiResponseStatusTrack(media *librespot.Media, position int64) *ApiResponseStatusTrack {
if media.IsTrack() {
track := media.Track()
var artists []string
for _, a := range track.Artist {
artists = append(artists, *a.Name)
}
albumCoverId := getBestImageIdForSize(track.Album.Cover, p.app.cfg.Server.ImageSize)
if albumCoverId == nil && track.Album.CoverGroup != nil {
albumCoverId = getBestImageIdForSize(track.Album.CoverGroup.Image, p.app.cfg.Server.ImageSize)
}
var trackCoverUrl *string
if p.prodInfo != nil {
trackCoverUrl = p.prodInfo.ImageUrl(albumCoverId)
}
return &ApiResponseStatusTrack{
Uri: librespot.SpotifyIdFromGid(librespot.SpotifyIdTypeTrack, track.Gid).Uri(),
Name: *track.Name,
ArtistNames: artists,
AlbumName: *track.Album.Name,
AlbumCoverUrl: trackCoverUrl,
Position: position,
Duration: int(*track.Duration),
ReleaseDate: track.Album.Date.String(),
TrackNumber: int(*track.Number),
DiscNumber: int(*track.DiscNumber),
}
} else {
episode := media.Episode()
albumCoverId := getBestImageIdForSize(episode.CoverImage.Image, p.app.cfg.Server.ImageSize)
var episodeCoverUrl *string
if p.prodInfo != nil {
episodeCoverUrl = p.prodInfo.ImageUrl(albumCoverId)
}
return &ApiResponseStatusTrack{
Uri: librespot.SpotifyIdFromGid(librespot.SpotifyIdTypeEpisode, episode.Gid).Uri(),
Name: *episode.Name,
ArtistNames: []string{*episode.Show.Name},
AlbumName: *episode.Show.Name,
AlbumCoverUrl: episodeCoverUrl,
Position: position,
Duration: int(*episode.Duration),
ReleaseDate: "",
TrackNumber: 0,
DiscNumber: 0,
}
}
}
type ApiResponseStatus struct {
Username string `json:"username"`
DeviceId string `json:"device_id"`
DeviceType string `json:"device_type"`
DeviceName string `json:"device_name"`
PlayOrigin string `json:"play_origin"`
Stopped bool `json:"stopped"`
Paused bool `json:"paused"`
Buffering bool `json:"buffering"`
Volume uint32 `json:"volume"`
VolumeSteps uint32 `json:"volume_steps"`
RepeatContext bool `json:"repeat_context"`
RepeatTrack bool `json:"repeat_track"`
ShuffleContext bool `json:"shuffle_context"`
Track *ApiResponseStatusTrack `json:"track"`
}
type ApiResponseVolume struct {
Value uint32 `json:"value"`
Max uint32 `json:"max"`
}
type ApiResponseToken struct {
Token string `json:"token"`
}
type ApiEvent struct {
Type ApiEventType `json:"type"`
Data any `json:"data"`
}
type ApiEventDataMetadata ApiResponseStatusTrack
type ApiEventDataVolume ApiResponseVolume
type ApiEventDataPlaying struct {
ContextUri string `json:"context_uri"`
Uri string `json:"uri"`
Resume bool `json:"resume"`
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataWillPlay struct {
ContextUri string `json:"context_uri"`
Uri string `json:"uri"`
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataNotPlaying struct {
ContextUri string `json:"context_uri"`
Uri string `json:"uri"`
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataPaused struct {
ContextUri string `json:"context_uri"`
Uri string `json:"uri"`
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataStopped struct {
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataSeek struct {
ContextUri string `json:"context_uri"`
Uri string `json:"uri"`
Position int `json:"position"`
Duration int `json:"duration"`
PlayOrigin string `json:"play_origin"`
}
type ApiEventDataRepeatTrack struct {
Value bool `json:"value"`
}
type ApiEventDataRepeatContext struct {
Value bool `json:"value"`
}
type ApiEventDataShuffleContext struct {
Value bool `json:"value"`
}
func NewApiServer(log librespot.Logger, address string, port int, allowOrigin string, certFile string, keyFile string) (_ ApiServer, err error) {
s := &ConcreteApiServer{log: log, allowOrigin: allowOrigin, certFile: certFile, keyFile: keyFile}
s.requests = make(chan ApiRequest)
s.listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", address, port))
if err != nil {
return nil, fmt.Errorf("failed starting api listener: %w", err)
}
log.Infof("api server listening on %s", s.listener.Addr())
go s.serve()
return s, nil
}
type StubApiServer struct {
log librespot.Logger
}
func NewStubApiServer(log librespot.Logger) (ApiServer, error) {
return &StubApiServer{log: log}, nil
}
func (s *StubApiServer) Emit(ev *ApiEvent) {
s.log.Tracef("voiding websocket event: %s", ev.Type)
}
func (s *StubApiServer) Receive() <-chan ApiRequest {
return make(<-chan ApiRequest)
}
func (s *ConcreteApiServer) handleRequest(req ApiRequest, w http.ResponseWriter) {
req.resp = make(chan apiResponse, 1)
s.requests <- req
resp := <-req.resp
if resp.err != nil {
switch {
case errors.Is(resp.err, ErrNoSession):
w.WriteHeader(http.StatusNoContent)
return
case errors.Is(resp.err, ErrForbidden):
w.WriteHeader(http.StatusForbidden)
return
case errors.Is(resp.err, ErrNotFound):
w.WriteHeader(http.StatusNotFound)
return
case errors.Is(resp.err, ErrMethodNotAllowed):
w.WriteHeader(http.StatusMethodNotAllowed)
return
case errors.Is(resp.err, ErrTooManyRequests):
w.WriteHeader(http.StatusTooManyRequests)
return
case errors.Is(resp.err, ErrBadRequest):
w.WriteHeader(http.StatusBadRequest)
return
default:
s.log.WithError(resp.err).Errorf("failed handling request %s", req.Type)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
switch respData := resp.data.(type) {
case []byte:
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = w.Write(respData)
default:
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(respData)
}
}
func jsonDecode(r *http.Request, v any) error {
defer func() { _ = r.Body.Close() }()
data, err := io.ReadAll(r.Body)
if err != nil {
return err
} else if len(data) == 0 {
return nil
}
return json.Unmarshal(data, v)
}
func (s *ConcreteApiServer) serve() {
m := http.NewServeMux()
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("{}"))
})
m.Handle("/web-api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.handleRequest(ApiRequest{
Type: ApiRequestTypeWebApi,
Data: ApiRequestDataWebApi{
Method: r.Method,
Path: strings.TrimPrefix(r.URL.Path, "/web-api/"),
Query: r.URL.Query(),
},
}, w)
}))
m.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeStatus}, w)
})
m.HandleFunc("/player/play", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data ApiRequestDataPlay
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(data.Uri) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypePlay, Data: data}, w)
})
m.HandleFunc("/player/resume", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeResume}, w)
})
m.HandleFunc("/player/pause", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypePause}, w)
})
m.HandleFunc("/player/playpause", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypePlayPause}, w)
})
m.HandleFunc("/player/next", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data ApiRequestDataNext
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeNext, Data: data}, w)
})
m.HandleFunc("/player/prev", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypePrev}, w)
})
m.HandleFunc("/player/seek", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data ApiRequestDataSeek
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if !data.Relative && data.Position < 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeSeek, Data: data}, w)
})
m.HandleFunc("/player/volume", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
s.handleRequest(ApiRequest{Type: ApiRequestTypeGetVolume}, w)
} else if r.Method == "POST" {
var data ApiRequestDataVolume
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if !data.Relative && data.Volume < 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeSetVolume, Data: data}, w)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
m.HandleFunc("/player/repeat_context", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data struct {
Repeat bool `json:"repeat_context"`
}
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeSetRepeatingContext, Data: data.Repeat}, w)
})
m.HandleFunc("/player/repeat_track", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data struct {
Repeat bool `json:"repeat_track"`
}
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeSetRepeatingTrack, Data: data.Repeat}, w)
})
m.HandleFunc("/player/shuffle_context", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data struct {
Shuffle bool `json:"shuffle_context"`
}
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeSetShufflingContext, Data: data.Shuffle}, w)
})
m.HandleFunc("/player/add_to_queue", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var data struct {
Uri string `json:"uri"`
}
if err := jsonDecode(r, &data); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if len(data.Uri) == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeAddToQueue, Data: data.Uri}, w)
})
m.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
s.handleRequest(ApiRequest{Type: ApiRequestTypeToken}, w)
})
m.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
opts := &websocket.AcceptOptions{}
if len(s.allowOrigin) > 0 {
allow := s.allowOrigin
allow = strings.TrimPrefix(allow, "http://")
allow = strings.TrimPrefix(allow, "https://")
allow = strings.TrimSuffix(allow, "/")
opts.OriginPatterns = []string{allow}
}
c, err := websocket.Accept(w, r, opts)
if err != nil {
s.log.WithError(err).Error("failed accepting websocket connection")
w.WriteHeader(http.StatusInternalServerError)
return
}
// add the client to the list
s.clientsLock.Lock()
s.clients = append(s.clients, c)
s.clientsLock.Unlock()
s.log.Debugf("new websocket client")
for {
_, _, err := c.Read(context.Background())
if s.close {
return
} else if err != nil {
s.log.WithError(err).Error("websocket connection errored")
// remove the client from the list
s.clientsLock.Lock()
for i, cc := range s.clients {
if cc == c {
s.clients = append(s.clients[:i], s.clients[i+1:]...)
break
}
}
s.clientsLock.Unlock()
return
}
}
})
c := cors.New(cors.Options{
AllowedOrigins: []string{s.allowOrigin},
AllowPrivateNetwork: true,
AllowCredentials: true,
})
var err error
if len(s.certFile) > 0 && len(s.keyFile) > 0 {
err = http.ServeTLS(s.listener, c.Handler(m), s.certFile, s.keyFile)
} else {
err = http.Serve(s.listener, c.Handler(m))
}
if s.close {
return
} else if err != nil {
s.log.WithError(err).Error("failed serving api")
s.Close()
}
}
func (s *ConcreteApiServer) Emit(ev *ApiEvent) {
s.clientsLock.RLock()
defer s.clientsLock.RUnlock()
s.log.Tracef("emitting websocket event: %s", ev.Type)
for _, client := range s.clients {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
err := wsjson.Write(ctx, client, ev)
cancel()
if err != nil {
// purposely do not propagate this to the caller
s.log.WithError(err).Error("failed communicating with websocket client")
}
}
}
func (s *ConcreteApiServer) Receive() <-chan ApiRequest {
return s.requests
}
func (s *ConcreteApiServer) Close() {
s.close = true
// close all websocket clients
s.clientsLock.RLock()
for _, client := range s.clients {
_ = client.Close(websocket.StatusGoingAway, "")
}
s.clientsLock.RUnlock()
// close the listener
_ = s.listener.Close()
}