-
Notifications
You must be signed in to change notification settings - Fork 597
/
lastfm.go
230 lines (192 loc) · 5.68 KB
/
lastfm.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
// Package lastfm implements the OAuth protocol for authenticating users through LastFM.
// This package can be used as a reference impleentation of an OAuth provider for Goth.
package lastfm
import (
"crypto/md5"
"encoding/hex"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"sort"
"github.com/markbates/goth"
"golang.org/x/oauth2"
)
var (
authURL = "http://www.lastfm.com/api/auth"
endpointProfile = "http://ws.audioscrobbler.com/2.0/"
)
// New creates a new LastFM provider, and sets up important connection details.
// You should always call `lastfm.New` to get a new Provider. Never try to craete
// one manullay.
func New(clientKey string, secret string, callbackURL string) *Provider {
p := &Provider{
ClientKey: clientKey,
Secret: secret,
CallbackURL: callbackURL,
providerName: "lastfm",
}
return p
}
// Provider is the implementation of `goth.Provider` for accessing LastFM
type Provider struct {
ClientKey string
Secret string
CallbackURL string
UserAgent string
HTTPClient *http.Client
providerName string
}
// Name is the name used to retrieve this provider later.
func (p *Provider) Name() string {
return p.providerName
}
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
func (p *Provider) SetName(name string) {
p.providerName = name
}
func (p *Provider) Client() *http.Client {
return goth.HTTPClientWithFallBack(p.HTTPClient)
}
// Debug is a no-op for the lastfm package.
func (p *Provider) Debug(debug bool) {}
// BeginAuth asks LastFm for an authentication end-point
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
urlParams := url.Values{}
urlParams.Add("api_key", p.ClientKey)
urlParams.Add("cb", p.CallbackURL)
session := &Session{
AuthURL: authURL + "?" + urlParams.Encode(),
}
return session, nil
}
// FetchUser will go to LastFM and access basic information about the user.
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
sess := session.(*Session)
user := goth.User{
AccessToken: sess.AccessToken,
Provider: p.Name(),
}
if user.AccessToken == "" {
// data is not yet retrieved since accessToken is still empty
return user, fmt.Errorf("%s has no user information available (yet)", p.providerName)
}
u := struct {
XMLName xml.Name `xml:"user"`
ID string `xml:"id"`
Name string `xml:"name"`
RealName string `xml:"realname"`
URL string `xml:"url"`
Country string `xml:"country"`
Age string `xml:"age"`
Gender string `xml:"gender"`
Subscriber string `xml:"subscriber"`
PlayCount string `xml:"playcount"`
Playlists string `xml:"playlists"`
Bootstrap string `xml:"bootstrap"`
Registered struct {
Unixtime string `xml:"unixtime,attr"`
Time string `xml:",chardata"`
} `xml:"registered"`
Images []struct {
Size string `xml:"size,attr"`
URL string `xml:",chardata"`
} `xml:"image"`
}{}
login := session.(*Session).Login
err := p.request(false, map[string]string{"method": "user.getinfo", "user": login}, &u)
if err == nil {
user.Name = u.RealName
user.NickName = u.Name
user.AvatarURL = u.Images[3].URL
user.UserID = u.ID
user.Location = u.Country
}
return user, err
}
// GetSession token from LastFM
func (p *Provider) GetSession(token string) (map[string]string, error) {
sess := struct {
Name string `xml:"name"`
Key string `xml:"key"`
Subscriber bool `xml:"subscriber"`
}{}
err := p.request(true, map[string]string{"method": "auth.getSession", "token": token}, &sess)
return map[string]string{"login": sess.Name, "token": sess.Key}, err
}
func (p *Provider) request(sign bool, params map[string]string, result interface{}) error {
urlParams := url.Values{}
urlParams.Add("method", params["method"])
params["api_key"] = p.ClientKey
for k, v := range params {
urlParams.Add(k, v)
}
if sign {
urlParams.Add("api_sig", signRequest(p.Secret, params))
}
uri := endpointProfile + "?" + urlParams.Encode()
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", p.UserAgent)
res, err := p.Client().Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode/100 == 5 { // only 5xx class errros
err = errors.New(fmt.Errorf("Request error(%v) %v", res.StatusCode, res.Status).Error())
return err
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
base := struct {
XMLName xml.Name `xml:"lfm"`
Status string `xml:"status,attr"`
Inner []byte `xml:",innerxml"`
}{}
err = xml.Unmarshal(body, &base)
if err != nil {
return err
}
if base.Status != "ok" {
errorDetail := struct {
Code int `xml:"code,attr"`
Message string `xml:",chardata"`
}{}
err = xml.Unmarshal(base.Inner, &errorDetail)
if err != nil {
return err
}
return errors.New(fmt.Errorf("Request Error(%v): %v", errorDetail.Code, errorDetail.Message).Error())
}
return xml.Unmarshal(base.Inner, result)
}
func signRequest(secret string, params map[string]string) string {
var keys []string
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var sigPlain string
for _, k := range keys {
sigPlain += k + params[k]
}
sigPlain += secret
hasher := md5.New()
hasher.Write([]byte(sigPlain))
return hex.EncodeToString(hasher.Sum(nil))
}
//RefreshToken refresh token is not provided by lastfm
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
return nil, errors.New("Refresh token is not provided by lastfm")
}
//RefreshTokenAvailable refresh token is not provided by lastfm
func (p *Provider) RefreshTokenAvailable() bool {
return false
}