-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
372 lines (335 loc) · 12.6 KB
/
api.go
File metadata and controls
372 lines (335 loc) · 12.6 KB
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
package main
import (
"context"
"embed"
"fmt"
"html/template"
"log"
"log/slog"
"net/http"
"strconv"
"time"
"github.com/zmb3/spotify/v2"
)
//go:embed static templates
var webUiContent embed.FS
const httpHandlersHost = ""
const httpHandlersPort = 58071
// ApiHandlersSetup initializes all the http handlers
func ApiHandlersSetup() {
http.Handle("/static/", http.FileServer(http.FS(webUiContent)))
http.HandleFunc("GET /callback", handleSpotifyCallback)
http.HandleFunc("GET /{$}", handleIndex)
http.HandleFunc("GET /playlist-select", handleGetPlaylistSelect)
http.HandleFunc("POST /playlist-select/{id}", handlePostPlaylistSelect)
http.HandleFunc("GET /playing", handleGetPlaying)
http.HandleFunc("GET /playing/{count}", handleGetPlaying)
http.HandleFunc("GET /startlist", handleGetStartList)
http.HandleFunc("GET /runstate", handleGetRunState)
http.HandleFunc("POST /start", handlePostStart)
http.HandleFunc("POST /start/now", handlePostStartNow)
http.HandleFunc("POST /start/{timestamp}", handlePostStart)
http.HandleFunc("POST /stop", handlePostStop)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
slog.Info("Request not found", "method", r.Method, "url", r.URL.String())
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("Not Found"))
})
}
// ApiHandlersRun starts and loops the http server.
func ApiHandlersRun() {
listenAddress := fmt.Sprintf("%s:%d", httpHandlersHost, httpHandlersPort)
log.Fatal(http.ListenAndServe(listenAddress, nil))
}
// renderTemplate takes the given templateFile and data and renders it to the given ResponseWriter.
// If loading the template or rendering itself fails, http.StatusInternalServerError is returned.
func renderTemplate(w http.ResponseWriter, templateFile string, data any) error {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl, err := template.ParseFS(webUiContent, templateFile)
if err != nil {
slog.Warn("Failed to parse template", "path", templateFile, "err", err)
http.Error(w, "Template error", http.StatusInternalServerError)
return err
}
if err := tmpl.Execute(w, data); err != nil {
slog.Warn("Failed to execute template", "path", templateFile, "err", err)
http.Error(w, "Render error", http.StatusInternalServerError)
return err
}
return nil
}
// handleSpotifyCallback http handler is used to finalize the Spotify authentication process.
// See https://developer.spotify.com/documentation/web-api/tutorials/code-flow for details on that.
//
// On successful authentication, this will receive the API token used for future requests.
// The token is sent via tokenCh channel where SpotifyClientSetup is waiting to read from.
//
// If CACHE_AUTH_TOKEN env var is set to 1, the token is cached for future use, and the whole
// process via Spotify authentication is skipped on the next startup.
//
// Renders HTML template to show successful authentication and redirects back home.
func handleSpotifyCallback(writer http.ResponseWriter, request *http.Request) {
token, err := auth.Token(request.Context(), state, request)
if err != nil {
http.Error(writer, "Couldn't get token", http.StatusForbidden)
log.Fatal(err)
}
if st := request.FormValue("state"); st != state {
http.NotFound(writer, request)
log.Fatalf("State mismatch: %s != %s\n", st, state)
}
if GetEnvInt("CACHE_AUTH_TOKEN", 0) == 1 {
slog.Debug("Saving token", "file", SpotifyTokenCacheFile)
if err := SaveToken(token); err != nil {
slog.Warn("Failed to save token", "err", err)
}
}
tokenCh <- token
writer.Header().Set("Refresh", "3; url=/")
if err := renderTemplate(writer, "templates/authdone.html", nil); err != nil {
http.Error(writer, "Something went wrong", http.StatusInternalServerError)
return
}
}
// handleIndex http handler renders the home page on index.html
func handleIndex(writer http.ResponseWriter, _ *http.Request) {
data := struct {
Username string
AuthUrl string
}{
Username: username,
AuthUrl: authUrl,
}
if err := renderTemplate(writer, "templates/index.html", data); err != nil {
return
}
}
// handleGetPlaylists http handler retrieves and renders the list of playlists for the active Spotify user,
// intended to select a new playlist to populate from it.
func handleGetPlaylistSelect(writer http.ResponseWriter, _ *http.Request) {
ctx := context.Background()
items, err := GetPlaylists(ctx)
if err != nil {
slog.Warn("Failed to get playlists", "err", err)
http.Error(writer, "Failed to get playlists", http.StatusInternalServerError)
return
}
data := struct {
Activated PlaylistInfo
Playlists []PlaylistInfo
}{
Activated: playlist,
Playlists: items,
}
if err := renderTemplate(writer, "templates/snippets/playlists.html", data); err != nil {
return
}
}
// handlePostPlaylistSelect http handler sets up the selected playlist as the new active to one to populate
// with the recently played songs, assuming it's valid and the current user can modify.
//
// If the new playlist is the same as the already active playlist, the request is more or less ignored.
// If playlist handling is already ongoing, it's stopped first.
//
// Renders the new state of active playlist on success.
func handlePostPlaylistSelect(writer http.ResponseWriter, request *http.Request) {
playlistId := spotify.ID(request.PathValue("id"))
if playlistId == playlist.ID {
slog.Info("Trying to activate already activated playlist, ignoring", "id", playlistId)
http.Error(writer, "Playlist already active", http.StatusNoContent)
return
}
ctx := context.Background()
if !ValidatePlaylist(ctx, playlistId) {
slog.Warn("Playlist validation failed", "id", playlistId)
http.Error(writer, "Failed to get playlist", http.StatusNotFound)
return
}
if running {
slog.Info("Shutting down current playlist handling", "id", playlist.ID, "name", playlist.Name)
stopCh <- struct{}{}
}
ActivatePlaylist(ctx, client, playlistId) // FIXME why is client always passed around, it's global anyway?
renderSpotifyRunState(writer, running)
}
// handleGetPlaying http handler renders the currently playing song and play history.
// An optional 'count' parameter can be added to the url to limit the number of maximum songs to show,
// defaulting to 0 if omitted.
//
// Rendering itself will add a "load more" option if the 'count' parameter is below Spotify's maximum
// number of last played songs (50).
func handleGetPlaying(writer http.ResponseWriter, request *http.Request) {
ctx := context.Background()
now, err := GetCurrentlyPlaying(ctx)
if err != nil {
slog.Warn("Failed to get currently playing", "err", err)
http.Error(writer, "Failed to get currently playing", http.StatusInternalServerError)
return
}
count := int(parseParamUint(request, "count", 10))
songs, err := GetLastSongs(context.Background(), count, 0)
if err != nil {
slog.Warn("Failed to get last played songs", "err", err)
http.Error(writer, "Failed to get last played songs", http.StatusInternalServerError)
return
}
var last []string
for index, song := range songs {
last = append(last, formatTrack(song.Track))
slog.Info(fmt.Sprintf(" %02d: [%s](%d) %s",
index+1,
song.PlayedAt.Format("2006-01-02 15:04:05 -0700 MST"),
song.PlayedAt.UnixMilli(),
formatTrack(song.Track),
))
}
nextCount := count + 10
if nextCount > 50 {
nextCount = 0
}
data := struct {
Now string
Items []string
Count int
NextCount int
}{
Now: now,
Items: last,
Count: count,
NextCount: nextCount,
}
if err := renderTemplate(writer, "templates/snippets/playing.html", data); err != nil {
return
}
}
// parseParamUint tries to get the value for the request's path wildcard parameter, expecting an unsigned int,
// and return it. If the paramName doesn't exist in the request path or fails to render, the given 'defaultValue'
// is used as a fallback instead.
//
// Note that despite parsing an unsinged integer, a signed integer value is returned here, since any place further
// down the road wants a signed integer anyway, and neither of the path values should be negative.
func parseParamUint(request *http.Request, paramName string, defaultValue int64) int64 {
var value = defaultValue
param := request.PathValue(paramName)
slog.Debug("Parsing path param", "name", paramName, "value", param)
if param != "" {
conv, err := strconv.ParseUint(param, 10, 64)
if err != nil {
slog.Warn("Failed to convert parameter, using default", "param", param, "err", err, "default", defaultValue)
} else {
value = int64(conv)
}
}
return value
}
// handleGetStartList http handler retrieves and renders the list of all recently played songs,
// intended to select a starting point for populating songs into the activated playlist.
func handleGetStartList(writer http.ResponseWriter, request *http.Request) {
songs, err := GetLastSongs(context.Background(), 50, 0)
if err != nil {
slog.Warn("Failed to get last played songs", "err", err)
http.Error(writer, "Failed to get last played songs", http.StatusInternalServerError)
return
}
type lastSongData struct {
Name string
Timestamp int64
}
var last []lastSongData
for _, song := range songs {
last = append(last, lastSongData{
Name: formatTrack(song.Track),
Timestamp: song.PlayedAt.Unix() * 1000, // round down to zero the ms part as some buffer
})
}
data := struct{ Items []lastSongData }{Items: last}
if err := renderTemplate(writer, "templates/snippets/startlist.html", data); err != nil {
return
}
}
// handleGetRunState http handler renders the current playlist processing run state.
func handleGetRunState(writer http.ResponseWriter, _ *http.Request) {
renderSpotifyRunState(writer, running)
}
// handlePostStart http handler tries to start the playlist processing by writing to the startCh channel.
//
// If processing is already running, http.StatusBadRequest is returned.
// If no active playlist is selected, http.StatusBadRequest is returned as well, as processing requires one.
//
// If a timestamp parameter is given in the request url path, only songs after that time will be added to the
// playlist, otherwise all the last played songs will be used.
func handlePostStart(writer http.ResponseWriter, request *http.Request) {
if running {
http.Error(writer, "Already started", http.StatusBadRequest)
return
}
if playlist.ID == "" {
// TODO show some error on the UI somewhere in that case
slog.Warn("Start requested but no playlist selected")
http.Error(writer, "No playlist selected", http.StatusBadRequest)
return
}
timestamp := parseParamUint(request, "timestamp", 0)
if timestamp > 0 {
lastTime = timestamp
}
startCh <- struct{}{}
renderSpotifyRunState(writer, true)
}
// handlePostStartNow http handler tries to start the playlist processing by writing to the startCh channel.
// If playback is currently ongoing, the start time of that song is taken as the processing starting point,
// otherwise the current time is taken, and processing will essentially start with the next played song.
//
// If processing is already running, http.StatusBadRequest is returned.
// If no active playlist is selected, http.StatusBadRequest is returned as well, as processing requires one.
func handlePostStartNow(writer http.ResponseWriter, request *http.Request) {
if running {
http.Error(writer, "Already started", http.StatusBadRequest)
return
}
if playlist.ID == "" {
// TODO show some error on the UI somewhere in that case
slog.Warn("Start requested but no playlist selected")
http.Error(writer, "No playlist selected", http.StatusBadRequest)
return
}
track, err := GetCurrentlyPlayedTrack(context.Background())
if err != nil {
slog.Warn("Cannot get currently played track", "err", err)
http.Error(writer, "Failed to get currently played track", http.StatusInternalServerError)
return
}
if track.Playing {
slog.Debug("Track is playing, using its timestamp", "timestamp", track.Timestamp)
lastTime = track.Timestamp
} else {
slog.Debug("Track not playing, using current time")
lastTime = time.Now().UnixMilli()
}
startCh <- struct{}{}
renderSpotifyRunState(writer, true)
}
// handlePostStop http handler tries to stop the playlist processing by writing to the stopCh channel.
//
// If processing is not running, http.StatusBadRequest is returned.
func handlePostStop(writer http.ResponseWriter, _ *http.Request) {
if !running {
http.Error(writer, "Already stopped", http.StatusBadRequest)
return
}
stopCh <- struct{}{}
renderSpotifyRunState(writer, false)
}
// renderSpotifyRunState renders the current playlist processing running state.
func renderSpotifyRunState(writer http.ResponseWriter, state bool) {
data := struct {
Running bool
Playlist PlaylistInfo
}{
Running: state,
Playlist: playlist,
}
if err := renderTemplate(writer, "templates/snippets/runstate.html", data); err != nil {
return
}
}