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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
|
package main
// HTTP routes.
//
// The UI is server-rendered HTML driven by htmx: buttons POST to "snips/…"
// endpoints that return a fragment which replaces the button. Every route that
// mutates something also works without JavaScript, by falling back to a
// redirect (see htmxOrReferer and redirectOrFallback below).
//
// Route names, methods and the htmx attributes are kept identical to the
// Haskell version so the two can be diffed against the same database.
import (
"context"
"embed"
"encoding/json"
"fmt"
"html/template"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"golang.org/x/sync/errgroup"
)
//go:embed templates/*.html
var templateFS embed.FS
//go:embed static/progress-player.js
var progressPlayerJS []byte
var templates = template.Must(template.ParseFS(templateFS, "templates/*.html"))
// routes builds the mux.
func (a *app) routes() http.Handler {
mux := http.NewServeMux()
a.assets.registerRoutes(mux)
mux.HandleFunc("/static/progress-player.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
w.Write(progressPlayerJS)
})
// Transmission's download directory, served for the audio player. Only
// mounted when a directory is configured.
if a.cfg.downloadDirectory != "" {
mux.Handle(a.cfg.staticFileEndpoint+"/",
http.StripPrefix(a.cfg.staticFileEndpoint+"/",
http.FileServer(http.Dir(a.cfg.downloadDirectory))))
}
mux.HandleFunc("/", a.handleIndex)
mux.HandleFunc("/redacted-search", a.handleSearch)
mux.HandleFunc("/artist", a.handleArtist)
mux.HandleFunc("/artist/refresh", a.handleArtistRefresh)
mux.HandleFunc("/populate-recommendations", a.handlePopulateRecommendations)
mux.HandleFunc("/autorefresh", a.handleAutorefresh)
mux.HandleFunc("/serve/torrent", a.handleServeTorrent)
mux.HandleFunc("/serve/torrent/cover", a.handleServeTorrentCover)
mux.HandleFunc("/snips/redacted/torrentDataJson", a.handleTorrentDataJSON)
mux.HandleFunc("/snips/redacted/getTorrentFile", a.handleGetTorrentFile)
mux.HandleFunc("/snips/redacted/startTorrentFile", a.handleStartTorrentFile)
mux.HandleFunc("/snips/transmission/getTorrentState", a.handleTorrentState)
return withRouteSpan(mux)
}
// withRouteSpan opens a span per request, named after the path, matching the
// "Route /…" spans the Haskell version produced.
func withRouteSpan(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "Route "+r.URL.Path)
defer span.End()
attr(span, "server.path", r.URL.Path)
attr(span, "server.query_args", r.URL.RawQuery)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// ---------------------------------------------------------------------------
// Page rendering
// ---------------------------------------------------------------------------
// pageData is the model for the full-page template.
type pageData struct {
Title string
AssetTags template.HTML
MainContent template.HTML
SearchFieldContent string
Settings settingsView
UniqueRunID string
}
type settingsView struct {
FreeleechExhausted bool
}
// writePage streams a full page.
//
// The <head> is written and flushed before the body is computed, so the browser
// can start fetching the stylesheet and scripts while the (often slow) database
// and API work is still running. This mirrors the Haskell HtmlStream handler and
// is the reason page rendering is not simply a single ExecuteTemplate call.
func (a *app) writePage(w http.ResponseWriter, r *http.Request, title string, body func(context.Context) (template.HTML, error)) {
ctx := r.Context()
// Start the body work immediately; it runs while the head is being sent.
type bodyResult struct {
html template.HTML
err error
}
done := make(chan bodyResult, 1)
go func() {
h, err := body(ctx)
done <- bodyResult{h, err}
}()
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
head := pageData{Title: title, AssetTags: template.HTML(a.assets.headHTML)}
fmt.Fprint(w, "<!DOCTYPE html>\n<html>\n")
if err := templates.ExecuteTemplate(w, "head", head); err != nil {
slog.Error("rendering head", "err", err)
return
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
res := <-done
if res.err != nil {
// The status line is long gone, so the error has to be rendered into
// the page body.
fmt.Fprintf(w, "<body><h1>Error</h1><pre>%s</pre></body></html>",
template.HTMLEscapeString(res.err.Error()))
slog.Error("rendering page body", "path", r.URL.Path, "err", res.err)
return
}
settings, err := a.getSettings(ctx)
if err != nil {
slog.Warn("could not read settings", "err", err)
}
data := pageData{
MainContent: res.html,
SearchFieldContent: r.URL.Query().Get("searchstr"),
Settings: settingsView{FreeleechExhausted: settings.freeleechTokensExhaustedAt != nil},
UniqueRunID: a.uniqueRunID,
}
fmt.Fprint(w, "<body>\n")
if err := templates.ExecuteTemplate(w, "body", data); err != nil {
slog.Error("rendering body", "err", err)
}
fmt.Fprint(w, "\n</body>\n</html>\n")
}
// ---------------------------------------------------------------------------
// Table rendering
// ---------------------------------------------------------------------------
// tableRow is the view model for one row.
type tableRow struct {
Torrent torrentData
ArtistLinks template.HTML
ReasonLinks template.HTML
GroupLink string
ReleaseTypeTooltip string
TorrentIDVals string
}
type tableData struct {
SectionName string
WithReason bool
Rows []tableRow
}
func mkTableRow(td torrentData, recommendedArtistIDs map[int]bool, reasons []recommendationReason) tableRow {
return tableRow{
Torrent: td,
ArtistLinks: artistLinks(td.Artists, recommendedArtistIDs),
ReasonLinks: reasonLinks(reasons),
GroupLink: mkRedactedTorrentLink(td.GroupID),
ReleaseTypeTooltip: fmt.Sprintf("%s (Release type ID: %d)", td.ReleaseType.StringKey, td.ReleaseType.IntKey),
TorrentIDVals: fmt.Sprintf(`{"torrent-id":%d}`, td.TorrentID),
}
}
// artistLinks renders the comma-separated artist links.
//
// Artists that triggered a recommendation are emphasised, so it is visible why
// a row is being suggested.
func artistLinks(artists []artistRef, emphasise map[int]bool) template.HTML {
var parts []string
for _, ar := range artists {
name := template.HTMLEscapeString(ar.Name)
if emphasise[ar.ID] {
name = "<em>" + name + "</em>"
}
parts = append(parts, fmt.Sprintf(`<a href="%s">%s</a>`, mkArtistLink(ar.ID), name))
}
return template.HTML(strings.Join(parts, ", "))
}
func reasonLinks(reasons []recommendationReason) template.HTML {
var parts []string
seen := map[int]bool{}
for _, r := range reasons {
if seen[r.FavoritedArtistID] {
continue
}
seen[r.FavoritedArtistID] = true
parts = append(parts, fmt.Sprintf(`<a href="%s">%s</a>`,
mkArtistLink(r.FavoritedArtistID),
template.HTMLEscapeString(r.FavoritedArtistName)))
}
return template.HTML(strings.Join(parts, ", "))
}
func mkArtistLink(artistID int) string {
return fmt.Sprintf("/artist?redacted_id=%d", artistID)
}
// renderTorrentTable renders one section.
func renderTorrentTable(sectionName string, torrents []torrentData) (template.HTML, error) {
data := tableData{SectionName: sectionName}
for _, td := range torrents {
data.Rows = append(data.Rows, mkTableRow(td, nil, nil))
}
return execTemplate("torrent-table", data)
}
// renderTorrentTableByReleaseType groups the torrents into one table per release
// type, in the canonical release-type order.
func renderTorrentTableByReleaseType(torrents []torrentData) (template.HTML, error) {
groups := map[int][]torrentData{}
var order []int
for _, td := range torrents {
key := releaseTypeSortIndex(td.ReleaseType)
if _, seen := groups[key]; !seen {
order = append(order, key)
}
groups[key] = append(groups[key], td)
}
// Sort the section keys, which are indices into allReleaseTypesSorted.
for i := 0; i < len(order); i++ {
for j := i + 1; j < len(order); j++ {
if order[j] < order[i] {
order[i], order[j] = order[j], order[i]
}
}
}
var out template.HTML
for _, key := range order {
section := groups[key]
name := section[0].ReleaseType.StringKey + "s"
html, err := renderTorrentTable(name, section)
if err != nil {
return "", err
}
out += html
}
return out, nil
}
func renderRecommendationsTable(sectionName string, recs []recommendation) (template.HTML, error) {
data := tableData{SectionName: sectionName, WithReason: true}
for _, rec := range recs {
emphasise := map[int]bool{}
for _, r := range rec.RecommendedBy {
emphasise[r.RecommendedArtistID] = true
}
data.Rows = append(data.Rows, mkTableRow(rec.Torrent, emphasise, rec.RecommendedBy))
}
table, err := execTemplate("torrent-table", data)
if err != nil {
return "", err
}
form, err := execTemplate("recommendations-form", nil)
if err != nil {
return "", err
}
return form + table, nil
}
func execTemplate(name string, data any) (template.HTML, error) {
var sb strings.Builder
if err := templates.ExecuteTemplate(&sb, name, data); err != nil {
return "", err
}
return template.HTML(sb.String()), nil
}
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
// handleIndex renders the landing page: latest releases by favourite artists,
// plus recommendations.
func (a *app) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
a.writePage(w, r, "whatcd-resolver", func(ctx context.Context) (template.HTML, error) {
var (
latest []torrentData
recs []recommendation
)
g, gctx := errgroup.WithContext(ctx)
g.Go(func() error {
limit := 100
var err error
latest, err = a.getBestTorrentsData(gctx, bestTorrentsFilter{
LimitResults: &limit,
Ordering: byLastReleases,
OnlyFavourites: true,
DisallowedReleaseTypes: []releaseType{
releaseTypeBootleg,
releaseTypeGuestAppearance,
},
})
return err
})
g.Go(func() error {
limit := 50
var err error
recs, err = a.getRecommendedTorrentsData(gctx, []releaseType{
releaseTypeBootleg,
releaseTypeGuestAppearance,
releaseTypeRemix,
releaseTypeDJMix,
}, &limit)
return err
})
if err := g.Wait(); err != nil {
return "", err
}
var out template.HTML
if len(latest) == 0 {
out += "<h1>Latest Releases</h1><p>No torrents found</p>"
} else {
html, err := renderTorrentTable("Latest Releases", latest)
if err != nil {
return "", err
}
out += html
}
if len(recs) == 0 {
form, err := execTemplate("recommendations-form", nil)
if err != nil {
return "", err
}
out += "<h1>Recommended</h1><p>No recommended releases found</p>" + form
} else {
html, err := renderRecommendationsTable("Recommended", recs)
if err != nil {
return "", err
}
out += html
}
return out, nil
})
}
// handleSearch runs a Redacted search, stores the results and shows them.
func (a *app) handleSearch(w http.ResponseWriter, r *http.Request) {
searchstr := r.URL.Query().Get("searchstr")
if searchstr == "" {
http.Error(w, `No such query argument "searchstr"`, http.StatusBadRequest)
return
}
a.writePage(w, r, "whatcd-resolver – Search – "+searchstr, func(ctx context.Context) (template.HTML, error) {
q := map[string][]string{"searchstr": {searchstr}}
ids, err := a.searchAndInsert(ctx, q, 0)
if err != nil {
return "", err
}
torrents, err := a.getBestTorrentsData(ctx, bestTorrentsFilter{
OnlyTheseTorrents: ids,
})
if err != nil {
return "", err
}
table, err := renderTorrentTableByReleaseType(torrents)
if err != nil {
return "", err
}
return template.HTML(fmt.Sprintf("<h1>Search results for <pre>%s</pre></h1>",
template.HTMLEscapeString(searchstr))) + table, nil
})
}
// handleArtist shows one artist's releases, and marks them as a favourite.
func (a *app) handleArtist(w http.ResponseWriter, r *http.Request) {
artistID, err := queryInt(r, "redacted_id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
title := "whatcd-resolver"
if name, err := a.getArtistNameByID(r.Context(), artistID); err == nil && name != "" {
title = name + " - Artist Page - whatcd-resolver"
}
a.writePage(w, r, title, func(ctx context.Context) (template.HTML, error) {
// Visiting an artist page counts as marking them a favourite.
if _, err := a.pool.Exec(ctx,
`INSERT INTO redacted.artist_favourites (artist_id) VALUES ($1) ON CONFLICT DO NOTHING`,
artistID); err != nil {
return "", err
}
torrents, err := a.getBestTorrentsData(ctx, bestTorrentsFilter{OnlyArtistID: &artistID})
if err != nil {
return "", err
}
table, err := renderTorrentTableByReleaseType(torrents)
if err != nil {
return "", err
}
return template.HTML(`<div id="artist-torrents">`) + table + template.HTML(fmt.Sprintf(`</div>
<form method="post" action="artist/refresh" hx-post="artist/refresh">
<input hidden type="text" name="artist-id" value="%d" />
<button type="submit" hx-disabled-elt="this">Refresh Artist Page</button>
<div class="htmx-indicator">Refreshing!</div>
</form>`, artistID)), nil
})
}
// handleArtistRefresh re-fetches an artist's discography, then returns to the
// artist page.
func (a *app) handleArtistRefresh(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
artistID, err := formInt(r, "artist-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, err := a.refreshArtist(r.Context(), artistID); err != nil {
httpError(w, err)
return
}
redirectOrFallback(w, r, mkArtistLink(artistID))
}
// handlePopulateRecommendations fetches similar artists and their releases.
//
// This is slow (many API calls) and deliberately synchronous, as in the Haskell
// version: the button is disabled by htmx while it runs.
func (a *app) handlePopulateRecommendations(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ctx := r.Context()
favourites, err := a.populateSimilarArtistsForFavourites(ctx)
if err != nil {
httpError(w, err)
return
}
releases, err := a.populateReleasesForSimilarArtists(ctx)
if err != nil {
httpError(w, err)
return
}
html := fmt.Sprintf(`
<div>
<h2>Recommendation Population Complete!</h2>
<p>Processed %d favorite artists</p>
<p>Found releases for %d similar artists</p>
<p><a href="/">Return to main page</a></p>
</div>`, favourites, releases)
htmxOrReferer(w, r, html)
}
// handleAutorefresh tells the browser to reload if the server has restarted.
func (a *app) handleAutorefresh(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
if r.URL.Query().Get("hasItBeenRestarted") != a.uniqueRunID {
w.Header().Set("HX-Refresh", "true")
}
w.WriteHeader(http.StatusOK)
}
// handleTorrentDataJSON renders the stored API JSON for a torrent.
func (a *app) handleTorrentDataJSON(w http.ResponseWriter, r *http.Request) {
torrentID, err := formInt(r, "torrent-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
raw, err := a.getTorrentByID(r.Context(), torrentID)
if err != nil {
httpError(w, err)
return
}
var val any
if err := json.Unmarshal(raw, &val); err != nil {
httpError(w, err)
return
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, renderJSONValue(val))
}
// handleGetTorrentFile downloads a .torrent from Redacted and hands it to
// Transmission.
func (a *app) handleGetTorrentFile(w http.ResponseWriter, r *http.Request) {
torrentID, err := formInt(r, "torrent-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx := r.Context()
settings, err := a.getSettings(ctx)
if err != nil {
httpError(w, err)
return
}
file, status, err := a.getTorrentFileAndInsert(ctx, torrentID, settings.freeleechTokensExhaustedAt)
if err != nil {
httpError(w, err)
return
}
// Record or clear the token exhaustion, so the 24h back-off in
// getTorrentFile has something to work from.
switch status {
case noTokensRemaining:
now := time.Now().UTC()
if err := a.setFreeleechExhausted(ctx, &now); err != nil {
slog.Warn("could not record freeleech exhaustion", "err", err)
}
case freeleechPossible:
if settings.freeleechTokensExhaustedAt != nil {
if err := a.setFreeleechExhausted(ctx, nil); err != nil {
slog.Warn("could not clear freeleech exhaustion", "err", err)
}
}
}
a.startTorrentAndRespond(w, r, torrentID, file)
}
// handleStartTorrentFile hands an already-downloaded .torrent to Transmission.
func (a *app) handleStartTorrentFile(w http.ResponseWriter, r *http.Request) {
torrentID, err := formInt(r, "torrent-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
file, err := a.getTorrentFileByID(r.Context(), torrentID)
if err != nil {
httpError(w, err)
return
}
if len(file) == 0 {
httpError(w, fmt.Errorf("no torrent file for torrentId %d", torrentID))
return
}
a.startTorrentAndRespond(w, r, torrentID, file)
}
// startTorrentAndRespond adds the torrent and returns the polling snippet.
func (a *app) startTorrentAndRespond(w http.ResponseWriter, r *http.Request, torrentID int, file []byte) {
ctx := r.Context()
hash, _, err := a.transmission.addTorrent(ctx, file)
if err != nil {
httpError(w, err)
return
}
if err := a.updateTransmissionTorrentHashByID(ctx, torrentID, hash); err != nil {
httpError(w, err)
return
}
// The returned fragment replaces the button and polls for progress.
html := fmt.Sprintf(
`<div hx-trigger="every 1s" hx-swap="outerHTML" hx-post="snips/transmission/getTorrentState" hx-vals="{"torrent-hash":"%s"}">Starting</div>`,
template.HTMLEscapeString(hash))
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, html)
}
// handleTorrentState reports whether Transmission still has a torrent.
func (a *app) handleTorrentState(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
hash := r.FormValue("torrent-hash")
if hash == "" {
http.Error(w, "missing torrent-hash", http.StatusBadRequest)
return
}
status, err := a.transmission.listTorrentsByHash(r.Context(), []string{hash})
if err != nil {
httpError(w, err)
return
}
w.Header().Set("Content-Type", "text/html")
if _, ok := status[hash]; ok {
fmt.Fprint(w, "Running")
} else {
fmt.Fprint(w, "ERROR unknown")
}
}
// handleServeTorrent redirects to the file endpoint for one file of a torrent.
func (a *app) handleServeTorrent(w http.ResponseWriter, r *http.Request) {
torrentID, err := queryInt(r, "torrent-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fileID, err := queryInt(r, "file-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if a.cfg.downloadDirectory == "" {
http.Error(w, "Transmission download disabled", http.StatusNotFound)
return
}
path, err := a.getTorrentFilePath(r.Context(), torrentID, fileID)
if err != nil {
httpError(w, err)
return
}
if path == "" {
http.Error(w, "Torrent file not found", http.StatusNotFound)
return
}
http.Redirect(w, r, a.cfg.staticFileEndpoint+"/"+path, http.StatusSeeOther)
}
// handleServeTorrentCover serves or redirects to a release's cover art.
func (a *app) handleServeTorrentCover(w http.ResponseWriter, r *http.Request) {
torrentID, err := queryInt(r, "torrent-id")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if a.cfg.downloadDirectory == "" {
http.Error(w, "Transmission download disabled", http.StatusNotFound)
return
}
art, err := a.getTorrentCoverArt(r.Context(), torrentID)
if err != nil {
httpError(w, err)
return
}
if art == nil {
http.Error(w, "Torrent cover not found", http.StatusNotFound)
return
}
if art.Path != "" {
http.Redirect(w, r, a.cfg.staticFileEndpoint+"/"+art.Path, http.StatusSeeOther)
return
}
w.Header().Set("Content-Type", art.MIMEType)
w.Write(art.Picture)
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// htmxOrReferer returns the fragment to htmx, or reloads the previous page when
// JavaScript is not available, so POST endpoints work without htmx.
func htmxOrReferer(w http.ResponseWriter, r *http.Request, html string) {
if r.Header.Get("Hx-Request") == "" {
if ref := r.Header.Get("Referer"); ref != "" {
http.Redirect(w, r, ref, http.StatusSeeOther)
return
}
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, html)
}
// redirectOrFallback redirects, using htmx's client-side redirect when
// available and a normal 303 otherwise.
func redirectOrFallback(w http.ResponseWriter, r *http.Request, target string) {
if r.Header.Get("Hx-Request") != "" {
w.Header().Set("Hx-Redirect", target)
w.WriteHeader(http.StatusOK)
return
}
http.Redirect(w, r, target, http.StatusSeeOther)
}
func queryInt(r *http.Request, name string) (int, error) {
v := r.URL.Query().Get(name)
if v == "" {
return 0, fmt.Errorf("no such query argument %q", name)
}
n, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("query argument %q is not a number: %q", name, v)
}
return n, nil
}
func formInt(r *http.Request, name string) (int, error) {
if err := r.ParseForm(); err != nil {
return 0, err
}
v := r.FormValue(name)
if v == "" {
return 0, fmt.Errorf("field %q does not exist in the form", name)
}
n, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("field %q is not a number: %q", name, v)
}
return n, nil
}
func httpError(w http.ResponseWriter, err error) {
slog.Error("request failed", "err", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// renderJSONValue renders arbitrary JSON as HTML, the way the Haskell Html.mkVal
// did: objects as definition lists, arrays as ordered lists.
func renderJSONValue(v any) string {
switch val := v.(type) {
case nil:
return "<em>null</em>"
case bool:
if val {
return "<em>true</em>"
}
return "<em>false</em>"
case float64:
return template.HTMLEscapeString(strconv.FormatFloat(val, 'f', -1, 64))
case string:
return template.HTMLEscapeString(val)
case []any:
var sb strings.Builder
sb.WriteString("<ol>")
for _, el := range val {
sb.WriteString("<li>" + renderJSONValue(el) + "</li>")
}
sb.WriteString("</ol>")
return sb.String()
case map[string]any:
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
// Sorted, so the output is stable and comparable between runs.
for i := 0; i < len(keys); i++ {
for j := i + 1; j < len(keys); j++ {
if keys[j] < keys[i] {
keys[i], keys[j] = keys[j], keys[i]
}
}
}
var sb strings.Builder
sb.WriteString("<dl>")
for _, k := range keys {
sb.WriteString("<dt>" + template.HTMLEscapeString(k) + "</dt>")
sb.WriteString("<dd>" + renderJSONValue(val[k]) + "</dd>")
}
sb.WriteString("</dl>")
return sb.String()
default:
return template.HTMLEscapeString(fmt.Sprint(val))
}
}
|