/
track.go
154 lines (130 loc) · 3.95 KB
/
track.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
package spotify
import (
"bytes"
"context"
"fmt"
"math"
"strings"
"time"
"github.com/camphor-/relaym-server/domain/entity"
"github.com/camphor-/relaym-server/domain/service"
"github.com/zmb3/spotify/v2"
)
// Search はSpotify APIを通して、与えられたクエリを用い音楽を検索します。
func (c *Client) Search(ctx context.Context, q string) ([]*entity.Track, error) {
const searchKey = "searchKey"
token, ok := service.GetTokenFromContext(ctx)
if !ok {
return nil, fmt.Errorf("token not found")
}
cached, ok := c.cache.Get(searchKey + q)
if result, typeOK := cached.(*spotify.SearchResult); ok && typeOK {
return c.toTracks(result.Tracks.Tracks), nil
}
cli := spotify.New(c.auth.Client(ctx, token), spotify.WithAcceptLanguage("ja,en;q=0.9"))
result, err := cli.Search(ctx, q, spotify.SearchTypeTrack)
if err != nil {
return nil, fmt.Errorf("search q=%s: %w", q, err)
}
c.cache.SetDefault(searchKey+q, result)
tracks := c.toTracks(result.Tracks.Tracks)
return tracks, nil
}
// GetTrackFromURI はSpotify APIを通して、与えられたTrack URIを用い音楽を取得します。
func (c *Client) GetTracksFromURI(ctx context.Context, trackURIs []string) ([]*entity.Track, error) {
const getTracksKey = "getTracksKey"
if len(trackURIs) == 0 {
return nil, nil
}
token, ok := service.GetTokenFromContext(ctx)
if !ok {
return nil, fmt.Errorf("token not found")
}
cli := spotify.New(c.auth.Client(ctx, token), spotify.WithAcceptLanguage("ja,en;q=0.9"))
ids := make([]spotify.ID, len(trackURIs))
for i, trackURI := range trackURIs {
id := strings.Replace(trackURI, "spotify:track:", "", 1)
ids[i] = spotify.ID(id)
}
tracks := make([]*entity.Track, len(trackURIs))
// GetTracksは一度につき50曲までしか取得できない
countForLoop := int(math.Ceil(float64(len(ids)) / 50.0))
for i := 0; i < countForLoop; i++ {
var idsForAPI []spotify.ID
if i == (countForLoop - 1) {
idsForAPI = ids[i*50:]
} else {
idsForAPI = ids[i*50 : (i+1)*50]
}
var resultTracks []*spotify.FullTrack
key := c.idsToCacheKey(idsForAPI)
cached, ok := c.cache.Get(getTracksKey + key)
if v, typeOK := cached.([]*spotify.FullTrack); ok && typeOK {
resultTracks = v
} else {
var err error
resultTracks, err = cli.GetTracks(ctx, idsForAPI)
if err != nil {
return nil, fmt.Errorf("get track uris=%s: %w", trackURIs, err)
}
c.cache.SetDefault(getTracksKey+key, resultTracks)
}
for j, rt := range resultTracks {
idx := i*50 + j
tracks[idx] = c.toTrack(rt)
}
}
return tracks, nil
}
func (c *Client) idsToCacheKey(ids []spotify.ID) string {
buff := bytes.Buffer{}
for _, id := range ids {
buff.WriteString(string(id))
}
return buff.String()
}
func (c *Client) toTracks(resultTracks []spotify.FullTrack) []*entity.Track {
tracks := make([]*entity.Track, len(resultTracks))
for i, rt := range resultTracks {
rt := rt
tracks[i] = c.toTrack(&rt)
}
return tracks
}
func (c *Client) toTrack(fullTrack *spotify.FullTrack) *entity.Track {
if fullTrack == nil {
return nil
}
return &entity.Track{
URI: string(fullTrack.URI),
ID: fullTrack.ID.String(),
Name: fullTrack.Name,
Duration: time.Duration(fullTrack.Duration) * time.Millisecond,
Artists: c.toArtists(fullTrack.Artists),
URL: fullTrack.ExternalURLs["spotify"],
Album: &entity.Album{
Name: fullTrack.Album.Name,
Images: c.toImages(fullTrack.Album.Images),
},
}
}
func (c *Client) toArtists(resultArtists []spotify.SimpleArtist) []*entity.Artist {
artists := make([]*entity.Artist, len(resultArtists))
for i, a := range resultArtists {
artists[i] = &entity.Artist{
Name: a.Name,
}
}
return artists
}
func (c *Client) toImages(resultImages []spotify.Image) []*entity.AlbumImage {
images := make([]*entity.AlbumImage, len(resultImages))
for i, image := range resultImages {
images[i] = &entity.AlbumImage{
URL: image.URL,
Height: image.Height,
Width: image.Width,
}
}
return images
}