79 lines
2.3 KiB
Go
79 lines
2.3 KiB
Go
package contented
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
|
|
"code.ivysaur.me/thumbnail"
|
|
)
|
|
|
|
func thumbnailer(t byte) (*thumbnail.Thumbnailer, error) {
|
|
// Modelled on what imgur.com offers
|
|
// @ref https://api.imgur.com/models/image#thumbs
|
|
|
|
const (
|
|
cacheSize = 1
|
|
outputFmt = thumbnail.OUTPUT_JPG
|
|
scaleFmt = thumbnail.SCALEFMT_BILINEAR
|
|
)
|
|
|
|
switch t {
|
|
case 's':
|
|
return thumbnail.NewThumbnailerEx(90, 90, cacheSize, outputFmt, thumbnail.ASPECT_CROP_TO_DIMENSIONS, scaleFmt), nil
|
|
case 'b':
|
|
return thumbnail.NewThumbnailerEx(160, 160, cacheSize, outputFmt, thumbnail.ASPECT_CROP_TO_DIMENSIONS, scaleFmt), nil
|
|
case 't':
|
|
return thumbnail.NewThumbnailerEx(160, 160, cacheSize, outputFmt, thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY, scaleFmt), nil
|
|
case 'm':
|
|
return thumbnail.NewThumbnailerEx(340, 340, cacheSize, outputFmt, thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY, scaleFmt), nil
|
|
case 'l':
|
|
return thumbnail.NewThumbnailerEx(640, 640, cacheSize, outputFmt, thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY, scaleFmt), nil
|
|
case 'h':
|
|
return thumbnail.NewThumbnailerEx(1024, 1024, cacheSize, outputFmt, thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY, scaleFmt), nil
|
|
default:
|
|
return nil, errors.New("Unsupported thumbnail type (should be s/b/t/m/l/h)")
|
|
}
|
|
}
|
|
|
|
func (this *Server) handleThumb(w http.ResponseWriter, r *http.Request, thumbnailType byte, fileId string) {
|
|
t, err := thumbnailer(thumbnailType)
|
|
if err != nil {
|
|
log.Printf("%s Thumbnail failed: %s\n", this.remoteIP(r), err.Error())
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
|
|
err = this.handleThumbInternal(w, t, fileId)
|
|
if err != nil {
|
|
log.Printf("%s Thumbnail failed: %s\n", this.remoteIP(r), err.Error())
|
|
|
|
w.Header().Set(`Location`, fmt.Sprintf(`/nothumb_%d.png`, t.Height()))
|
|
w.WriteHeader(302)
|
|
}
|
|
}
|
|
|
|
func (this *Server) handleThumbInternal(w http.ResponseWriter, t *thumbnail.Thumbnailer, fileId string) error {
|
|
|
|
// Load metadata
|
|
m, err := this.Metadata(fileId)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
filePath := filepath.Join(this.opts.DataDirectory, m.FileHash)
|
|
thumb, err := t.RenderFile_NoCache_MimeType(filePath, m.MimeType)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
w.Header().Set(`Content-Length`, fmt.Sprintf("%d", len(thumb)))
|
|
w.Header().Set(`Content-Type`, `image/jpeg`)
|
|
w.WriteHeader(200)
|
|
w.Write(thumb)
|
|
|
|
return nil
|
|
}
|