forked from die-net/fotomat
/
image-handler.go
249 lines (209 loc) · 6.39 KB
/
image-handler.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Copyright 2013-2014 Aaron Hopkins. All rights reserved.
// Use of this source code is governed by the GPL v2 license
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"github.com/die-net/fotomat/imager"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strconv"
"time"
)
var (
maxOutputDimension = flag.Int("max_output_dimension", 2048, "Maximum width or height of an image response.")
maxBufferPixels = flag.Uint("max_buffer_pixels", 6500000, "Maximum number of pixels to allocate for an intermediate image buffer.")
maxProcessingDuration = flag.Duration("max_processing_duration", time.Minute, "Maximum duration we can be processing an image before assuming we crashed (0 = disable).")
localImageDirectory = flag.String("local_image_directory", "", "Enable local image serving from this path (\"\" = proxy instead).")
pool chan bool
transport http.Transport = http.Transport{Proxy: http.ProxyFromEnvironment}
client = http.Client{Transport: http.RoundTripper(&transport)}
)
func init() {
http.HandleFunc("/", imageProxyHandler)
http.HandleFunc("/albums/crop", albumsCropHandler)
}
func imageProxyHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
sendError(w, nil, http.StatusMethodNotAllowed)
return
}
path, preview, crop, width, height, ok := parsePath(r.URL.Path)
if !ok {
sendError(w, nil, 400)
return
}
var u *url.URL
if *localImageDirectory == "" {
u = &url.URL{Scheme: "http", Host: r.Host, Path: path}
} else {
u = &url.URL{Scheme: "file", Host: "localhost", Path: path}
}
fetchAndProcessImage(w, u.String(), preview, crop, width, height)
}
var matchPath = regexp.MustCompile(`^(/.*)=(p?)([sc])(\d{1,5})x(\d{1,5})$`)
func parsePath(path string) (string, bool, bool, uint, uint, bool) {
g := matchPath.FindStringSubmatch(path)
if len(g) != 6 {
return "", false, false, 0, 0, false
}
// Disallow repeated scaling parameters.
if matchPath.MatchString(g[1]) {
return "", false, false, 0, 0, false
}
width, err := strconv.Atoi(g[4])
if err != nil || width <= 0 || width > *maxOutputDimension {
return "", false, false, 0, 0, false
}
height, err := strconv.Atoi(g[5])
if err != nil || height <= 0 || height > *maxOutputDimension {
return "", false, false, 0, 0, false
}
return g[1], (g[2] == "p"), (g[3] == "c"), uint(width), uint(height), true
}
func poolInit(limit int) {
if *localImageDirectory != "" {
transport.RegisterProtocol("file", http.NewFileTransport(http.Dir(*localImageDirectory)))
}
pool = make(chan bool, limit)
for i := 0; i < limit; i++ {
pool <- true
}
}
/*
Supported geometries:
WxH# - scale down so the shorter edge fits within this bounding box, crop to new aspect ratio
WxH or WxH> - scale down so the longer edge fits within this bounding box, no crop
*/
var matchGeometry = regexp.MustCompile(`^(\d{1,5})x(\d{1,5})([>#])?$`)
func albumsCropHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "HEAD" {
sendError(w, nil, http.StatusMethodNotAllowed)
return
}
if err := r.ParseForm(); err != nil {
sendError(w, err, 0)
return
}
crop, width, height, ok := parseGeometry(r.FormValue("geometry"))
if !ok {
sendError(w, nil, 400)
return
}
fetchAndProcessImage(w, r.FormValue("image_url"), false, crop, width, height)
}
func fetchAndProcessImage(w http.ResponseWriter, url string, preview, crop bool, width, height uint) {
aborted := w.(http.CloseNotifier).CloseNotify()
orig, err, status := fetchUrl(url)
if err != nil || status != http.StatusOK {
sendError(w, err, status)
return
}
// Wait for an image thread to be available.
<-pool
// Has client closed connection while we were waiting?
select {
case <-aborted:
pool <- true // Free up image thread ASAP.
sendError(w, nil, http.StatusRequestTimeout)
return
default:
}
thumb, err := processImage(url, orig, preview, crop, width, height)
orig = nil // Free up image memory ASAP.
pool <- true // Free up image thread ASAP.
if err != nil {
thumb = nil // Free up image memory ASAP.
sendError(w, err, 0)
return
}
w.Write(thumb)
thumb = nil // Free up image memory ASAP.
}
func parseGeometry(geometry string) (bool, uint, uint, bool) {
g := matchGeometry.FindStringSubmatch(geometry)
if len(g) != 4 {
return false, 0, 0, false
}
width, err := strconv.Atoi(g[1])
if err != nil || width <= 0 || width > *maxOutputDimension {
return false, 0, 0, false
}
height, err := strconv.Atoi(g[2])
if err != nil || height <= 0 || height > *maxOutputDimension {
return false, 0, 0, false
}
crop := (g[3] == "#")
return crop, uint(width), uint(height), true
}
func fetchUrl(url string) ([]byte, error, int) {
resp, err := client.Get(url)
if err != nil {
return nil, err, 0
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err, 0
}
switch resp.StatusCode {
case http.StatusOK,
http.StatusNoContent,
http.StatusBadRequest,
http.StatusUnauthorized,
http.StatusForbidden,
http.StatusNotFound,
http.StatusRequestTimeout,
http.StatusGone:
return body, nil, resp.StatusCode
default:
err := fmt.Errorf("Proxy received %d %s", resp.StatusCode, http.StatusText(resp.StatusCode))
return nil, err, http.StatusBadGateway
}
}
func processImage(url string, orig []byte, preview, crop bool, width, height uint) ([]byte, error) {
if *maxProcessingDuration > 0 {
timer := time.AfterFunc(*maxProcessingDuration, func() {
panic(fmt.Sprintf("Processing %v longer than %v", url, *maxProcessingDuration))
})
defer timer.Stop()
}
img, err := imager.New(orig, *maxBufferPixels)
if err != nil {
return nil, err
}
defer img.Close()
// Preview images are tiny, blurry JPEGs.
if preview {
img.Sharpen = false
img.BlurFactor = 1.0
img.OutputFormat = "JPEG"
img.JpegQuality = 40
}
var thumb []byte
if crop {
thumb, err = img.Crop(width, height)
} else {
thumb, err = img.Thumbnail(width, height, true)
}
return thumb, err
}
func sendError(w http.ResponseWriter, err error, status int) {
if status == 0 {
switch err {
case imager.UnknownFormat:
status = http.StatusUnsupportedMediaType
case imager.TooBig:
status = http.StatusRequestEntityTooLarge
default:
status = http.StatusInternalServerError
}
}
if err == nil {
err = fmt.Errorf(http.StatusText(status))
}
http.Error(w, err.Error(), status)
}