Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
220 lines (192 loc) · 7.02 KB
/
Copy pathmain.go
File metadata and controls
220 lines (192 loc) · 7.02 KB
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
package main
import (
"embed"
"encoding/json"
"flag"
"io/fs"
"log"
"mime"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
)
//go:embed static
var staticFiles embed.FS
func main() {
configPath := flag.String("config", "config.json", "path to the config file")
flag.Parse()
cfg, err := LoadConfig(*configPath)
if err != nil {
log.Fatalf("randomimageviewer: %v", err)
}
renderer, err := NewRenderer(cfg.CacheDir, cfg.CacheSizeMB)
if err != nil {
log.Fatalf("randomimageviewer: %v", err)
}
library := NewLibrary(cfg.Folder, time.Duration(cfg.RescanSeconds)*time.Second)
srv := &server{cfg: cfg, library: library, renderer: renderer}
static, err := fs.Sub(staticFiles, "static")
if err != nil {
log.Fatalf("randomimageviewer: %v", err)
}
// Go's MIME table has no entry for .webmanifest, so without this the
// manifest is served as text/plain and Chrome declines to install the app.
if err := mime.AddExtensionType(".webmanifest", "application/manifest+json"); err != nil {
log.Printf("register manifest MIME type: %v", err)
}
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(static)))
mux.HandleFunc("/api/images", srv.handleImages)
mux.HandleFunc("/api/image/", srv.handleImage)
// An initial scan up front, so a misconfigured folder is reported at
// startup rather than on the first request from a phone across the room.
snap := library.Snapshot()
if snap.Missing {
log.Printf("warning: cannot read folder %s — the app will show an error until it becomes readable", cfg.Folder)
} else {
log.Printf("serving %d image(s) from %s", len(snap.Images), cfg.Folder)
}
log.Printf("cache: %s (limit %d MB)", cfg.CacheDir, cfg.CacheSizeMB)
httpServer := &http.Server{
Addr: cfg.Listen,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
if cfg.TLS.Cert != "" {
log.Printf("listening on https://%s", displayAddr(cfg.Listen))
err = httpServer.ListenAndServeTLS(cfg.TLS.Cert, cfg.TLS.Key)
} else {
log.Printf("listening on http://%s", displayAddr(cfg.Listen))
// Worth saying once rather than leaving it to be discovered: over plain
// HTTP by IP, the browser withholds Wake Lock and Fullscreen because
// the page is not a secure context. localhost is exempt, which is why
// this is not printed for a bind that nothing but loopback can reach —
// there the note would be advising a fix for a problem the deployment
// does not have.
if !loopbackOnly(cfg.Listen) {
log.Printf("note: reached by LAN IP over http, the screen will sleep and fullscreen is unavailable — set tls.cert/tls.key to fix")
}
err = httpServer.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
log.Fatalf("randomimageviewer: %v", err)
}
}
func displayAddr(listen string) string {
if strings.HasPrefix(listen, ":") {
return "localhost" + listen
}
return listen
}
// Whether nothing but loopback can reach this bind address — which is exactly
// when a page served over plain HTTP is still a secure context, and Wake Lock
// and Fullscreen work without a certificate.
//
// Everything uncertain answers false. A bare port listens on every interface, a
// hostname other than localhost can resolve anywhere, and an address that will
// not parse is about to fail at Listen anyway. A redundant note costs a line of
// log; a missing one sends someone hunting for why the screen keeps sleeping.
func loopbackOnly(listen string) bool {
host, _, err := net.SplitHostPort(listen)
if err != nil {
host = listen
}
if host == "localhost" {
return true
}
if ip := net.ParseIP(host); ip != nil {
return ip.IsLoopback()
}
return false
}
type server struct {
cfg Config
library *Library
renderer *Renderer
}
// handleImages returns the manifest. The client picks the random image from it,
// exactly as ContentView does — selection policy stays in one place on the
// client rather than being split across the wire.
func (s *server) handleImages(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
snap := s.library.Snapshot()
if r.URL.Query().Get("refresh") == "1" {
snap = s.library.Refresh()
}
// The listing is live state; a cached copy would defeat the whole point of
// re-fetching it when the page becomes visible again.
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(snap); err != nil {
log.Printf("encode manifest: %v", err)
}
}
// handleImage serves one derivative: /api/image/<id>?w=<cap>
func (s *server) handleImage(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
id := strings.TrimPrefix(r.URL.Path, "/api/image/")
// The id is a hash the server minted and still holds in its listing. It is
// never joined onto a path, so there is nothing here to traverse with — a
// value that is not in the current listing simply does not resolve.
if id == "" || strings.ContainsAny(id, "/\\.") {
http.NotFound(w, r)
return
}
img, ok := s.library.Lookup(id)
if !ok {
http.NotFound(w, r)
return
}
requested, _ := strconv.ParseFloat(r.URL.Query().Get("w"), 64)
capPx := ClampCap(requested)
derivative, err := s.renderer.Render(img, capPx)
if err != nil {
// A file that lists but will not decode is a real possibility — a
// truncated download, a .png that is actually something else. Report it
// and let the client show its failure state.
log.Printf("render %s at %d: %v", img.Name, capPx, err)
http.Error(w, "unable to render image", http.StatusUnprocessableEntity)
return
}
file, err := os.Open(derivative.Path)
if err != nil {
// The derivative was pruned between rendering and serving.
log.Printf("open derivative for %s: %v", img.Name, err)
http.Error(w, "unable to read image", http.StatusInternalServerError)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil {
http.Error(w, "unable to read image", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", derivative.ContentType)
// The cache key covers path, mtime, size and cap, so it identifies these
// exact bytes — which makes it an exact ETag. The URL cannot be marked
// immutable, because editing a file in place keeps the same URL; a short
// max-age plus revalidation against this ETag is the honest combination.
w.Header().Set("ETag", `"`+s.renderer.key(img, capPx)+`"`)
w.Header().Set("Cache-Control", "private, max-age=300")
w.Header().Set("X-Pixel-Width", strconv.Itoa(derivative.Width))
w.Header().Set("X-Pixel-Height", strconv.Itoa(derivative.Height))
// Tells the client there is no sharper version to fetch, so it can skip the
// second load stage instead of re-requesting identical pixels.
w.Header().Set("X-Full-Resolution", boolHeader(derivative.FullResolution))
http.ServeContent(w, r, img.Name, info.ModTime(), file)
}
func boolHeader(b bool) string {
if b {
return "1"
}
return "0"
}