-
Notifications
You must be signed in to change notification settings - Fork 0
/
publicServer.go
231 lines (184 loc) · 5.59 KB
/
publicServer.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
package main
import (
"encoding/json"
"errors"
"image"
"image/jpeg"
"net/http"
"path"
"strconv"
"github.com/disintegration/imaging"
"github.com/golang/glog"
"github.com/gorilla/mux"
"github.com/rokeller/photo-search/srv/web/models"
)
type publicServerContext struct {
*serverContext
}
func NewPublicServer(ctx *serverContext) *http.Server {
mux := mux.NewRouter()
srv := &http.Server{
Addr: ":8080",
Handler: mux,
}
publicCtx := publicServerContext{
serverContext: ctx,
}
wellKnownRouter := mux.PathPrefix("/.well-known").Subrouter()
publicCtx.addWellKnown(wellKnownRouter)
apiRouter := mux.PathPrefix("/api/v1").Subrouter()
authMiddleware := NewAuthenticationMiddleware(
ctx.oauthSettings.Audience,
ctx.oauthSettings.Issuer,
)
// The APIs require authentication.
apiRouter.Use(authMiddleware.Middleware)
publicCtx.addV1API(apiRouter)
spa := spaHandler{staticPath: "dist", indexPath: "index.html"}
mux.PathPrefix("/").Handler(spa)
return srv
}
func (c publicServerContext) addWellKnown(mux *mux.Router) {
mux.HandleFunc("/flrx39.net/photoSearch/auth/config", c.handleWellKnownAuthConfig).
Methods("GET")
}
func (c publicServerContext) handleWellKnownAuthConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Add("content-type", "application/json; charset=utf-8")
w.WriteHeader(200)
json.NewEncoder(w).Encode(c.serverContext.oauthSettings)
}
func (c publicServerContext) addV1API(mux *mux.Router) {
mux.HandleFunc("/photos/search", c.handleV1SearchPhotos).
Methods("POST").
HeadersRegexp("Content-Type", "(text|application)/json")
mux.HandleFunc("/photos/recommend", c.handleV1RecommendPhotos).
Methods("POST").
HeadersRegexp("Content-Type", "(text|application)/json")
mux.HandleFunc("/photos/{id}", c.handleV1PhotosGetById).
Methods("GET")
mux.HandleFunc("/photos/{id}/{width}", c.handleV1PhotosWithWidthGetById).
Methods("GET")
}
func (c publicServerContext) handleV1SearchPhotos(w http.ResponseWriter, r *http.Request) {
req := &models.SearchPhotosRequest{}
json.NewDecoder(r.Body).Decode(req)
w.Header().Add("content-type", "application/json; charset=utf-8")
limit := uint(10)
if nil != req.Limit {
limit = *req.Limit
}
res, err := c.search(req.Query, limit, req.Offset, req.Filter)
if nil != err {
c.respondForError(err, w)
} else {
w.WriteHeader(200)
json.NewEncoder(w).Encode(res)
}
}
func (c publicServerContext) handleV1RecommendPhotos(w http.ResponseWriter, r *http.Request) {
req := &models.RecommendPhotosRequest{}
json.NewDecoder(r.Body).Decode(req)
w.Header().Add("content-type", "application/json; charset=utf-8")
limit := uint(10)
if nil != req.Limit {
limit = *req.Limit
}
res, err := c.recommend(req.Id, limit, req.Offset, req.Filter)
if nil != err {
c.respondForError(err, w)
} else {
w.WriteHeader(200)
json.NewEncoder(w).Encode(res)
}
}
func (c publicServerContext) handleV1PhotosGetById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
payload, err := c.getPayloadById(id)
if nil != err {
c.respondForError(err, w)
} else {
relPath := getPathFromPayload(payload)
absPath := path.Join(c.photosRootDir, *relPath)
w.Header().Add("cache-control", "max-age=31556736, immutable")
http.ServeFile(w, r, absPath)
}
}
func (c publicServerContext) handleV1PhotosWithWidthGetById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
widthStr := vars["width"]
width, err := strconv.Atoi(widthStr)
if nil != err {
w.WriteHeader(400)
}
payload, err := c.getPayloadById(id)
if nil != err {
c.respondForError(err, w)
return
}
relPath := getPathFromPayload(payload)
absPath := path.Join(c.photosRootDir, *relPath)
image, err := resizeImage(absPath, width)
if nil != err {
w.WriteHeader(500)
return
}
orientation := getOrientationFromPayload(payload)
if nil != orientation {
// Apply the reverse transformation of the orientation in the EXIF tags
// to put the photo into the right shape again.
image = realignImage(image, *orientation)
} else {
glog.V(1).Infof("Missing 'Orientation' tag in '%s'.", *relPath)
}
w.Header().Add("cache-control", "max-age=31556736, immutable")
w.Header().Add("content-type", "image/jpeg")
jpeg.Encode(w, image, &jpeg.Options{Quality: 66})
}
func (c publicServerContext) respondForError(err error, w http.ResponseWriter) {
var pserr *photoSearchError
if errors.As(err, &pserr) {
if pserr.recoverable {
w.WriteHeader(503)
} else {
w.WriteHeader(500)
}
pserr.WriteJson(w)
} else {
w.WriteHeader(500)
json.NewEncoder(w).Encode(err)
}
}
func resizeImage(path string, newWidth int) (image.Image, error) {
image, err := imaging.Open(path)
if err != nil {
glog.Errorf("Failed to open photo file '%s': %v", path, err)
return nil, err
}
resized := imaging.Resize(image, newWidth, 0, imaging.Lanczos)
return resized, nil
}
func realignImage(img image.Image, orientation int64) image.Image {
// See https://exiftool.org/TagNames/EXIF.html
switch orientation {
case 1: // Normal, do nothing
return img
case 2: // Mirror horizontal
return imaging.FlipH(img)
case 3: // Rotate 180
return imaging.Rotate180(img)
case 4: // Mirror vertical
return imaging.FlipV(img)
case 5: // Mirror horizontal and rotate 270 degrees clockwise
return imaging.FlipH(imaging.Rotate90(img))
case 6: // Rotate 90 degrees clockwise
return imaging.Rotate270(img) // _counter_-clockwise
case 7: // Mirror horizontal and rotate 90 degrees clockwise
return imaging.FlipH(imaging.Rotate270(img))
case 8: // Rotate 270 degrees clockwise
return imaging.Rotate90(img) // _counter_-clockwise
default:
return img
}
}