contented/thumb.go

93 lines
2.0 KiB
Go
Raw Normal View History

2017-11-18 00:11:39 +00:00
package contented
import (
"errors"
"fmt"
"log"
"net/http"
"path/filepath"
"code.ivysaur.me/thumbnail"
)
func getThumbnailerConfig(t byte) (*thumbnail.Config, error) {
2017-11-18 00:11:39 +00:00
// Modelled on what imgur.com offers
// @ref https://api.imgur.com/models/image#thumbs
opts := thumbnail.Config{
Aspect: thumbnail.FitOutside,
Output: thumbnail.Jpeg,
Scale: thumbnail.Bicubic,
}
2017-11-18 00:11:39 +00:00
switch t {
case 's':
opts.Width = 90
opts.Height = 90
2017-11-18 00:11:39 +00:00
case 'b':
opts.Width = 160
opts.Height = 160
2017-11-18 00:11:39 +00:00
case 't':
opts.Width = 160
opts.Height = 160
// thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY
2017-11-18 00:11:39 +00:00
case 'm':
opts.Width = 340
opts.Height = 340
// thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY
2017-11-18 00:11:39 +00:00
case 'l':
opts.Width = 640
opts.Height = 640
// thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY
2017-11-18 00:11:39 +00:00
case 'h':
opts.Width = 1024
opts.Height = 1024
// thumbnail.ASPECT_RESPECT_MAX_DIMENSION_ONLY
2017-11-18 00:11:39 +00:00
default:
return nil, errors.New("Unsupported thumbnail type (should be s/b/t/m/l/h)")
}
return &opts, nil
2017-11-18 00:11:39 +00:00
}
func (this *Server) handleThumb(w http.ResponseWriter, r *http.Request, thumbnailType byte, fileId string) {
opts, err := getThumbnailerConfig(thumbnailType)
2017-11-18 00:11:39 +00:00
if err != nil {
log.Printf("%s Thumbnail failed: %s\n", this.remoteIP(r), err.Error())
http.Error(w, err.Error(), 400)
return
2017-11-18 00:11:39 +00:00
}
t := thumbnail.NewThumbnailerEx(opts)
err = this.handleThumbInternal(w, t, fileId)
2017-11-18 00:11:39 +00:00
if err != nil {
log.Printf("%s Thumbnail failed: %s\n", this.remoteIP(r), err.Error())
w.Header().Set(`Location`, fmt.Sprintf(`/nothumb_%d.png`, opts.Height))
w.WriteHeader(302)
2017-11-18 00:11:39 +00:00
}
}
func (this *Server) handleThumbInternal(w http.ResponseWriter, t thumbnail.Thumbnailer, fileId string) error {
2017-11-18 00:11:39 +00:00
// Load metadata
m, err := this.Metadata(fileId)
if err != nil {
return err
}
filePath := filepath.Join(this.opts.DataDirectory, m.FileHash)
thumb, err := t.RenderFileAs(filePath, m.MimeType)
2017-11-18 00:11:39 +00:00
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
}