-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
419 lines (329 loc) · 8.51 KB
/
core.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
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
package GoGrooveShark
// Some of the responses can be condensed down to use embedded structs when
// https://codereview.appspot.com/6460044 - is released in stable go1.1
import (
"bytes"
"crypto/hmac"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
const (
API_HOST = "api.grooveshark.com/ws3.php"
)
type apiRequestPayload struct {
Method string `json:"method"`
Parameters map[string]interface{} `json:"parameters"`
Header map[string]interface{} `json:"header"`
}
type apiError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type ApiErrorResponse struct {
Errors []apiError `json:"errors"`
}
func (err *ApiErrorResponse) Error() string {
strRet := ""
// Return all of the errors
for _, element := range err.Errors {
strRet += element.Message + "\n"
}
return strRet
}
type apiResponse struct {
HttpCode int
Body string
}
func (resp *apiResponse) getError() error {
errResp := &ApiErrorResponse{}
// If we could unmarshal into the error type, we know the result was an error.
// GrooveShark claim that this is a RESTFul api, but the http response code is always 200(ok)
// which makes working out if the response is ok a little harder
err := json.Unmarshal([]byte(resp.Body), errResp)
foundError := false
for _, element := range errResp.Errors {
if element.Code != 0 {
foundError = true
break
}
}
if err == nil && foundError {
return errResp
}
return nil
}
func (apiResp *apiResponse) unmarshal(resp interface{}) {
r := responseUnmarshaller{}
r.Result.resp = resp
json.Unmarshal([]byte(apiResp.Body), &r)
}
type SongInfo struct {
SongID int
SongName string
ArtistID int
ArtistName string
AlbumID int
AlbumName string
CoverArtFileName string
Popularity string
IsLowBitrateAvailable bool
IsVerified bool
Flags int
}
type Playlist struct {
PlaylistName string
TSModified int
UserID int
PlaylistDescription string
CoverArtFilename string
Songs []SongInfo
}
type EmptyResponse struct {
Success bool `json:"success"`
}
type responseUnmarshaller struct {
Header map[string]string `json:"header"`
Result resultUnmarshaller `json:"result"`
}
type resultUnmarshaller struct {
resp interface{}
}
func (r *resultUnmarshaller) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, r.resp)
}
type GrooveShark struct {
secretKey, publicKey string
sessionId string
}
func NewGrooveShark(key, secret string) *GrooveShark {
return &GrooveShark{
secretKey: secret,
publicKey: key,
}
}
func (gs *GrooveShark) GetPlaylist(playlistID string, limit *int) (*Playlist, error) {
args := make(map[string]interface{})
args["playlistID"] = playlistID
if limit != nil {
args["limit"] = limit
}
resp, err := gs.apiCall("getPlaylist", args)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
playlist := new(Playlist)
resp.unmarshal(playlist)
return playlist, nil
}
type SessionResponse struct {
Success bool `json:"success"`
SessionId string `json:"sessionID"`
}
func (gs *GrooveShark) StartSession() (*string, error) {
resp, err := gs.apiCallSecure("startSession", nil)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
session := SessionResponse{}
resp.unmarshal(&session)
if !session.Success {
return nil, errors.New("Error starting session")
}
// Set the property
gs.sessionId = session.SessionId
return &gs.sessionId, nil
}
type User struct {
UserID int
Email string
FName string
LName string
IsPlus bool
IsAnywhere bool
IsPremium bool
Success bool `json:"success"`
}
func (gs *GrooveShark) Authenticate(login, password string) (*User, error) {
md5Hasher := md5.New()
md5Hasher.Write([]byte(password))
passwordHash := fmt.Sprintf("%x", md5Hasher.Sum(nil))
// Start a session if we haven't got one currently
if len(gs.sessionId) == 0 {
_, err := gs.StartSession()
if err != nil {
return nil, err
}
}
args := make(map[string]interface{})
args["login"] = login
args["password"] = passwordHash
resp, err := gs.apiCallSecure("authenticate", args)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
user := new(User)
resp.unmarshal(user)
if !user.Success {
return nil, errors.New("Error authenticating user")
}
return user, nil
}
func (gs *GrooveShark) Logout() error {
resp, err := gs.apiCallSecure("logout", nil)
if err != nil {
return err
}
err = resp.getError()
if err != nil {
return err
}
return nil
}
func (gs *GrooveShark) PingService() (*string, error) {
resp, err := gs.apiCallSecure("pingService", nil)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
helloWorld := new(string)
resp.unmarshal(helloWorld)
return helloWorld, nil
}
func (gs *GrooveShark) AddUserFavoriteSong(songId int) error {
args := make(map[string]interface{})
args["songID"] = songId
resp, err := gs.apiCall("addUserFavoriteSong", args)
if err != nil {
return err
}
err = resp.getError()
if err != nil {
return err
}
respData := EmptyResponse{}
resp.unmarshal(&respData)
if !respData.Success {
return errors.New("Error adding favorite song")
}
return nil
}
type PlaylistResponse struct {
Success bool `json:"success"`
PlaylistsTSModified int `json:"playlistsTSModified"`
PlaylistID int `json:"playlistID"`
}
func (gs *GrooveShark) CreatePlaylist(playlistName string, songIds []int) (*PlaylistResponse, error) {
args := make(map[string]interface{})
args["name"] = playlistName
args["songIDs"] = songIds
resp, err := gs.apiCall("createPlaylist", args)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
respData := new(PlaylistResponse)
resp.unmarshal(respData)
if !respData.Success {
return nil, errors.New("Error creating playlist")
}
return respData, nil
}
type DeletePlaylistResponse struct {
Success bool `json:"success"`
PlaylistsTSModified int `json:"playlistsTSModified"`
}
func (gs *GrooveShark) DeletePlaylist(playlistId int) (*DeletePlaylistResponse, error) {
args := make(map[string]interface{})
args["playlistID"] = playlistId
resp, err := gs.apiCall("deletePlaylist", args)
if err != nil {
return nil, err
}
err = resp.getError()
if err != nil {
return nil, err
}
respData := new(DeletePlaylistResponse)
resp.unmarshal(respData)
if !respData.Success {
return nil, errors.New("Error deleting playlist")
}
return respData, nil
}
func (gs *GrooveShark) apiCall(methodName string, args map[string]interface{}) (*apiResponse, error) {
return gs.apiCallEx(methodName, args, false)
}
func (gs *GrooveShark) apiCallSecure(methodName string, args map[string]interface{}) (*apiResponse, error) {
return gs.apiCallEx(methodName, args, true)
}
func (gs *GrooveShark) apiCallEx(methodName string, args map[string]interface{}, secure bool) (*apiResponse, error) {
// Setup the request payload that will be sent over the wire
req := apiRequestPayload{Method: methodName}
req.Parameters = args
req.Header = make(map[string]interface{})
req.Header["wsKey"] = gs.publicKey
if len(gs.sessionId) > 0 {
req.Header["sessionID"] = gs.sessionId
}
postData, err := json.Marshal(req)
if err != nil {
return nil, err
}
payload := fmt.Sprintf("%s", postData)
signature := createSignature(payload, gs.secretKey)
proto := "http"
if secure {
proto = "https"
}
// Build the URL
queryStr := "?sig=" + signature
url := proto + "://" + API_HOST + queryStr
bodyBuffer := new(bytes.Buffer)
bodyBuffer.Write([]byte(payload))
httpReq, err := http.NewRequest("POST", url, bodyBuffer)
if err != nil {
return nil, err
}
// Set the headers
httpReq.Header.Set("Content-Type", "text/plain; charset=UTF-8")
httpReq.Header.Set("User-Agent", "GoGrooveShark-Go")
// Send off the request
resp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
response := new(apiResponse)
response.Body = fmt.Sprintf("%s", body)
response.HttpCode = resp.StatusCode
return response, nil
}
// Creates a signature that is required by all API calls to GrooveShark
func createSignature(query string, privateKey string) string {
h := hmac.New(md5.New, []byte(privateKey))
h.Write([]byte(query))
return fmt.Sprintf("%x", h.Sum(nil))
}