-
-
Notifications
You must be signed in to change notification settings - Fork 760
/
routes_performer.go
85 lines (70 loc) · 1.94 KB
/
routes_performer.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
package api
import (
"context"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/stashapp/stash/pkg/logger"
"github.com/stashapp/stash/pkg/models"
"github.com/stashapp/stash/pkg/utils"
)
type PerformerFinder interface {
models.PerformerGetter
GetImage(ctx context.Context, performerID int) ([]byte, error)
}
type performerRoutes struct {
routes
performerFinder PerformerFinder
}
func (rs performerRoutes) Routes() chi.Router {
r := chi.NewRouter()
r.Route("/{performerId}", func(r chi.Router) {
r.Use(rs.PerformerCtx)
r.Get("/image", rs.Image)
})
return r
}
func (rs performerRoutes) Image(w http.ResponseWriter, r *http.Request) {
performer := r.Context().Value(performerKey).(*models.Performer)
defaultParam := r.URL.Query().Get("default")
var image []byte
if defaultParam != "true" {
readTxnErr := rs.withReadTxn(r, func(ctx context.Context) error {
var err error
image, err = rs.performerFinder.GetImage(ctx, performer.ID)
return err
})
if errors.Is(readTxnErr, context.Canceled) {
return
}
if readTxnErr != nil {
logger.Warnf("read transaction error on fetch performer image: %v", readTxnErr)
}
}
if len(image) == 0 {
image = getDefaultPerformerImage(performer.Name, performer.Gender)
}
utils.ServeImage(w, r, image)
}
func (rs performerRoutes) PerformerCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
performerID, err := strconv.Atoi(chi.URLParam(r, "performerId"))
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
var performer *models.Performer
_ = rs.withReadTxn(r, func(ctx context.Context) error {
var err error
performer, err = rs.performerFinder.Find(ctx, performerID)
return err
})
if performer == nil {
http.Error(w, http.StatusText(404), 404)
return
}
ctx := context.WithValue(r.Context(), performerKey, performer)
next.ServeHTTP(w, r.WithContext(ctx))
})
}