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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
|
package main
import (
"database/sql"
"embed"
"encoding/json"
"errors"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"strings"
"time"
)
//go:embed static
var staticFS embed.FS
// server holds the shared state for the HTTP handlers.
//
// There is no authentication and no CSRF protection, and that is a deliberate
// consequence of binding to localhost only: this is a single-user tool running
// on the author's own machine. Exposing it on a public interface would require
// both, and runServe refuses to do so accidentally.
type server struct {
db *sql.DB
css string // page stylesheet with chroma classes appended
}
// runServe starts the editor/preview server.
func runServe(args []string) error {
fs := newFlagSet("serve")
dbPath := fs.String("db", "", "path to the SQLite database (required, created if missing)")
addr := fs.String("addr", "127.0.0.1:8791", "listen address")
if err := fs.Parse(args); err != nil {
return err
}
if *dbPath == "" {
return fmt.Errorf("-db is required")
}
db, err := openDB(*dbPath)
if err != nil {
return err
}
defer db.Close()
s := &server{db: db, css: pageCSS + "\n" + chromaCSS()}
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", s.handleIndex)
mux.HandleFunc("POST /posts", s.handleCreatePost)
mux.HandleFunc("GET /edit/{slug}", s.handleEdit)
mux.HandleFunc("GET /posts/{slug}", s.handlePreview)
mux.HandleFunc("GET /asset/{id}/{variant}", s.handleAsset)
mux.HandleFunc("GET /style.css", s.handleCSS)
mux.HandleFunc("PATCH /api/posts/{id}", s.handleUpdatePost)
mux.HandleFunc("DELETE /api/posts/{id}", s.handleDeletePost)
mux.HandleFunc("POST /api/posts/{id}/blocks", s.handleCreateBlock)
mux.HandleFunc("POST /api/posts/{id}/upload", s.handleUpload)
mux.HandleFunc("PATCH /api/blocks/{id}", s.handleUpdateBlock)
mux.HandleFunc("POST /api/blocks/{id}/move", s.handleMoveBlock)
mux.HandleFunc("DELETE /api/blocks/{id}", s.handleDeleteBlock)
mux.Handle("GET /static/", http.FileServer(http.FS(staticFS)))
log.Printf("blocks: serving %s on http://%s", *dbPath, *addr)
srv := &http.Server{
Addr: *addr,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
return srv.ListenAndServe()
}
// ---------------------------------------------------------------------------
// Pages
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
posts, err := listPosts(s.db)
if err != nil {
s.fail(w, err)
return
}
s.render(w, "index", map[string]any{"Posts": posts})
}
func (s *server) handleEdit(w http.ResponseWriter, r *http.Request) {
post, err := postBySlug(s.db, r.PathValue("slug"))
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.fail(w, err)
return
}
blocks, err := blocksOfPost(s.db, post.ID)
if err != nil {
s.fail(w, err)
return
}
// The editor needs the blocks as data, not as rendered HTML: it owns the
// DOM and re-renders a card in place after every edit.
payload, err := json.Marshal(blocksToJSON(blocks))
if err != nil {
s.fail(w, err)
return
}
s.render(w, "edit", map[string]any{
"Post": post,
// The payload is placed in a JSON script tag rather than interpolated
// into JavaScript source, so no escaping subtleties can turn post
// content into executable code.
"BlocksJSON": template.JS(payload),
})
}
func (s *server) handlePreview(w http.ResponseWriter, r *http.Request) {
post, err := postBySlug(s.db, r.PathValue("slug"))
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.fail(w, err)
return
}
blocks, err := blocksOfPost(s.db, post.ID)
if err != nil {
s.fail(w, err)
return
}
body, usesSTL, err := renderPost(blocks, previewAssetURL)
if err != nil {
s.fail(w, err)
return
}
s.render(w, "preview", map[string]any{
"Post": post,
"Body": template.HTML(body),
"UsesSTL": usesSTL,
})
}
// previewAssetURL is the AssetURL used while authoring: blobs are served
// straight out of SQLite. A future static export supplies a different function
// (see render.go) without the renderer changing.
func previewAssetURL(a *Asset, variant string) string {
return fmt.Sprintf("/asset/%d/%s", a.ID, variant)
}
// handleAsset serves a stored blob.
//
// The content hash is used as a strong ETag, and the response is marked
// immutable: an asset's bytes are content-addressed and can never change under
// a given id, so a browser is free to cache it forever. This is what keeps the
// preview responsive when a post carries a dozen photos.
func (s *server) handleAsset(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad asset id", http.StatusBadRequest)
return
}
asset, err := assetByID(s.db, id)
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.fail(w, err)
return
}
variant := r.PathValue("variant")
etag := `"` + asset.SHA256[:16] + "-" + variant + `"`
if match := r.Header.Get("If-None-Match"); match == etag {
w.WriteHeader(http.StatusNotModified)
return
}
rend, err := loadRendition(s.db, id, variant)
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
s.fail(w, err)
return
}
w.Header().Set("Content-Type", rend.MIME)
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("Content-Length", strconv.Itoa(len(rend.Bytes)))
w.Write(rend.Bytes)
}
func (s *server) handleCSS(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Write([]byte(s.css))
}
// ---------------------------------------------------------------------------
// API
func (s *server) handleCreatePost(w http.ResponseWriter, r *http.Request) {
title := strings.TrimSpace(r.FormValue("title"))
if title == "" {
title = "Untitled"
}
post, err := createPost(s.db, title)
if err != nil {
s.fail(w, err)
return
}
http.Redirect(w, r, "/edit/"+post.Slug, http.StatusSeeOther)
}
func (s *server) handleUpdatePost(w http.ResponseWriter, r *http.Request) {
id, ok := s.pathID(w, r)
if !ok {
return
}
var req struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Status string `json:"status"`
}
if !decodeJSON(w, r, &req) {
return
}
if req.Status != "draft" && req.Status != "published" {
req.Status = "draft"
}
post, err := updatePost(s.db, id, req.Title, req.Subtitle, req.Status)
if err != nil {
s.apiFail(w, err)
return
}
writeJSON(w, map[string]any{"slug": post.Slug, "title": post.Title})
}
func (s *server) handleDeletePost(w http.ResponseWriter, r *http.Request) {
id, ok := s.pathID(w, r)
if !ok {
return
}
if err := deletePost(s.db, id); err != nil {
s.apiFail(w, err)
return
}
writeJSON(w, map[string]any{"ok": true})
}
func (s *server) handleCreateBlock(w http.ResponseWriter, r *http.Request) {
postID, ok := s.pathID(w, r)
if !ok {
return
}
var req struct {
Kind string `json:"kind"`
After int `json:"after"`
}
if !decodeJSON(w, r, &req) {
return
}
// Checked here as well as in insertBlock so that a bad kind is reported as
// the client error it is, rather than surfacing as a 500.
if !validKinds[req.Kind] {
http.Error(w, "unknown block kind "+strconv.Quote(req.Kind), http.StatusBadRequest)
return
}
block, err := insertBlock(s.db, postID, req.After, req.Kind, "", nil, BlockMeta{})
if err != nil {
s.apiFail(w, err)
return
}
s.writeBlocks(w, block.PostID)
}
func (s *server) handleUpload(w http.ResponseWriter, r *http.Request) {
postID, ok := s.pathID(w, r)
if !ok {
return
}
after := -1
if v := r.URL.Query().Get("after"); v != "" {
if n, err := strconv.Atoi(v); err == nil {
after = n
}
}
// Keep only a modest amount in memory; the rest spills to a temp file that
// FormFile cleans up, and readUploadPart enforces the real size limit.
if err := r.ParseMultipartForm(8 << 20); err != nil {
http.Error(w, "bad multipart form: "+err.Error(), http.StatusBadRequest)
return
}
filename, data, err := readUploadPart(r, "file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, err := ingestUpload(s.db, postID, after, filename, data); err != nil {
if errors.Is(err, ErrNotFound) {
http.Error(w, "no such post", http.StatusNotFound)
return
}
// A rejected file type or an undecodable image is the user's problem
// to fix, not a server fault.
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.writeBlocks(w, postID)
}
func (s *server) handleUpdateBlock(w http.ResponseWriter, r *http.Request) {
id, ok := s.pathID(w, r)
if !ok {
return
}
var req struct {
Content string `json:"content"`
Meta BlockMeta `json:"meta"`
}
if !decodeJSON(w, r, &req) {
return
}
if err := updateBlock(s.db, id, req.Content, req.Meta); err != nil {
s.apiFail(w, err)
return
}
writeJSON(w, map[string]any{"ok": true})
}
func (s *server) handleMoveBlock(w http.ResponseWriter, r *http.Request) {
id, ok := s.pathID(w, r)
if !ok {
return
}
var req struct {
Position int `json:"position"`
}
if !decodeJSON(w, r, &req) {
return
}
if err := moveBlock(s.db, id, req.Position); err != nil {
s.apiFail(w, err)
return
}
writeJSON(w, map[string]any{"ok": true})
}
func (s *server) handleDeleteBlock(w http.ResponseWriter, r *http.Request) {
id, ok := s.pathID(w, r)
if !ok {
return
}
if err := deleteBlock(s.db, id); err != nil {
s.apiFail(w, err)
return
}
writeJSON(w, map[string]any{"ok": true})
}
// ---------------------------------------------------------------------------
// Helpers
// blockJSON is the wire shape of a block for the editor. Kept separate from the
// Block struct so the editor's contract does not silently change whenever a
// database column is added.
type blockJSON struct {
ID int64 `json:"id"`
Position int `json:"position"`
Kind string `json:"kind"`
Content string `json:"content"`
Meta BlockMeta `json:"meta"`
// Asset fields, present only for blocks that have one.
AssetURL string `json:"assetUrl,omitempty"`
AssetOrig string `json:"assetOrig,omitempty"`
AssetMesh string `json:"assetMesh,omitempty"`
AssetName string `json:"assetName,omitempty"`
AssetWidth int `json:"assetWidth,omitempty"`
}
func blocksToJSON(blocks []Block) []blockJSON {
out := make([]blockJSON, 0, len(blocks))
for i := range blocks {
b := &blocks[i]
j := blockJSON{ID: b.ID, Position: b.Position, Kind: b.Kind, Content: b.Content, Meta: b.Meta}
if b.Asset != nil {
j.AssetName = b.Asset.Filename
j.AssetOrig = previewAssetURL(b.Asset, VariantOriginal)
j.AssetWidth = b.Asset.Width
switch b.Asset.Kind {
case AssetImage:
j.AssetURL = previewAssetURL(b.Asset, VariantWebP800)
case AssetSTL:
j.AssetMesh = previewAssetURL(b.Asset, VariantMesh)
}
}
out = append(out, j)
}
return out
}
// writeBlocks responds with a post's full block list. Mutations that can change
// positions return the whole list rather than the changed row, so the editor
// never has to reconstruct the ordering itself and cannot drift out of sync
// with the database.
func (s *server) writeBlocks(w http.ResponseWriter, postID int64) {
blocks, err := blocksOfPost(s.db, postID)
if err != nil {
s.fail(w, err)
return
}
writeJSON(w, map[string]any{"blocks": blocksToJSON(blocks)})
}
func (s *server) pathID(w http.ResponseWriter, r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return 0, false
}
return id, true
}
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<20)).Decode(dst); err != nil {
http.Error(w, "bad JSON: "+err.Error(), http.StatusBadRequest)
return false
}
return true
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("write json: %v", err)
}
}
// fail reports an unexpected server-side error.
func (s *server) fail(w http.ResponseWriter, err error) {
log.Printf("error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// apiFail maps a model error to a status code: a missing row is the client
// asking for something that is not there, anything else is our fault.
func (s *server) apiFail(w http.ResponseWriter, err error) {
if errors.Is(err, ErrNotFound) {
http.Error(w, "not found", http.StatusNotFound)
return
}
log.Printf("error: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
|