spotify.go 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package spotify
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "golang.org/x/oauth2"
  10. "golang.org/x/oauth2/clientcredentials"
  11. spotifyAuth "golang.org/x/oauth2/spotify"
  12. "io"
  13. "log"
  14. "net/http"
  15. "net/url"
  16. "reflect"
  17. "strings"
  18. )
  19. type SpotifyClient struct {
  20. clientID string
  21. clientSecret string
  22. bearerAuth string
  23. baseURL *url.URL
  24. httpClient *http.Client
  25. config *oauth2.Config
  26. context context.Context
  27. }
  28. type TrackInfo struct {
  29. Album AlbumInfo `json:"album"`
  30. Artists []ArtistInfo `json:"artists"`
  31. DiskNumber int `json:"disc_number"`
  32. DurationMS int `json:"duration_ms"`
  33. Explicit bool `json:"explicit"`
  34. ExternalIds ExternalIds `json:"external_ids"`
  35. ExternalUrls ExternalUrls `json:"external_urls"`
  36. Href string `json:"href"`
  37. ID string `json:"id"`
  38. IsPlayable bool `json:"is_playable"`
  39. Name string `json:"name"`
  40. Popularity int `json:"popularity"`
  41. PreviewUrl string `json:"preview_url"`
  42. TrackNumber int `json:"track_number"`
  43. Type string `json:"type"`
  44. Uri string `json:"uri"`
  45. }
  46. type AlbumInfo struct {
  47. AlbumType string `json:"album_type"`
  48. Artists []ArtistInfo `json:"artists"`
  49. ExternalUrls ExternalUrls `json:"external_urls"`
  50. Href string `json:"href"`
  51. ID string `json:"id"`
  52. Images []ImageInfo `json:"images"`
  53. Name string `json:"name"`
  54. Type string `json:"type"`
  55. Uri string `json:"uri"`
  56. }
  57. type ArtistInfo struct {
  58. ExternalUrls ExternalUrls `json:"external_urls"`
  59. Href string `json:"href"`
  60. ID string `json:"id"`
  61. Name string `json:"name"`
  62. Type string `json:"type"`
  63. Uri string `json:"uri"`
  64. }
  65. type ImageInfo struct {
  66. Height int `json:"height"`
  67. URL string `json:url`
  68. Width int `json:"width"`
  69. }
  70. type ExternalIds struct {
  71. ISRC string `json:"isrc"`
  72. }
  73. type ExternalUrls struct {
  74. Spotify string `json:"spotify"`
  75. }
  76. type TokenInfo struct {
  77. AccessToken string `json:"access_token"`
  78. TokenType string `json:"token_type"`
  79. ExpiresIn int `json:"expires_in"`
  80. }
  81. type AuthErrorResponse struct {
  82. Error string `json:"error"`
  83. ErrorDescription string `json:"error_description"`
  84. }
  85. type ErrorResponse struct {
  86. Error ErrorInfo `json:"error"`
  87. }
  88. type ErrorInfo struct {
  89. Status int `json:"status"`
  90. Message string `json:"message"`
  91. }
  92. type PlaylistInfo struct {
  93. Collaborative bool `json:"collaborative"`
  94. Description string `json:"description"`
  95. ExternalUrls ExternalUrls `json:"external_urls"`
  96. Followers Followers `json:"followers"`
  97. Href string `json:"href"`
  98. Id string `json:"id"`
  99. // TODO images
  100. Name string `json:"name"`
  101. // TODO owner
  102. Public bool `json:"public"`
  103. SnapshotId string `json:"snapshot_id"`
  104. Tracks TracksInfo `json:"tracks"`
  105. Type string `json:"type"`
  106. Uri string `json:"uri"`
  107. }
  108. type TracksInfo struct {
  109. Href string `json:"href"`
  110. Items []PlaylistTrack `json:"items"`
  111. Limit int `json:"limit"`
  112. Next string `json:"next"`
  113. Offset int `json:"offset"`
  114. Type string `json:"type"`
  115. Previous string `json:"string"`
  116. Total int `json:"total"`
  117. }
  118. type PlaylistTrack struct {
  119. AddedAt string `json:"added_at"`
  120. AddedBy string `json:"added_by"`
  121. IsLocal bool `json:"is_local"`
  122. Track TrackInfo `json":track"`
  123. }
  124. type Followers struct {
  125. Href string `json:"href"`
  126. Total int `json:"total"`
  127. }
  128. type SpotifyProfile struct {
  129. Birthdate string `json:"birthdate"`
  130. Country string `json:"country"`
  131. DisplayName string `json:"display_name"`
  132. Email string `json:"email"`
  133. ExternalUrls ExternalUrls `json:"external_urls"`
  134. Followers Followers `json:"followers"`
  135. Id string `json:"id"`
  136. Product string `json:"product"`
  137. Type string `json:"type"`
  138. Uri string `json:"uri"`
  139. }
  140. func NewClient(username, secret string) *SpotifyClient {
  141. baseURL, _ := url.Parse("https://api.spotify.com")
  142. httpClient := &http.Client{}
  143. return &SpotifyClient{
  144. clientID: username,
  145. clientSecret: secret,
  146. baseURL: baseURL,
  147. httpClient: httpClient,
  148. }
  149. }
  150. func (s *SpotifyClient) Authenticate() error {
  151. config := &clientcredentials.Config{
  152. ClientID: s.clientID,
  153. ClientSecret: s.clientSecret,
  154. TokenURL: spotifyAuth.Endpoint.TokenURL,
  155. }
  156. token, err := config.Token(context.Background())
  157. if err != nil {
  158. log.Println(err)
  159. return err
  160. }
  161. s.bearerAuth = token.AccessToken
  162. return nil
  163. }
  164. func (s *SpotifyClient) SetupUserAuthenticate(redirectURL string) error {
  165. s.config = &oauth2.Config{
  166. ClientID: s.clientID,
  167. ClientSecret: s.clientSecret,
  168. RedirectURL: redirectURL,
  169. Scopes: []string{"playlist-modify-public"},
  170. Endpoint: spotifyAuth.Endpoint,
  171. }
  172. tr := &http.Transport{
  173. TLSNextProto: map[string]func(authority string, c *tls.Conn) http.RoundTripper{},
  174. }
  175. s.context = context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: tr})
  176. return nil
  177. }
  178. func (s *SpotifyClient) GetTrack(trackId string) (*TrackInfo, error) {
  179. var trackInfo TrackInfo
  180. url := s.urlFromBase(fmt.Sprintf("/v1/tracks/%s", trackId))
  181. err := s.doRequest("GET", url, &trackInfo, nil, nil)
  182. if err != nil {
  183. return nil, err
  184. } else {
  185. return &trackInfo, nil
  186. }
  187. }
  188. func (s *SpotifyClient) NewPlaylist(name, userId string) (*PlaylistInfo, error) {
  189. var playlistInfo PlaylistInfo
  190. values := &url.Values{}
  191. values.Add("name", name)
  192. url := s.urlFromBase(fmt.Sprintf("/v1/users/%s/playlists", userId))
  193. err := s.doRequest("POST", url, &playlistInfo, values, nil)
  194. if err != nil {
  195. return nil, err
  196. } else {
  197. return &playlistInfo, nil
  198. }
  199. }
  200. type Playlist struct {
  201. Uris []string `json:"uris"`
  202. }
  203. func (s *SpotifyClient) UpdatePlaylist(userId, playlistId string, tracks []string) error {
  204. uris := make([]string, 0)
  205. for _, track := range tracks {
  206. uris = append(uris, "spotify:track:"+track)
  207. }
  208. //playlist := &Playlist{uris}
  209. values := &url.Values{}
  210. values.Add("uris", strings.Join(uris, ","))
  211. result := struct {
  212. SnapshotID string `json:"snapshot_id"`
  213. }{}
  214. url := s.urlFromBase(fmt.Sprintf("/v1/users/%s/playlists/%s", userId, playlistId))
  215. err := s.doRequest("PUT", url, &result, values, nil)
  216. return err
  217. }
  218. func (s *SpotifyClient) GetMe() (*SpotifyProfile, error) {
  219. var profile SpotifyProfile
  220. url := s.urlFromBase(fmt.Sprintf("/v1/me"))
  221. err := s.doRequest("GET", url, &profile, nil, nil)
  222. if err != nil {
  223. return nil, err
  224. } else {
  225. return &profile, nil
  226. }
  227. }
  228. func (s *SpotifyClient) urlFromBase(path string) *url.URL {
  229. endpoint := &url.URL{Path: path}
  230. return s.baseURL.ResolveReference(endpoint)
  231. }
  232. func (s *SpotifyClient) doRequest(method string, url *url.URL, object interface{}, values *url.Values, inputBody interface{}) error {
  233. var bodyReader io.Reader
  234. var contentType string
  235. if inputBody != nil {
  236. //pr, pw := io.Pipe()
  237. //go func() {
  238. // err := json.NewEncoder(pw).Encode(&inputBody)
  239. // pw.Close()
  240. // if err != nil {
  241. // log.Printf("Spotify: Encoding body failed: %s\n", err.Error())
  242. // }
  243. //}()
  244. var buf bytes.Buffer
  245. err := json.NewEncoder(&buf).Encode(&inputBody)
  246. log.Printf("Spotify: Body is '%s'\n", buf.String())
  247. if err != nil {
  248. log.Printf("Spotify: Encoding body failed: %s\n", err.Error())
  249. return err
  250. }
  251. bodyReader = &buf
  252. contentType = "application/json"
  253. } else if values != nil {
  254. s := values.Encode()
  255. bodyReader = strings.NewReader(s)
  256. contentType = "application/x-www-form-urlencoded"
  257. }
  258. req, err := http.NewRequest(method, url.String(), bodyReader)
  259. if err != nil {
  260. return err
  261. }
  262. req.Header.Set("Content-Type", contentType)
  263. if s.bearerAuth != "" {
  264. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.bearerAuth))
  265. }
  266. req.Header.Set("Accept", "application/json")
  267. req.Header.Set("User-Agent", "github.com/lamperi/e4bot/spotify")
  268. log.Printf("Spotify: %s %s\n", method, url.Path)
  269. resp, err := s.httpClient.Do(req)
  270. if err != nil {
  271. return err
  272. }
  273. defer resp.Body.Close()
  274. if resp.StatusCode != 200 {
  275. var errorResp ErrorResponse
  276. err = json.NewDecoder(resp.Body).Decode(&errorResp)
  277. return errors.New(fmt.Sprintf("Spotify API returned: %d: %s", resp.StatusCode, errorResp.Error.Message))
  278. }
  279. if object != nil {
  280. log.Printf("Spotify: Trying to decode payload %s\n", reflect.TypeOf(object))
  281. err = json.NewDecoder(resp.Body).Decode(object)
  282. if err != nil {
  283. return err
  284. }
  285. }
  286. return nil
  287. }
  288. func (s *SpotifyClient) GetAuthUrl(state string) string {
  289. return s.config.AuthCodeURL(state)
  290. }
  291. func (s *SpotifyClient) HandleToken(state string, r *http.Request) error {
  292. values := r.URL.Query()
  293. if e := values.Get("error"); e != "" {
  294. return errors.New("spotify: auth failed - " + e)
  295. }
  296. code := values.Get("code")
  297. if code == "" {
  298. return errors.New("spotify: didn't get access code")
  299. }
  300. actualState := values.Get("state")
  301. if actualState != state {
  302. return errors.New("spotify: redirect state parameter doesn't match")
  303. }
  304. token, err := s.config.Exchange(s.context, code)
  305. if err != nil {
  306. return err
  307. }
  308. log.Println("Got token from Spotify", token)
  309. client := s.config.Client(s.context, token)
  310. s.httpClient = client
  311. return nil
  312. }
  313. func (s *SpotifyClient) HasUserLogin() bool {
  314. return s.httpClient != nil && s.config != nil && s.context != nil
  315. }