Skip to content

Commit

Permalink
quick refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
brianstrauch committed Jun 30, 2021
1 parent 3305f3d commit d1e72f0
Show file tree
Hide file tree
Showing 10 changed files with 38 additions and 66 deletions.
8 changes: 4 additions & 4 deletions accounts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import (
"testing"
)

func TestCreateVerifierAndChallenge(t *testing.T) {
verifier, challenge, err := CreateVerifierAndChallenge()
func TestCreatePKCEVerifierAndChallenge(t *testing.T) {
verifier, challenge, err := CreatePKCEVerifierAndChallenge()
if err != nil {
t.Fatal(err)
}
Expand All @@ -25,7 +25,7 @@ func TestCreateVerifierAndChallenge(t *testing.T) {
}
}

func TestBuildAuthURI(t *testing.T) {
func TestBuildPKCEAuthURI(t *testing.T) {
var (
clientID = "client"
redirectURI = "http://localhost:1024"
Expand All @@ -34,7 +34,7 @@ func TestBuildAuthURI(t *testing.T) {
scope = "user-modify-playback-state"
)

uri := BuildAuthURI(clientID, redirectURI, challenge, state, scope)
uri := BuildPKCEAuthURI(clientID, redirectURI, challenge, state, scope)

substrings := []string{
"client_id=" + clientID,
Expand Down
1 change: 1 addition & 0 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func (a *API) call(method, apiVersion, endpoint string, query url.Values, body i
RawQuery: query.Encode(),
Scheme: "https",
}

req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return err
Expand Down
1 change: 0 additions & 1 deletion api_test.go

This file was deleted.

1 change: 0 additions & 1 deletion examples/pkce_authorization/pkce_authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const (
func main() {
// 1. Create the code verifier and challenge
verifier, challenge, err := spotify.CreatePKCEVerifierAndChallenge()

if err != nil {
panic(err)
}
Expand Down
48 changes: 12 additions & 36 deletions examples/playlists/playlists.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package main

import (
"context"
"errors"
"fmt"
"net/http"

"github.com/brianstrauch/spotify"
"github.com/brianstrauch/spotify/examples"
"github.com/pkg/browser"
)

Expand All @@ -32,7 +30,7 @@ func main() {
panic(err)
}

code, err := listenForCode(state)
code, err := examples.ListenForCode(state)
if err != nil {
panic(err)
}
Expand All @@ -42,45 +40,23 @@ func main() {
panic(err)
}

playlists, err := spotify.NewAPI(token.AccessToken).GetPlaylists()
api := spotify.NewAPI(token.AccessToken)

playlists, err := api.GetPlaylists()
if err != nil {
panic(err)
} else if len(playlists) == 0 {
panic("no playlists")
}
if len(playlists) == 0 {
panic("no playlists found")
}

playlist := new(spotify.Playlist)
if err := playlists[0].Get(spotify.NewAPI(token.AccessToken), playlist); err != nil {
if err := playlists[0].Get(api, playlist); err != nil {
panic(err)
}
fmt.Println(playlist.Name)
fmt.Printf("%d tracks\n", playlist.Tracks.Total)
}

func listenForCode(state string) (string, error) {
server := &http.Server{Addr: ":1024"}

var code string
var err error

http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state || r.URL.Query().Get("error") != "" {
err = errors.New("authorization failed")
fmt.Fprintln(w, "Failure.")
} else {
code = r.URL.Query().Get("code")
fmt.Fprintln(w, "Success!")
}

// Use a separate thread so browser doesn't show a "No Connection" message
go func() {
server.Shutdown(context.Background())
}()
})

if err := server.ListenAndServe(); err != http.ErrServerClosed {
return "", err
fmt.Println(playlist.Name)
for i, playlistTrack := range playlist.Tracks.Items {
fmt.Printf("%d. %s\n", i+1, playlistTrack.Track.Name)
}

return code, err
}
21 changes: 9 additions & 12 deletions href.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
package spotify

import (
"errors"
"net/url"
"strings"
)

type HREF string

// Get returns the most recent version of the object in it's entirety
// Get returns the most recent version of the object in its entirety
func (h *HREF) Get(api *API, obj interface{}) error {
url, err := h.URL()
if err != nil {
return err
}
urlParts := strings.Split(url.Path, "/")
// looking for a URL that looks something like
// /v1/playlists
if len(urlParts) < 2 {
return errors.New("invalid endpoint structure")
}
apiVersion := urlParts[0]
path := strings.Join(urlParts[1:], "/")
return api.get(apiVersion, path, url.Query(), obj)

// Example path: v1/me/player
idx := strings.Index(url.Path, "/")
version := url.Path[:idx]
endpoint := url.Path[idx:]

return api.get(version, endpoint, url.Query(), obj)
}

// URL parses HREF into a *net/url.URL
// URL parses HREF into a URL object
func (h *HREF) URL() (*url.URL, error) {
return url.Parse(string(*h))
}
14 changes: 7 additions & 7 deletions playlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@ type Playlist struct {
Tracks Tracks `json:"tracks"`
}

// PlaylistResponse is the response type for the Get a Playlist request
type PlaylistResponse struct {
ItemsMeta
Items []Playlist `json:"items"`
}

func (a *API) GetPlaylists() ([]Playlist, error) {
playlists := new(PlaylistResponse)
playlists := &struct {
ItemsMeta
Items []Playlist `json:"items"`
}{}

if err := a.get("v1", "/me/playlists", nil, playlists); err != nil {
return nil, err
}

return playlists.Items, nil
}

Expand All @@ -36,5 +35,6 @@ func (a *API) GetPlaylist(id string) (*Playlist, error) {
if err := a.get("v1", path.Join("/playlists", id), nil, playlist); err != nil {
return nil, err
}

return playlist, nil
}
4 changes: 2 additions & 2 deletions search.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ type Paging struct {
Tracks Tracks `json:"tracks"`
}

// Get Spotify Catalog information about albums, artists, playlists, tracks, shows or episodes that match a keyword
// string.
// Search gets Spotify Catalog information about albums, artists, playlists, tracks, shows or episodes that match a
// keyword string.
func (a *API) Search(q string, limit int) (*Paging, error) {
v := url.Values{}
v.Add("q", q)
Expand Down
4 changes: 2 additions & 2 deletions tracks.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Tracks struct {
Items []PlaylistTrack `json:"items"`
}

// Track represents a Track in the Spotify API
// PlaylistTrack represents a PlaylistTrackObject in the Spotify API
// See https://developer.spotify.com/documentation/web-api/reference/#object-playlisttrackobject
type PlaylistTrack struct {
// AddedAt is when the track was added to the playlist or saved
Expand All @@ -25,7 +25,7 @@ type PlaylistTrack struct {
URI string `json:"uri"`
}

// TrackObject represents the TrackObject struct in the API
// Track represents the TrackObject struct in the API
// https://developer.spotify.com/documentation/web-api/reference/#object-trackobject
type Track struct {
Meta
Expand Down
2 changes: 1 addition & 1 deletion user_profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type User struct {
// GetUserProfile gets detailed profile information about the current user (including the current user's username).
func (a *API) GetUserProfile() (*User, error) {
user := new(User)
err := a.get("/me", user)
err := a.get("v1", "/me", nil, user)

return user, err
}

0 comments on commit d1e72f0

Please sign in to comment.