-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
146 lines (132 loc) · 4.66 KB
/
api.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
package spotify
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"github.com/cheshire137/scrobble-saver/pkg/config"
"github.com/cheshire137/scrobble-saver/pkg/data_store"
"github.com/cheshire137/scrobble-saver/pkg/util"
"github.com/gorilla/sessions"
)
const ApiUrl = "https://api.spotify.com/v1"
type Api struct {
config *config.Config
ds *data_store.DataStore
spotifyUser *data_store.SpotifyUser
session *sessions.Session
w http.ResponseWriter
r *http.Request
}
func NewApi(config *config.Config, ds *data_store.DataStore) *Api {
return &Api{config: config, ds: ds}
}
func NewAuthenticatedApi(config *config.Config, ds *data_store.DataStore, spotifyUser *data_store.SpotifyUser, session *sessions.Session, w http.ResponseWriter, r *http.Request) *Api {
return &Api{config: config, ds: ds, spotifyUser: spotifyUser, session: session, w: w, r: r}
}
func (a *Api) put(path string, body any) *util.RequestError {
url, err := url.Parse(ApiUrl + path)
if err != nil {
return util.NewRequestError(http.StatusInternalServerError, err)
}
bodyJson, err := json.Marshal(body)
if err != nil {
return util.NewRequestError(http.StatusInternalServerError, err)
}
req, err := http.NewRequest(http.MethodPut, url.String(), bytes.NewBuffer(bodyJson))
if err != nil {
return util.NewRequestError(http.StatusInternalServerError, err)
}
util.LogRequest(req)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.spotifyUser.AccessToken))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
util.LogError("Failed to get %s:", path, err)
return util.NewRequestError(http.StatusInternalServerError, err)
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode != http.StatusUnauthorized {
util.LogError("Non-200 response for "+path+":", resp.Status)
}
return util.NewRequestError(resp.StatusCode, fmt.Errorf("%s %s", resp.Status, path))
}
return nil
}
func (a *Api) get(path string, params url.Values, v any) *util.RequestError {
url, err := url.Parse(ApiUrl + path)
if err != nil {
return util.NewRequestError(http.StatusInternalServerError, err)
}
url.RawQuery = params.Encode()
req, err := http.NewRequest(http.MethodGet, url.String(), nil)
if err != nil {
return util.NewRequestError(http.StatusInternalServerError, err)
}
util.LogRequest(req)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.spotifyUser.AccessToken))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
util.LogError("Failed to get %s:", path, err)
return util.NewRequestError(http.StatusInternalServerError, err)
}
return a.handleResponse(resp, path, v)
}
func (a *Api) handleResponse(resp *http.Response, path string, v any) *util.RequestError {
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
util.LogError("Failed to read %s response body:", path, err)
return util.NewRequestError(http.StatusInternalServerError, err)
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode != http.StatusUnauthorized {
util.LogError("Non-200 response for "+path+":", resp.Status, string(data))
}
return util.NewRequestError(resp.StatusCode, fmt.Errorf("%s %s", resp.Status, path))
}
err = json.Unmarshal(data, &v)
if err != nil {
util.LogError("Failed to unmarshal %s response:", path, err)
return util.NewRequestError(resp.StatusCode, err)
}
return nil
}
func (a *Api) getParamsStr(params url.Values) string {
keys := make([]string, len(params))
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
keyValuePairs := make([]string, len(params))
for _, key := range keys {
value := params.Get(key)
keyValuePairs = append(keyValuePairs, key+value)
}
return strings.Join(keyValuePairs, "")
}
func (a *Api) cacheResponse(response any, path, params, userId string) {
spotifyCachedResponse, err := data_store.NewSpotifyCachedResponse(response, path, params, userId)
if err != nil {
util.LogError("Could not serialize Spotify %s response for caching:", path, err)
}
err = a.ds.InsertSpotifyCachedResponse(spotifyCachedResponse)
if err != nil {
util.LogError("Could not cache Spotify %s response:", path, err)
}
util.LogInfo("Cached Spotify %s response for %s", path, userId)
}
func (a *Api) loadCachedResponse(path, paramsForCache, userId string, response any) (bool, error) {
cachedResponseBody := a.ds.LoadCachedSpotifyResponse(path, paramsForCache, userId)
if cachedResponseBody != "" {
util.LogInfo("Using cached response for path=%s, userId=%s, params=%s", path, userId, paramsForCache)
err := json.Unmarshal([]byte(cachedResponseBody), &response)
return true, err // cache hit
}
return false, nil // cache miss
}