oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "context"
5 "net/http"
6 "strconv"
7 "time"
8
9 "amadan.net/oficina/sheets/internal/sheets/store"
10)
11
12// historyEntry is one edit, ready to render.
13type historyEntry struct {
14 ID uint64
15 Ref string // A1 notation
16 Who string
17 Old string
18 New string
19 When time.Time
20 Mine bool
21 Cleared bool // the edit emptied the cell
22}
23
24type historyView struct {
25 Sheet SheetSummary
26 Entries []historyEntry
27 MayWrite bool
28 Notice string
29 NoticeTone string `json:"-"`
30}
31
32// handleHistory shows what has been typed into a sheet.
33//
34// Spec §4.3: the log holds inputs, never derived values. So this lists
35// edits somebody made, not cells that changed — an edit to one cell
36// that recalculated four hundred appears once, which is both what the
37// storage can support and what a person actually wants to read.
38func (a *App) handleHistory(w http.ResponseWriter, r *http.Request) {
39 s, ok := a.sheetFromURL(w, r)
40 if !ok {
41 return
42 }
43 viewer, ok := a.actor(r)
44 if !ok {
45 a.notFound(w, r)
46 return
47 }
48
49 h, err := a.openTabFor(s)
50 if err != nil {
51 a.fail(w, r, err)
52 return
53 }
54 defer h.Release()
55
56 records, err := store.History(a.db, a.sealer, store.HistoryQuery{TabID: s.TabID})
57 if err != nil {
58 a.fail(w, r, err)
59 return
60 }
61
62 idx := newPosIndex(h)
63 names := a.memberNames()
64 entries := make([]historyEntry, 0, len(records))
65 for _, rec := range records {
66 row, okR := idx.rowPos[rec.RowID]
67 col, okC := idx.colPos[rec.ColID]
68 if !okR || !okC {
69 continue // an event pointing at a row or column that is gone
70 }
71 entries = append(entries, historyEntry{
72 ID: rec.ID,
73 Ref: colLabel(col) + strconv.Itoa(row+1),
74 Who: names[rec.ActorID],
75 Old: rec.OldRaw,
76 New: rec.NewRaw,
77 When: time.Unix(rec.CreatedAt, 0).UTC(),
78 Mine: rec.ActorID == viewer.ID,
79 Cleared: rec.NewRaw == "",
80 })
81 }
82
83 a.render(w, r, "history", onSheet(s, "Version history"), http.StatusOK, historyView{
84 Sheet: s, Entries: entries,
85 MayWrite: a.mayWrite(s.ID, viewer),
86 Notice: historyNotice(r.URL.Query().Get("notice")),
87 NoticeTone: noticeTone(r.URL.Query().Get("notice")),
88 })
89}
90
91func historyNotice(code string) string {
92 switch code {
93 case "restored":
94 return "Put back. That is itself an edit, so you can undo it too."
95 case "undone":
96 return "Undone. Your last edit has been put back to what it was."
97 case "nothing":
98 return "You have not edited anything on this sheet yet."
99 case "gone":
100 return "That edit is no longer in the history."
101 default:
102 return ""
103 }
104}
105
106// memberNames maps actor ids to addresses for display.
107//
108// One query rather than one per row: a page of two hundred edits by
109// three people would otherwise be two hundred lookups.
110func (a *App) memberNames() map[uint64]string {
111 out := map[uint64]string{}
112 if a.db == nil {
113 return out
114 }
115 var members []Member
116 if err := a.db.Find(&members).Error; err != nil {
117 return out
118 }
119 refs := a.homeOnlyRefs(context.Background())
120 for _, m := range members {
121 if subject, ok := refs[m.ID]; ok && m.Address == "" {
122 out[m.ID] = homeOnlyLabel(subject)
123 continue
124 }
125 out[m.ID] = m.Label()
126 }
127 return out
128}
129
130// handleRestore puts one cell back to what it held before an edit.
131//
132// Spec ruling 17's named baseline: view history and restore a cell or a
133// range. Restoring is a FRESH last-write-wins write, not a rewind — so
134// it appears in history as an edit by whoever did it, fans out to every
135// open tab like any other, and is itself undoable. A rewind that
136// rewrote the past would make the log disagree with the sheet.
137func (a *App) handleRestore(w http.ResponseWriter, r *http.Request) {
138 s, ok := a.sheetFromURL(w, r)
139 if !ok {
140 return
141 }
142 viewer, ok := a.actor(r)
143 if !ok {
144 a.notFound(w, r)
145 return
146 }
147 if !a.mayWrite(s.ID, viewer) {
148 a.notFound(w, r)
149 return
150 }
151 eventID, err := strconv.ParseUint(r.FormValue("event"), 10, 64)
152 if err != nil || eventID == 0 {
153 a.notFound(w, r)
154 return
155 }
156 rec, found := store.EventByID(a.db, a.sealer, s.TabID, eventID)
157 if !found {
158 a.historyRedirect(w, r, s, "gone")
159 return
160 }
161 if err := a.applyRaw(r.Context(), s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil {
162 if !a.guardRefused(w, r, err) {
163 a.fail(w, r, err)
164 }
165 return
166 }
167 a.historyRedirect(w, r, s, "restored")
168}
169
170// undoScan is how far back undo will look for an edit it can read.
171//
172// It asked for one row and took what came back, which is wrong because
173// History skips an event it cannot unseal: one unreadable newest edit
174// turned into "nothing to undo" while readable older ones sat behind
175// it. Asking for a window and taking the first that survives is the
176// fix, and the window is bounded rather than open because a tab full of
177// undecryptable events would otherwise turn one undo into a scan of the
178// whole log, unsealing every row on the way.
179//
180// Twenty is a judgement, not a measurement: far enough that the case
181// this exists for — an event or two under a key we no longer hold — is
182// covered, short enough that the pathological tab costs twenty AEAD
183// opens and stops. Past that, undo reports nothing to undo, which by
184// then is the honest answer.
185const undoScan = 20
186
187// handleUndo reverts the viewer's own most recent readable edit.
188//
189// Own-edits-only, cell-level (spec §7). Multi-user undo has no correct
190// answer; this one is predictable and explainable, which is the next
191// best thing. Applied as a fresh write, so if somebody has since
192// written over that cell your undo takes it back — and is itself
193// undoable.
194func (a *App) handleUndo(w http.ResponseWriter, r *http.Request) {
195 s, ok := a.sheetFromURL(w, r)
196 if !ok {
197 return
198 }
199 viewer, ok := a.actor(r)
200 if !ok {
201 a.notFound(w, r)
202 return
203 }
204 if !a.mayWrite(s.ID, viewer) {
205 a.notFound(w, r)
206 return
207 }
208 records, err := store.History(a.db, a.sealer, store.HistoryQuery{
209 TabID: s.TabID, ActorID: viewer.ID, Limit: undoScan,
210 })
211 if err != nil {
212 a.fail(w, r, err)
213 return
214 }
215 if len(records) == 0 {
216 a.historyRedirect(w, r, s, "nothing")
217 return
218 }
219 rec := records[0]
220 if err := a.applyRaw(r.Context(), s, rec.RowID, rec.ColID, rec.OldRaw, viewer); err != nil {
221 if !a.guardRefused(w, r, err) {
222 a.fail(w, r, err)
223 }
224 return
225 }
226 a.historyRedirect(w, r, s, "undone")
227}
228
229// applyRaw writes a cell and fans the result out, exactly as an
230// ordinary edit does.
231//
232// Shared by restore and undo so neither can drift from the write path
233// the grid uses: same store call, same hub publish, same version.
234func (a *App) applyRaw(ctx context.Context, s SheetSummary, rowID, colID uint64, raw string, by Member) error {
235 h, err := a.openTabFor(s)
236 if err != nil {
237 return err
238 }
239 defer h.Release()
240
241 rep, err := h.Guarded(a.writeGuard(ctx, s.ID, by, SheetEditor)).SetReport(rowID, colID, raw, by.ID)
242 if err != nil {
243 return err
244 }
245 a.publishReport(s, h, rep)
246 return nil
247}
248
249func (a *App) historyRedirect(w http.ResponseWriter, r *http.Request, s SheetSummary, notice string) {
250 if nativeNotice(w, r, notice) {
251 return
252 }
253 http.Redirect(w, r, "/sheets/"+strconv.FormatUint(s.ID, 10)+"/history?notice="+notice,
254 http.StatusSeeOther)
255}
256