2019-02-09 12:30:49 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-04-02 22:11:48 +00:00
|
|
|
"crypto/md5"
|
|
|
|
"fmt"
|
2019-02-09 12:30:49 +00:00
|
|
|
"net/http"
|
|
|
|
"strconv"
|
2020-04-02 22:11:48 +00:00
|
|
|
"strings"
|
2020-06-22 23:19:19 +00:00
|
|
|
|
|
|
|
"github.com/go-chi/chi"
|
|
|
|
"github.com/stashapp/stash/pkg/models"
|
2019-02-09 12:30:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type studioRoutes struct{}
|
|
|
|
|
|
|
|
func (rs studioRoutes) Routes() chi.Router {
|
|
|
|
r := chi.NewRouter()
|
|
|
|
|
|
|
|
r.Route("/{studioId}", func(r chi.Router) {
|
|
|
|
r.Use(StudioCtx)
|
|
|
|
r.Get("/image", rs.Image)
|
|
|
|
})
|
|
|
|
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
func (rs studioRoutes) Image(w http.ResponseWriter, r *http.Request) {
|
2019-02-14 22:53:32 +00:00
|
|
|
studio := r.Context().Value(studioKey).(*models.Studio)
|
2020-06-22 23:19:19 +00:00
|
|
|
qb := models.NewStudioQueryBuilder()
|
|
|
|
image, _ := qb.GetStudioImage(studio.ID, nil)
|
|
|
|
|
|
|
|
etag := fmt.Sprintf("%x", md5.Sum(image))
|
2020-04-02 22:11:48 +00:00
|
|
|
if match := r.Header.Get("If-None-Match"); match != "" {
|
|
|
|
if strings.Contains(match, etag) {
|
|
|
|
w.WriteHeader(http.StatusNotModified)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-22 23:19:19 +00:00
|
|
|
contentType := http.DetectContentType(image)
|
2020-04-02 22:11:48 +00:00
|
|
|
if contentType == "text/xml; charset=utf-8" || contentType == "text/plain; charset=utf-8" {
|
|
|
|
contentType = "image/svg+xml"
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", contentType)
|
|
|
|
w.Header().Add("Etag", etag)
|
2020-06-22 23:19:19 +00:00
|
|
|
w.Write(image)
|
2019-02-09 12:30:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func StudioCtx(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
studioID, err := strconv.Atoi(chi.URLParam(r, "studioId"))
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, http.StatusText(404), 404)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
qb := models.NewStudioQueryBuilder()
|
|
|
|
studio, err := qb.Find(studioID, nil)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, http.StatusText(404), 404)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-02-14 22:53:32 +00:00
|
|
|
ctx := context.WithValue(r.Context(), studioKey, studio)
|
2019-02-09 12:30:49 +00:00
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
2019-02-14 22:53:32 +00:00
|
|
|
}
|