This repository has been archived by the owner on Feb 9, 2021. It is now read-only.
/
server.go
426 lines (364 loc) · 9.43 KB
/
server.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package server
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"math/big"
"net/http"
"os"
"path"
"strconv"
"github.com/agorf/thyme-backend/thumb"
"github.com/gorilla/handlers"
_ "github.com/mattn/go-sqlite3"
)
const (
listenAddr = "127.0.0.1:9292"
bigThumbSize = 1000
)
var (
db *sql.DB
getSetStmt *sql.Stmt
getSetsStmt *sql.Stmt
getPhotoStmt *sql.Stmt
getPhotosStmt *sql.Stmt
)
type Set struct {
Id int
Name string
PhotosCount int
TakenAt sql.NullString
ThumbPhotoId int
ThumbPhotoPath string
}
type Photo struct {
Aperture sql.NullFloat64
Camera sql.NullString
ExposureComp sql.NullInt64
ExposureTime sql.NullFloat64
Flash sql.NullString
FocalLength sql.NullFloat64
FocalLength35 sql.NullInt64
Height int64
ISO sql.NullInt64
Id int
Lat sql.NullFloat64
Lens sql.NullString
Lng sql.NullFloat64
NextPhotoId sql.NullInt64
Path string
PrevPhotoId sql.NullInt64
SetId int
Size int
TakenAt sql.NullString
Width int64
}
// used by scanSet and scanPhoto to accept row(s)
type rowScanner interface {
Scan(dest ...interface{}) error
}
func urlPath(photoPath, suffix string) string {
return path.Join("", "thumbs", thumb.Basename(photoPath, suffix))
}
func (s *Set) ThumbURL() string {
return urlPath(s.ThumbPhotoPath, "small")
}
func (s *Set) MarshalJSON() ([]byte, error) { // implements Marshaler
setMap := map[string]interface{}{
"id": s.Id,
"name": s.Name,
"photos_count": s.PhotosCount,
"thumb_photo_id": s.ThumbPhotoId,
"thumb_url": s.ThumbURL(),
}
setMap["taken_at"], _ = s.TakenAt.Value()
return json.Marshal(setMap)
}
func (p *Photo) AspectRatio() [2]int64 {
gcd := new(big.Int).GCD(nil, nil, big.NewInt(p.Width), big.NewInt(p.Height)).Int64()
return [2]int64{p.Width / gcd, p.Height / gcd}
}
func (p *Photo) BigThumbHeight() int64 {
if p.Orientation() == "portrait" {
if p.Height < bigThumbSize {
return p.Height
}
return bigThumbSize
}
aspectRatio := p.AspectRatio()
return int64(math.Floor((float64(aspectRatio[1])/float64(aspectRatio[0]))*float64(p.BigThumbWidth()) + .5))
}
func (p *Photo) BigThumbWidth() int64 {
if p.Orientation() == "portrait" {
aspectRatio := p.AspectRatio()
return int64(math.Floor((float64(aspectRatio[0])/float64(aspectRatio[1]))*float64(p.BigThumbHeight()) + .5))
}
if p.Width < bigThumbSize {
return p.Width
}
return bigThumbSize
}
func (p *Photo) Filename() string {
return path.Base(p.Path)
}
func (p *Photo) Orientation() string {
if p.Height > p.Width {
return "portrait"
}
return "landscape"
}
func (p *Photo) ThumbURL(suffix string) string {
return urlPath(p.Path, suffix)
}
func (p *Photo) MarshalJSON() ([]byte, error) { // implements Marshaler
photoMap := map[string]interface{}{
"aspect_ratio": p.AspectRatio(),
"big_thumb_height": p.BigThumbHeight(),
"big_thumb_url": p.ThumbURL("big"),
"big_thumb_width": p.BigThumbWidth(),
"filename": p.Filename(),
"height": p.Height,
"id": p.Id,
"orientation": p.Orientation(),
"path": p.Path,
"set_id": p.SetId,
"size": p.Size,
"small_thumb_url": p.ThumbURL("small"),
"width": p.Width,
}
photoMap["aperture"], _ = p.Aperture.Value()
photoMap["camera"], _ = p.Camera.Value()
photoMap["exposure_comp"], _ = p.ExposureComp.Value()
photoMap["exposure_time"], _ = p.ExposureTime.Value()
photoMap["flash"], _ = p.Flash.Value()
photoMap["focal_length"], _ = p.FocalLength.Value()
photoMap["focal_length_35"], _ = p.FocalLength35.Value()
photoMap["iso"], _ = p.ISO.Value()
photoMap["lat"], _ = p.Lat.Value()
photoMap["lens"], _ = p.Lens.Value()
photoMap["lng"], _ = p.Lng.Value()
photoMap["next_photo_id"], _ = p.NextPhotoId.Value()
photoMap["prev_photo_id"], _ = p.PrevPhotoId.Value()
photoMap["taken_at"], _ = p.TakenAt.Value()
return json.Marshal(photoMap)
}
func badRequest(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, http.StatusBadRequest, "Bad Request")
}
func internalServerError(w http.ResponseWriter, r *http.Request, err error) {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, http.StatusInternalServerError, "Internal Server Error")
log.Print(err)
}
func requireParam(param string, w http.ResponseWriter, r *http.Request) error {
if len(r.URL.Query()[param]) == 0 {
badRequest(w, r)
return errors.New(fmt.Sprintf("missing %s parameter", param))
}
return nil
}
func scanSet(row rowScanner, set *Set) error {
return row.Scan(
&set.Id,
&set.Name,
&set.PhotosCount,
&set.TakenAt,
&set.ThumbPhotoId,
&set.ThumbPhotoPath,
)
}
func getSetById(setId int) (set *Set, err error) {
set = &Set{}
row := getSetStmt.QueryRow(setId)
err = scanSet(row, set)
return
}
func getSets() (sets []*Set, err error) {
rows, err := getSetsStmt.Query()
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
set := Set{}
if err = scanSet(rows, &set); err != nil {
return
}
sets = append(sets, &set)
}
err = rows.Err()
return
}
func scanPhoto(row rowScanner, photo *Photo) error {
return row.Scan(
&photo.Aperture,
&photo.Camera,
&photo.ExposureComp,
&photo.ExposureTime,
&photo.Flash,
&photo.FocalLength,
&photo.FocalLength35,
&photo.Height,
&photo.Id,
&photo.ISO,
&photo.Lat,
&photo.Lens,
&photo.Lng,
&photo.NextPhotoId,
&photo.Path,
&photo.PrevPhotoId,
&photo.SetId,
&photo.Size,
&photo.TakenAt,
&photo.Width,
)
}
func getPhotoById(photoId int) (photo *Photo, err error) {
photo = &Photo{}
row := getPhotoStmt.QueryRow(photoId)
err = scanPhoto(row, photo)
return
}
func getPhotosBySetId(setId int) (photos []*Photo, err error) {
rows, err := getPhotosStmt.Query(setId)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
photo := Photo{}
if err = scanPhoto(rows, &photo); err != nil {
return
}
photos = append(photos, &photo)
}
err = rows.Err()
return
}
func getSetHandler(w http.ResponseWriter, r *http.Request) {
if requireParam("id", w, r) != nil {
return
}
setId, err := strconv.Atoi(r.URL.Query()["id"][0])
if err != nil {
log.Fatal(err)
}
set, err := getSetById(setId)
if err == sql.ErrNoRows { // set does not exist
http.NotFound(w, r)
return
}
if err != nil {
internalServerError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(set)
}
func getSetsHandler(w http.ResponseWriter, r *http.Request) {
sets, err := getSets()
if err != nil {
internalServerError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(sets)
}
func getPhotoHandler(w http.ResponseWriter, r *http.Request) {
if requireParam("id", w, r) != nil {
return
}
photoId, err := strconv.Atoi(r.URL.Query()["id"][0])
if err != nil {
log.Fatal(err)
}
photo, err := getPhotoById(photoId)
if err == sql.ErrNoRows { // photo does not exist
http.NotFound(w, r)
return
}
if err != nil {
internalServerError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(photo)
}
func getPhotosHandler(w http.ResponseWriter, r *http.Request) {
if requireParam("set_id", w, r) != nil {
return
}
setId, err := strconv.Atoi(r.URL.Query()["set_id"][0])
if err != nil {
log.Fatal(err)
}
photos, err := getPhotosBySetId(setId)
if err != nil {
internalServerError(w, r, err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(photos)
}
func setupDatabase() {
var err error
dbPath := path.Join(os.Getenv("HOME"), ".thyme.db")
db, err = sql.Open("sqlite3", dbPath) // := here shadows global db var
if err != nil {
log.Fatal(err)
}
setAttrs := `sets.id, name, photos_count, sets.taken_at, thumb_photo_id,
photos.path`
getSetStmt, err = db.Prepare(fmt.Sprintf(`
SELECT %s FROM sets
JOIN photos ON sets.thumb_photo_id = photos.id
WHERE sets.id = ?
`, setAttrs))
if err != nil {
log.Fatal(err)
}
getSetsStmt, err = db.Prepare(fmt.Sprintf(`
SELECT %s FROM sets
JOIN photos ON sets.thumb_photo_id = photos.id
ORDER BY sets.taken_at DESC
`, setAttrs))
if err != nil {
log.Fatal(err)
}
photoAttrs := `aperture, camera, exposure_comp, exposure_time, flash,
focal_length, focal_length_35, height, id, iso, lat, lens, lng,
next_photo_id, path, prev_photo_id, set_id, size, taken_at, width`
getPhotoStmt, err = db.Prepare(fmt.Sprintf(`
SELECT %s FROM photos WHERE id = ?
`, photoAttrs))
if err != nil {
log.Fatal(err)
}
getPhotosStmt, err = db.Prepare(fmt.Sprintf(`
SELECT %s FROM photos WHERE set_id = ? ORDER BY taken_at ASC
`, photoAttrs))
if err != nil {
log.Fatal(err)
}
}
func Run(thymePath string) {
setupDatabase()
defer db.Close()
defer getSetStmt.Close()
defer getSetsStmt.Close()
defer getPhotoStmt.Close()
defer getPhotosStmt.Close()
rootPath := path.Join(thymePath, "public")
http.Handle("/", http.FileServer(http.Dir(rootPath))) // static
http.HandleFunc("/set", getSetHandler)
http.HandleFunc("/sets", getSetsHandler)
http.HandleFunc("/photo", getPhotoHandler)
http.HandleFunc("/photos", getPhotosHandler)
fmt.Printf("Listening on http://%s serving path %q\n", listenAddr, rootPath)
fmt.Println("Press Ctrl-C to exit")
log.Fatal(http.ListenAndServe(listenAddr, handlers.LoggingHandler(os.Stdout, http.DefaultServeMux)))
}