This repository has been archived by the owner on Feb 11, 2024. It is now read-only.
/
lyrics.go
78 lines (61 loc) · 1.49 KB
/
lyrics.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
package spotify
import (
"fmt"
"io"
"strconv"
"github.com/valyala/fastjson"
)
type LyricsLines struct {
StartTime int
Words string
}
func (s *SpotifyClient) GetLyrics(trackID string) (lyrics []LyricsLines, err error) {
token, err := s.getToken()
if err != nil {
return nil, err
}
req, err := s.newRequest("GET", fmt.Sprintf("https://spclient.wg.spotify.com/color-lyrics/v2/track/%s?format=json&market=from_token", trackID), nil)
if err != nil {
return nil, err
}
req.Header.Set("authorization", "Bearer "+token.AccessToken)
req.Header.Set("App-platform", "WebPlayer")
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// TODO: dirty, i'll rewrite this later
body, err := fastjson.Parse(string(b))
if err != nil {
return nil, err
}
if string(body.Get("lyrics", "syncType").GetStringBytes()) != "LINE_SYNCED" {
return nil, nil
}
for _, v := range body.GetArray("lyrics", "lines") {
startTime, err := strconv.Atoi(string(v.GetStringBytes("startTimeMs")))
if err != nil {
return nil, err
}
lyrics = append(lyrics, LyricsLines{
StartTime: startTime,
Words: string(v.GetStringBytes("words")),
})
}
return lyrics, nil
}
func GetCurrentWords(lyrics []LyricsLines, currentMs int) string {
for i := len(lyrics) - 1; i >= 0; i-- {
line := lyrics[i]
if currentMs < line.StartTime {
continue
}
return line.Words
}
return ""
}