Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
73 lines
2.3 KiB
Go
73 lines
2.3 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/images"
|
|
)
|
|
|
|
type coverHandlers struct{ svc coverService }
|
|
|
|
// sizeParam reads ?size=: absent means large, otherwise exactly "small" or "large" once.
|
|
func sizeParam(c *gin.Context) (images.Size, bool) {
|
|
values := c.QueryArray("size")
|
|
switch {
|
|
case len(values) == 0:
|
|
return images.Large, true
|
|
case len(values) == 1 && values[0] == string(images.Small):
|
|
return images.Small, true
|
|
case len(values) == 1 && values[0] == string(images.Large):
|
|
return images.Large, true
|
|
}
|
|
writeError(c, http.StatusBadRequest, "invalid_input", "size must be small or large")
|
|
return "", false
|
|
}
|
|
|
|
// album serves the cover of an album: a JPEG made from the picture in the album's own
|
|
// files, built on the first request. It never contacts anybody.
|
|
func (h *coverHandlers) album(c *gin.Context) {
|
|
id, ok := pathID(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
size, ok := sizeParam(c)
|
|
if !ok {
|
|
return
|
|
}
|
|
cover, err := h.svc.AlbumCover(c.Request.Context(), id, size)
|
|
switch {
|
|
case errors.Is(err, images.ErrAlbumNotFound):
|
|
writeError(c, http.StatusNotFound, "album_not_found", "no such album")
|
|
return
|
|
case errors.Is(err, images.ErrNoCover):
|
|
writeError(c, http.StatusNotFound, "cover_not_found", "this album has no cover")
|
|
return
|
|
case errors.Is(err, images.ErrFilesUnreadable):
|
|
_ = c.Error(err)
|
|
writeError(c, http.StatusServiceUnavailable, "files_unreadable", "the files of the album could not be read, try again later")
|
|
return
|
|
case errors.Is(err, images.ErrSourceUnavailable):
|
|
_ = c.Error(err) // keep the cause in the log
|
|
writeError(c, http.StatusBadGateway, "provider_unavailable", "the cover provider could not be reached, try again later")
|
|
return
|
|
case errors.Is(err, context.Canceled):
|
|
c.AbortWithStatus(statusClientClosed) // the client left; nobody is waiting
|
|
return
|
|
case err != nil:
|
|
_ = c.Error(err)
|
|
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
|
return
|
|
}
|
|
defer cover.File.Close()
|
|
|
|
hdr := c.Writer.Header()
|
|
hdr.Set("Content-Type", "image/jpeg")
|
|
hdr.Set("ETag", `"`+cover.ETag+`"`)
|
|
hdr.Set("Cache-Control", "private, max-age=3600") // it is the listener's own library
|
|
hdr.Set("X-Content-Type-Options", "nosniff")
|
|
http.ServeContent(c.Writer, c.Request, "cover.jpg", cover.ModTime, cover.File)
|
|
}
|