/
connector.go
174 lines (144 loc) · 4.13 KB
/
connector.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
package spotify
// Methods that are using spotify API. They are using rate limited client.
import (
"birnenlabs.com/go/lib/oauth"
"birnenlabs.com/go/lib/ratelimit"
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/golang/glog"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
type connector struct {
// Client with 1 qps limit
httpClient ratelimit.AnyClient
// market to search songs (e.g. "pl")
market string
}
func newConnector(ctx context.Context, market string) (*connector, error) {
// First create OAuth.
oauthClient, err := oauth.Create("spotify")
if err != nil {
return nil, err
}
// Verify the token
err = oauthClient.VerifyToken(ctx)
if err != nil {
return nil, err
}
// Get http client with Bearer
httpClient, err := oauthClient.CreateAuthenticatedHttpClient(ctx)
if err != nil {
return nil, err
}
return &connector{
httpClient: ratelimit.New(httpClient, time.Second),
market: market,
}, nil
}
func (s *connector) addToPlaylist(ctx context.Context, playlistId string, trackId string) error {
url := fmt.Sprintf(
"https://api.spotify.com/v1/playlists/%s/tracks?uris=spotify:track:%s",
playlistId, trackId)
glog.V(1).Infof("Add to playlist url: %q.", url)
resp, err := s.httpClient.Post(url, "text/plain", bytes.NewReader(nil))
if err != nil {
return err
}
defer resp.Body.Close()
// 201 == created
if resp.StatusCode != 201 {
return fmt.Errorf("response code: %v", resp.StatusCode)
}
return nil
}
func (s *connector) removeFromPlaylist(ctx context.Context, playlistId string, trackId string) error {
url := fmt.Sprintf(
"https://api.spotify.com/v1/playlists/%s/tracks?uris=spotify:track:%s",
playlistId, trackId)
body := fmt.Sprintf("{\"tracks\":[{\"uri\":\"spotify:track:%v\"}]}", trackId)
glog.V(1).Infof("Remove from playlist url: %q.", url)
r, err := http.NewRequest(http.MethodDelete, url, strings.NewReader(body))
resp, err := s.httpClient.Do(r)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("response code: %v", resp.StatusCode)
}
return nil
}
func (s *connector) listLiked(ctx context.Context) ([]SpotifyTrack, error) {
return s.listPlaylistUrl(ctx, "https://api.spotify.com/v1/me/tracks")
}
func (s *connector) listPlaylist(ctx context.Context, playlistId string) ([]SpotifyTrack, error) {
return s.listPlaylistUrl(ctx, fmt.Sprintf(
"https://api.spotify.com/v1/playlists/%s/tracks",
playlistId))
}
func (s *connector) listPlaylistUrl(ctx context.Context, nextUrl string) ([]SpotifyTrack, error) {
result := make([]SpotifyTrack, 0)
for nextUrl != "" {
glog.V(2).Infof("List playlist url: %q.", nextUrl)
resp, err := s.httpClient.Get(nextUrl)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("response code: %v", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r = new(PlaylistResponse)
err = json.Unmarshal(body, &r)
if err != nil {
return nil, err
}
nextUrl = r.Next
for _, playlistItem := range r.Items {
result = append(result, playlistItem.Track)
}
}
glog.V(2).Infof("ListPlaylist: %v", result)
return result, nil
}
func (s *connector) findTracks(ctx context.Context, query string) ([]SpotifyTrack, error) {
url := fmt.Sprintf(
"https://api.spotify.com/v1/search?type=track&market=%s&limit=50&q=%s",
s.market, url.QueryEscape(updateQueryString(query)))
glog.V(1).Infof("Find tracks url: %q.", url)
resp, err := s.httpClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("response code: %v", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r = new(SearchResponse)
err = json.Unmarshal(body, &r)
if err != nil {
return nil, err
}
glog.V(1).Infof("Found %v tracks for query %q.", len(r.Tracks.Items), query)
return r.Tracks.Items, nil
}
func updateQueryString(query string) string {
for _, token := range []string{"&", "feat.", "feat", "vs.", "vs"} {
query = strings.Replace(query, token, "", -1)
}
return query
}