-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomusicbrainz.go
360 lines (279 loc) · 7.56 KB
/
gomusicbrainz.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
package gomusicbrainz
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/tidwall/gjson"
)
const (
apiBaseURL = "https://musicbrainz.org/ws/2/"
releaseGroupPath = "release-group/"
recordingPath = "recording/"
musicalWorkPath = "work/"
isrcPath = "isrc/"
iswcPath = "iswc/"
artistPath = "artist/"
limit = "10"
offset = "0"
aliases = "aliases"
)
var (
// AppName indicates the Application Name
AppName string
// AppVersion indicates the version of the app ex:1.2.3
AppVersion string
// ContactURLOrEmail should be set to either an email address or a website for MusicBraniz to reach out
ContactURLOrEmail string
userAgentString string
replacer = strings.NewReplacer("-", "", ".", "", " ", "")
)
// GetRecording returns the Recording object for a given MusicBrainzID
func GetRecording(mbid string) (*Recording, error) {
if mbid == "" {
return nil, errors.New("MBID is empty")
}
u := apiBaseURL + recordingPath + mbid
params := make(map[string]string)
params["inc"] = "isrcs artist-credits"
params = addJSONParam(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var recording Recording
gjson.Unmarshal(result, &recording)
return &recording, nil
}
// GetWork returns the Music Work object per the given MusicBrainzID
func GetWork(mbid string) (*Work, error) {
if mbid == "" {
return nil, errors.New("MBID is empty")
}
u := apiBaseURL + musicalWorkPath + mbid
params := make(map[string]string)
params["inc"] = aliases
params = addJSONParam(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var work Work
gjson.Unmarshal(result, &work)
return &work, nil
}
// GetRecordingsByISRC returns Recording entities for a given isrc
func GetRecordingsByISRC(isrc string) (*ISRC, error) {
if isrc == "" {
return nil, errors.New("ISRC is empty")
}
if !isISRC(isrc) {
return nil, errors.New("Not a valid ISRC")
}
u := apiBaseURL + isrcPath + isrc
params := make(map[string]string)
params["inc"] = "isrcs artist-credits"
params = addJSONParam(params)
params = addResultParams(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var i ISRC
gjson.Unmarshal(result, &i)
return &i, nil
}
// GetWorksByISWC returns Work entities for a given iswc
func GetWorksByISWC(iswc string) (*ISWC, error) {
if iswc == "" {
return nil, errors.New("ISWC is empty")
}
if !isISWC(iswc) {
return nil, errors.New("Not a valid ISWC")
}
u := apiBaseURL + iswcPath + iswc
params := make(map[string]string)
params["inc"] = aliases
params = addJSONParam(params)
params = addResultParams(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var i ISWC
gjson.Unmarshal(result, &i)
return &i, nil
}
// GetArtist returns the Artist entity for the given mbid
func GetArtist(mbid string) (*Artist, error) {
if mbid == "" {
return nil, errors.New("MBID is empty")
}
u := apiBaseURL + artistPath + mbid
params := make(map[string]string)
params["inc"] = aliases
params = addJSONParam(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var artist Artist
gjson.Unmarshal(result, &artist)
return &artist, nil
}
// SearchArtist returns the search results of the artists given
// the artistName and the optional entry of country
func SearchArtist(artistName string, country string) (*[]Artist, error) {
a := strings.TrimSpace(artistName)
if a == "" {
return nil, errors.New("artistName is empty")
}
u := apiBaseURL + artistPath
params := make(map[string]string)
params["query"] = fmt.Sprintf("artist:%s", a)
c := strings.TrimSpace(country)
if c != "" {
params["query"] += fmt.Sprintf(" AND country:%s", c)
}
params = addJSONParam(params)
params = addResultParams(params)
result, err := GET(u, params)
if err != nil {
return nil, err
}
var searchArtistResult SearchArtistResult
var artists *[]Artist
gjson.Unmarshal(result, &searchArtistResult)
if &searchArtistResult != nil {
artists = &searchArtistResult.Artists
}
return artists, nil
}
// SetMusicBrainzConfig sets the configuration requirements
// Set these values before making any request
func SetMusicBrainzConfig(appName string, appVersion string, contactURLOrEmail string) {
AppName = appName
AppVersion = appVersion
ContactURLOrEmail = contactURLOrEmail
}
// REQUEST makes a standard HTTP call
func REQUEST(method string, u string, body io.Reader) ([]byte, error) {
fmt.Println(u)
err := validateConfig()
if err != nil {
return nil, err
}
netTransport := &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
client := &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}
req, err := http.NewRequest(method, u, body)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", getUserAgentString())
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
fmt.Printf(`
STATUS: %s
RATE LIMIT: %s
RATE LIMIT REMAINING: %s
`, res.Status, res.Header.Get("X-Ratelimit-Limit"), res.Header.Get("X-Ratelimit-Remaining"))
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return data, nil
}
// GET makes an HTTP GET call to the specified uri
func GET(uri string, params map[string]string) ([]byte, error) {
pu, err := url.Parse(uri)
if err != nil {
return nil, err
}
var u string
if params != nil && len(params) > 0 {
u = buildURLString(pu, params)
} else {
u = pu.String()
}
return REQUEST(http.MethodGet, u, nil)
}
func retry(attempts int, sleep time.Duration, callback func(args ...interface{}) ([]byte, error)) ([]byte, error) {
var err error
for i := 0; i < attempts; i++ {
res, e := callback()
err = e
if err == nil {
return res, nil
}
if i > attempts {
break
}
time.Sleep(sleep)
fmt.Println("Retrying after error:", err)
}
return nil, fmt.Errorf("After %d attempts, last error: %s", attempts, err)
}
// isISRC checks for the input being a valid ISRC
func isISRC(input string) bool {
r1 := regexp.MustCompile("^[A-Z]{2}[A-Z0-9]{3}[0-9]{2}[0-9]{5}$")
//r2 := regexp.MustCompile("^[A-F]{2}[A-F0-9]{3}[0-9]{2}[0-9]{5}$")
input = replacer.Replace(input)
upperInput := strings.ToUpper(input)
return r1.MatchString(upperInput) //|| r2.MatchString(upperInput)
}
// isISWC checks for the input being a valid UUID
func isISWC(input string) bool {
r := regexp.MustCompile("^T[0-9]{3}[0-9]{3}[0-9]{3}[0-9]{1}$")
input = replacer.Replace(input)
upperInput := strings.ToUpper(input)
return r.MatchString(upperInput)
}
func validateConfig() error {
if AppName == "" || AppVersion == "" || ContactURLOrEmail == "" {
return errors.New("AppName, AppVersion or Contact parameters were not set! Make sure your app is calling SetMusicBrainzConfig() before making any requests")
}
return nil
}
func getUserAgentString() string {
if userAgentString == "" {
userAgentString = fmt.Sprintf("%s/%s (%s)", AppName, AppVersion, ContactURLOrEmail)
}
return userAgentString
}
func addJSONParam(params map[string]string) map[string]string {
params["fmt"] = "json"
return params
}
func addResultParams(params map[string]string) map[string]string {
params["limit"] = limit
params["offset"] = offset
return params
}
func encodeParams(u *url.URL, params map[string]string) string {
q := u.Query()
for k, v := range params {
q.Add(k, v)
}
return q.Encode()
}
func buildURLString(u *url.URL, params map[string]string) string {
u.RawQuery = encodeParams(u, params)
return u.String()
}