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
|
package main
// The editor's API.
//
// These are the routes the block editor in the browser talks to, and they are
// JSON rather than form posts because the client is a script that already holds
// the block list. Everything here is inert in the sense "Composing without
// committing" means: it writes to draft tables on this machine and nothing goes
// anywhere. Sending is not here, and is not reachable from here.
//
// Two rules shape the whole file.
//
// The server owns the ordering. Every mutation that can move a block answers
// with the draft's entire block list, so the editor never computes a position
// and cannot drift from the database; the cost is a re-render per structural
// change, which for the handful of blocks a reply holds is nothing. Editing a
// block's text is the exception — it answers {"ok":true} and no list, because
// re-rendering a textarea under a typing cursor loses the selection.
//
// A sent draft is read-only, and that is enforced here rather than by hiding
// the controls. The browser does hide them, but a draft that has gone out is a
// record of what was sent, and editing it afterwards would make that record
// disagree with the mail people received. The refusal is 409, the same answer
// and for the same reason as sending one twice.
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"
)
// ============================================================================
// Wire types
// ============================================================================
// blockJSON is the wire shape of one block.
//
// Kept apart from draftBlock so that the editor's contract does not silently
// change whenever a column is added — the same separation blocks(1) draws.
type blockJSON struct {
ID int64 `json:"id"`
Position int `json:"position"`
Kind string `json:"kind"`
Content string `json:"content"`
Meta blockMeta `json:"meta"`
// Attribution is repeated out of Meta because the editor shows it above a
// quote as a line of prose, and it is the one piece of a draft that came
// from a From: header rather than from the account owner.
Attribution string `json:"attribution,omitempty"`
}
// draftJSON is a draft as the editor sees it.
type draftJSON struct {
Token string `json:"token"`
Subject string `json:"subject"`
Blocks []blockJSON `json:"blocks"`
// Rich says the draft will be sent as multipart/alternative rather than
// text/plain. It is derived from the blocks, so it changes as they do and
// the editor can say what will go on the wire without asking again.
Rich bool `json:"rich"`
// Sent freezes the editor. The server refuses the writes as well; this is
// so the page can stop offering them.
Sent bool `json:"sent"`
}
func blocksToJSON(blocks []draftBlock) []blockJSON {
out := make([]blockJSON, 0, len(blocks))
for _, b := range blocks {
out = append(out, blockJSON{
ID: b.ID, Position: b.Position, Kind: b.Kind,
Content: b.Content, Meta: b.Meta, Attribution: b.Meta.Attribution,
})
}
return out
}
func draftToJSON(d *draft) draftJSON {
return draftJSON{
Token: d.Token, Subject: d.Subject,
Blocks: blocksToJSON(d.Blocks), Rich: d.RichFormat(), Sent: d.Sent(),
}
}
// ============================================================================
// Helpers
// ============================================================================
// editableDraft resolves the {token} of an editing route and refuses a draft
// that has already been sent.
//
// The 409 is the point of the helper. A sent draft is the record of what went
// out, and every route below would otherwise let that record be edited into
// something nobody received. Hiding the controls in the browser is a courtesy
// to whoever is looking at the page; this is the rule.
func (s *server) editableDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) {
d, ok := s.draftOf(w, r)
if !ok {
return nil, false
}
if d.Sent() {
apiError(w, http.StatusConflict,
"this draft was sent at "+d.SentAt.Format("2006-01-02 15:04")+
" and is kept as the record of what went out. Editing it now would "+
"make that record disagree with the mail people received; reply "+
"again from the message instead.")
return nil, false
}
return d, true
}
// writeBlocks answers with the draft's whole block list, re-read from the
// database rather than patched in memory: what the editor renders is then what
// a fresh page load would show, positions included.
func (s *server) writeBlocks(w http.ResponseWriter, d *draft) {
blocks, err := loadDraftBlocks(s.db.Read, d.ID)
if err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
d.Blocks = blocks
writeJSON(w, draftToJSON(d))
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("draft api: write json: %v", err)
}
}
// apiError answers in JSON, because every caller here is a script that reads
// the message out and puts it on the page. An HTML error body would be shown
// to the person as markup.
func apiError(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
// decodeJSON reads a request body, capped: these routes are reachable by
// anything that can reach the listen address.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)).Decode(dst); err != nil {
apiError(w, http.StatusBadRequest, "bad JSON: "+err.Error())
return false
}
return true
}
// blockIDOf reads the {block} path value.
func blockIDOf(w http.ResponseWriter, r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("block"), 10, 64)
if err != nil {
apiError(w, http.StatusBadRequest, "bad block id")
return 0, false
}
return id, true
}
// ============================================================================
// Routes
// ============================================================================
// handleAPIDraftGet answers with a draft as the editor needs it.
//
// The editor fetches this rather than reading a JSON island out of the page,
// because it is mounted under messages on the index and the contact view: a
// listing of ten messages embeds ten editors, and none of them should cost
// anything until somebody opens one.
func (s *server) handleAPIDraftGet(w http.ResponseWriter, r *http.Request) {
d, ok := s.draftOf(w, r)
if !ok {
return
}
writeJSON(w, draftToJSON(d))
}
// handleAPIDraftPatch updates a draft's subject.
func (s *server) handleAPIDraftPatch(w http.ResponseWriter, r *http.Request) {
d, ok := s.editableDraft(w, r)
if !ok {
return
}
var req struct {
Subject string `json:"subject"`
}
if !decodeJSON(w, r, &req) {
return
}
if err := updateDraftSubject(s.db.Write, d.ID, req.Subject); err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
writeJSON(w, map[string]bool{"ok": true})
}
// handleAPIBlockCreate appends a block after the given position.
func (s *server) handleAPIBlockCreate(w http.ResponseWriter, r *http.Request) {
d, ok := s.editableDraft(w, r)
if !ok {
return
}
var req struct {
Kind string `json:"kind"`
// After is the position to insert behind; negative appends.
After int `json:"after"`
}
if !decodeJSON(w, r, &req) {
return
}
// Checked here as well as in addDraftBlock so an unknown kind is reported
// as the client error it is rather than surfacing as a 500.
if !validBlockKinds[req.Kind] {
apiError(w, http.StatusBadRequest, "unknown block kind "+strconv.Quote(req.Kind))
return
}
if _, err := addDraftBlock(s.db.Write, d.ID, req.Kind, req.After); err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
s.writeBlocks(w, d)
}
// handleAPIBlockPatch writes one block's content and meta.
//
// This is the one mutation that does not answer with the block list: it cannot
// reorder anything, and it is called while somebody is typing.
func (s *server) handleAPIBlockPatch(w http.ResponseWriter, r *http.Request) {
d, ok := s.editableDraft(w, r)
if !ok {
return
}
blockID, ok := blockIDOf(w, r)
if !ok {
return
}
var req struct {
Content string `json:"content"`
Meta blockMeta `json:"meta"`
}
if !decodeJSON(w, r, &req) {
return
}
// The attribution of a quote is not the editor's to rewrite. It is body
// text naming who wrote the quoted passage, it came from a From: header,
// and the draft page shows it precisely so that what is displayed and what
// will be sent cannot differ. Whatever the request says, the stored line
// is kept.
for _, b := range d.Blocks {
if b.ID == blockID {
req.Meta.Attribution = b.Meta.Attribution
req.Meta.QuoteFrom = b.Meta.QuoteFrom
req.Meta.QuoteName = b.Meta.QuoteName
break
}
}
err := updateDraftBlock(s.db.Write, d.ID, blockID, req.Content, req.Meta)
if errors.Is(err, sql.ErrNoRows) {
apiError(w, http.StatusNotFound, "no such block in this draft")
return
}
if err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
writeJSON(w, map[string]bool{"ok": true})
}
// handleAPIBlockMove moves a block to a new position.
func (s *server) handleAPIBlockMove(w http.ResponseWriter, r *http.Request) {
d, ok := s.editableDraft(w, r)
if !ok {
return
}
blockID, ok := blockIDOf(w, r)
if !ok {
return
}
var req struct {
Position int `json:"position"`
}
if !decodeJSON(w, r, &req) {
return
}
err := moveDraftBlock(s.db.Write, d.ID, blockID, req.Position)
if errors.Is(err, sql.ErrNoRows) {
apiError(w, http.StatusNotFound, "no such block in this draft")
return
}
if err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
s.writeBlocks(w, d)
}
// handleAPIBlockDelete removes a block and closes the gap it leaves.
func (s *server) handleAPIBlockDelete(w http.ResponseWriter, r *http.Request) {
d, ok := s.editableDraft(w, r)
if !ok {
return
}
blockID, ok := blockIDOf(w, r)
if !ok {
return
}
err := deleteDraftBlock(s.db.Write, d.ID, blockID)
if errors.Is(err, sql.ErrNoRows) {
apiError(w, http.StatusNotFound, "no such block in this draft")
return
}
if err != nil {
apiError(w, http.StatusInternalServerError, fmt.Sprintf("db error: %v", err))
return
}
s.writeBlocks(w, d)
}
|