| 1 | // decks.go is the deck: its identifiers, the one seam every deck read |
| 2 | // goes through, the two functions that move a document forward, and the |
| 3 | // six screens that stand on them. |
| 4 | // |
| 5 | // The split it keeps: the `decks` row is what a list, a link or a |
| 6 | // permission check needs; the Y.Doc is the content. Nothing here reads |
| 7 | // content out of a column, and nothing writes content anywhere but |
| 8 | // through an op batch the core applies. |
| 9 | package slides |
| 10 | |
| 11 | import ( |
| 12 | "context" |
| 13 | "crypto/rand" |
| 14 | "encoding/json" |
| 15 | "errors" |
| 16 | "fmt" |
| 17 | "net/http" |
| 18 | "strings" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/go-chi/chi/v5" |
| 22 | "gorm.io/gorm" |
| 23 | |
| 24 | "amadan.net/rastrillo/rastrillo" |
| 25 | "amadan.net/rastrillo/rastrillo/form" |
| 26 | |
| 27 | "amadan.net/oficina/slides/internal/slides/core" |
| 28 | "amadan.net/oficina/slides/internal/slides/deck" |
| 29 | "amadan.net/oficina/slides/internal/slides/present" |
| 30 | slidehtml "amadan.net/oficina/slides/internal/slides/render" |
| 31 | ) |
| 32 | |
| 33 | // --- identifiers --- |
| 34 | |
| 35 | // sqidAlphabet avoids the characters a person misreads or mistypes |
| 36 | // when a deck link is read aloud: no 0/O, no 1/l/I. Docs' alphabet, |
| 37 | // character for character — the two apps' URLs should look like they |
| 38 | // come from the same suite. |
| 39 | const sqidAlphabet = "23456789abcdefghjkmnpqrstuvwxyz" |
| 40 | |
| 41 | // sqidLength is how many of those characters a deck's public name has. |
| 42 | const sqidLength = 10 |
| 43 | |
| 44 | // maxSqidAttempts bounds the retry loop on a UNIQUE violation. Ten |
| 45 | // characters over 31 symbols makes a collision astronomically |
| 46 | // unlikely; this exists so one is handled rather than surprising. |
| 47 | const maxSqidAttempts = 5 |
| 48 | |
| 49 | // newSqid mints a deck's public name. len(sqidAlphabet) is 31, not a |
| 50 | // power of two, so `b % 31` is very slightly biased: 256 % 31 == 8, so |
| 51 | // the first eight symbols come out about 3% more often than the rest. |
| 52 | // Said out loud rather than papered over — at ten characters the bias |
| 53 | // narrows the keyspace by a bounded fraction nowhere near enough to |
| 54 | // make a deck link guessable, and Docs made the same trade. |
| 55 | func newSqid() (string, error) { |
| 56 | raw := make([]byte, sqidLength) |
| 57 | if _, err := rand.Read(raw); err != nil { |
| 58 | return "", fmt.Errorf("slides: generate sqid: %w", err) |
| 59 | } |
| 60 | out := make([]byte, sqidLength) |
| 61 | for i, b := range raw { |
| 62 | out[i] = sqidAlphabet[int(b)%len(sqidAlphabet)] |
| 63 | } |
| 64 | return string(out), nil |
| 65 | } |
| 66 | |
| 67 | // idAlphabet is spec §2.2's "12 lowercase base32 characters" for slide |
| 68 | // and block ids. Thirty-two symbols exactly, so masking a random byte |
| 69 | // with 31 is uniform — unlike the sqid alphabet above, this one has no |
| 70 | // bias to admit to. |
| 71 | const idAlphabet = "abcdefghijklmnopqrstuvwxyz234567" |
| 72 | |
| 73 | // idLength is spec §2.2's twelve. |
| 74 | const idLength = 12 |
| 75 | |
| 76 | // newID mints a slide or block id. The core never draws entropy of its |
| 77 | // own (core/src/ops.rs: on wasm the CRDT library's seed is a constant), |
| 78 | // so every id in a document is minted here and travels in the op. |
| 79 | func newID() (string, error) { |
| 80 | raw := make([]byte, idLength) |
| 81 | if _, err := rand.Read(raw); err != nil { |
| 82 | return "", fmt.Errorf("slides: generate id: %w", err) |
| 83 | } |
| 84 | out := make([]byte, idLength) |
| 85 | for i, b := range raw { |
| 86 | out[i] = idAlphabet[b&31] |
| 87 | } |
| 88 | return string(out), nil |
| 89 | } |
| 90 | |
| 91 | // --- vocabularies --- |
| 92 | |
| 93 | // The rungs of spec §5. Only private and team are offered by a screen |
| 94 | // in this slice: granted needs a way to name people, which does not |
| 95 | // exist yet, but a deck already sitting on that rung stays readable to |
| 96 | // the people its grants name (visibleDecks) and its label renders. |
| 97 | const ( |
| 98 | rungPrivate = "private" |
| 99 | rungGranted = "granted" |
| 100 | rungTeam = "team" |
| 101 | ) |
| 102 | |
| 103 | // settableRungs is what the share page offers (share.go's access |
| 104 | // form), in the order it offers them. Not every rung there is — see |
| 105 | // the constants above. |
| 106 | var settableRungs = []string{rungPrivate, rungTeam} |
| 107 | |
| 108 | // themeIDs are the six themes a deck can wear, in the order the picker |
| 109 | // lists them. Identifiers, not copy: each one's visible name is a |
| 110 | // catalog key (slides.theme.<id>). |
| 111 | var themeIDs = []string{"paper", "ink", "sunset", "forest", "slate", "candy"} |
| 112 | |
| 113 | // defaultTheme is what a deck gets when nobody chose — the same value |
| 114 | // the core defaults meta.theme to (core/src/schema.rs's DEFAULT_THEME), |
| 115 | // so the row and the document agree before anything is written. |
| 116 | const defaultTheme = "paper" |
| 117 | |
| 118 | // serverClientID is the Yjs client id every update this process writes |
| 119 | // carries. One document is only ever edited server-side by one writer |
| 120 | // at a time (a Handle is not safe for concurrent use, and every write |
| 121 | // goes through applyOps), so a single fixed id is correct and stable |
| 122 | // across restarts — which a random one would not be. |
| 123 | const serverClientID = 1 |
| 124 | |
| 125 | // actorFor is spec §6.2's actor string for a signed-in person. Every |
| 126 | // write records one. |
| 127 | func actorFor(u User) string { return fmt.Sprintf("person:%d", u.ID) } |
| 128 | |
| 129 | // --- ops --- |
| 130 | |
| 131 | // op is one operation in a batch (spec §7.2, core/src/ops.rs). A map |
| 132 | // rather than a Go type per op: the core owns the vocabulary and |
| 133 | // validates every field of it, so a second declaration here would be a |
| 134 | // copy to keep in step for no checking that isn't already done. What it |
| 135 | // buys is that callers — sample.go especially — read as data. |
| 136 | type op map[string]any |
| 137 | |
| 138 | // opsJSON encodes a batch for core.Handle.Ops. |
| 139 | func opsJSON(ops []op) ([]byte, error) { |
| 140 | b, err := json.Marshal(ops) |
| 141 | if err != nil { |
| 142 | return nil, fmt.Errorf("slides: encode ops: %w", err) |
| 143 | } |
| 144 | return b, nil |
| 145 | } |
| 146 | |
| 147 | // --- the visibility seam --- |
| 148 | |
| 149 | // visibleDecks is the one query every deck read goes through: decks |
| 150 | // viewer owns, decks on the team rung, and decks a grant names them on |
| 151 | // (spec §5). |
| 152 | // |
| 153 | // Not rastrillo's scope.Owned (SKILL.md §3), which is owner-only: a |
| 154 | // deck's audience here is wider than its owner by design, and a helper |
| 155 | // that silently kept filtering to creator-only would make a shared deck |
| 156 | // look deleted rather than broken. Written here so the day grants get a |
| 157 | // screen, this is the one function that changes. |
| 158 | // |
| 159 | // A deck that is not in here does not exist: handlers answer 404, never |
| 160 | // 403, so a stranger holding a sqid cannot learn whether it is real. |
| 161 | // |
| 162 | // The condition is parenthesised in the string rather than left to |
| 163 | // GORM's clause building, because every caller chains another Where |
| 164 | // onto it and an unparenthesised OR would quietly widen to "or this |
| 165 | // deck is on the team rung" — the whole seam defeated by operator |
| 166 | // precedence. |
| 167 | func (a *app) visibleDecks(ctx context.Context, viewer User) *gorm.DB { |
| 168 | return a.visibleDecksOn(a.db.G.WithContext(ctx), viewer) |
| 169 | } |
| 170 | |
| 171 | func (a *app) visibleDecksOn(db *gorm.DB, viewer User) *gorm.DB { |
| 172 | g := db.Model(&Deck{}) |
| 173 | if viewer.ID <= 0 { |
| 174 | // Never reached past RequireSession; refusing outright beats |
| 175 | // trusting every caller to have checked, because the value |
| 176 | // this guards against — 0 — would otherwise match every row a |
| 177 | // backfill had ever left ownerless. |
| 178 | return g.Where("1 = 0") |
| 179 | } |
| 180 | if !a.member(viewer) { |
| 181 | // Team mode, and the roster does not say Member (a guest, or a |
| 182 | // standing that cannot be read now): the team rung is withheld, |
| 183 | // own decks included, and only grants reach (team_access.go). |
| 184 | return g.Where("EXISTS (SELECT 1 FROM deck_grants WHERE deck_grants.deck_id = decks.id AND deck_grants.user_id = ?)", viewer.ID) |
| 185 | } |
| 186 | return g.Where( |
| 187 | "(decks.owner_id = ? OR decks.rung = ? OR EXISTS ("+ |
| 188 | "SELECT 1 FROM deck_grants WHERE deck_grants.deck_id = decks.id AND deck_grants.user_id = ?))", |
| 189 | viewer.ID, rungTeam, viewer.ID) |
| 190 | } |
| 191 | |
| 192 | // --- the document --- |
| 193 | |
| 194 | // openDeck instantiates d's Y.Doc: a fresh wasm module, the newest |
| 195 | // snapshot applied, every update after it replayed in seq order, and |
| 196 | // the view that produces. |
| 197 | // |
| 198 | // The handle is the CALLER's to close. One module per request is |
| 199 | // deliberate — an instance is not safe for concurrent use, and a |
| 200 | // long-lived one is a change to make when there is evidence for it. |
| 201 | // |
| 202 | // The snapshot is an accelerator and never the truth (snapshot.go): a |
| 203 | // deck with none, or one whose snapshot row could not be read, opens |
| 204 | // from the plain log and is exactly the same deck, only slower. |
| 205 | func (a *app) openDeck(ctx context.Context, d Deck) (*core.Handle, *deck.Deck, error) { |
| 206 | return a.openDeckOn(ctx, a.db.G, d) |
| 207 | } |
| 208 | |
| 209 | // openDeckOn reads every snapshot and log page on the caller's connection. |
| 210 | func (a *app) openDeckOn(ctx context.Context, db *gorm.DB, d Deck) (*core.Handle, *deck.Deck, error) { |
| 211 | h, err := a.core.NewDoc(ctx, d.Sqid, serverClientID) |
| 212 | if err != nil { |
| 213 | return nil, nil, fmt.Errorf("slides: open deck %s: %w", d.Sqid, err) |
| 214 | } |
| 215 | |
| 216 | snap, updates, err := a.replayPlanOn(ctx, db, d) |
| 217 | if err != nil { |
| 218 | h.Close(ctx) |
| 219 | return nil, nil, err |
| 220 | } |
| 221 | var since int64 |
| 222 | retained := 0 |
| 223 | if snap != nil { |
| 224 | since = snap.Seq |
| 225 | retained = 1 |
| 226 | if err := h.Apply(ctx, snap.Bytes); err != nil { |
| 227 | h.Close(ctx) |
| 228 | a.logger.Error("slides: read a deck's newest snapshot, replaying the plain log instead", |
| 229 | "deck", d.Sqid, "err", err) |
| 230 | h, err = a.core.NewDoc(ctx, d.Sqid, serverClientID) |
| 231 | if err != nil { |
| 232 | return nil, nil, fmt.Errorf("slides: open deck %s: %w", d.Sqid, err) |
| 233 | } |
| 234 | since = 0 |
| 235 | retained = 0 |
| 236 | updates, err = replayLogOn(ctx, db, d, 0) |
| 237 | if err != nil { |
| 238 | h.Close(ctx) |
| 239 | return nil, nil, err |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | for len(updates) > 0 { |
| 244 | for _, u := range updates { |
| 245 | if u.Seq != since+1 { |
| 246 | h.Close(ctx) |
| 247 | return nil, nil, fmt.Errorf("slides: incomplete deck %s log at seq %d", d.Sqid, since+1) |
| 248 | } |
| 249 | if retained >= replayCheckpointCadence { |
| 250 | state, err := h.State(ctx) |
| 251 | if err != nil { |
| 252 | h.Close(ctx) |
| 253 | return nil, nil, fmt.Errorf("slides: checkpoint deck %s replay: %w", d.Sqid, err) |
| 254 | } |
| 255 | h.Close(ctx) |
| 256 | h, err = a.core.NewDoc(ctx, d.Sqid, serverClientID) |
| 257 | if err != nil { |
| 258 | return nil, nil, err |
| 259 | } |
| 260 | if err := h.Apply(ctx, state); err != nil { |
| 261 | h.Close(ctx) |
| 262 | return nil, nil, err |
| 263 | } |
| 264 | retained = 1 |
| 265 | } |
| 266 | if err := h.Apply(ctx, u.Bytes); err != nil { |
| 267 | h.Close(ctx) |
| 268 | return nil, nil, fmt.Errorf("slides: replay deck %s update %d: %w", d.Sqid, u.Seq, err) |
| 269 | } |
| 270 | since = u.Seq |
| 271 | retained++ |
| 272 | } |
| 273 | updates, err = replayLogOn(ctx, db, d, since) |
| 274 | if err != nil { |
| 275 | h.Close(ctx) |
| 276 | return nil, nil, err |
| 277 | } |
| 278 | } |
| 279 | if since != d.Seq { |
| 280 | h.Close(ctx) |
| 281 | return nil, nil, fmt.Errorf("slides: incomplete deck %s log at seq %d", d.Sqid, since+1) |
| 282 | } |
| 283 | |
| 284 | view, err := h.JSON(ctx) |
| 285 | if err != nil { |
| 286 | h.Close(ctx) |
| 287 | return nil, nil, fmt.Errorf("slides: read deck %s view: %w", d.Sqid, err) |
| 288 | } |
| 289 | parsed, err := deck.Parse(view) |
| 290 | if err != nil { |
| 291 | h.Close(ctx) |
| 292 | return nil, nil, err |
| 293 | } |
| 294 | return h, parsed, nil |
| 295 | } |
| 296 | |
| 297 | // errDeckBusy is applyOps' optimistic-lock failure: somebody else's |
| 298 | // update landed between this one reading Deck.Seq and writing it. The |
| 299 | // batch applied nothing; the caller reopens the deck and tries again. |
| 300 | var errDeckBusy = errors.New("slides: the deck moved while this update was being written") |
| 301 | |
| 302 | // applyOps runs one batch against an open handle and records what it |
| 303 | // produced: the update bytes as the next row of d's log, and d.Seq |
| 304 | // bumped to match — both in one transaction, so a deck can never have |
| 305 | // a seq the log cannot account for. |
| 306 | // |
| 307 | // The seq bump is the optimistic lock (`WHERE id = ? AND seq = ?`): if |
| 308 | // no row matched, another writer got there first and the whole |
| 309 | // transaction rolls back with errDeckBusy. |
| 310 | // |
| 311 | // The (deck_id, seq) unique index is the SAME lock, hit one statement |
| 312 | // earlier — the update row goes in before the bump, so a losing writer |
| 313 | // violates the index before it ever reaches the clause. rastrillo's |
| 314 | // db.Open sets GORM's TranslateError, which makes that violation a |
| 315 | // gorm.ErrDuplicatedKey, and it is translated here into errDeckBusy: |
| 316 | // it is not a bug in the batch, it is the same lost race, and the |
| 317 | // caller's answer to it is the same retry. Without this the loser came |
| 318 | // out as a 500 where docs/api.md promises a 409, and editDeck's retry |
| 319 | // never ran. |
| 320 | // |
| 321 | // One honest wrinkle: h.Ops runs INSIDE the transaction, so a rollback |
| 322 | // leaves the handle holding a change the database does not. That is |
| 323 | // harmless while handles are per-request and discarded after a failure |
| 324 | // — which is every caller today — and is the reason editDeck reopens |
| 325 | // rather than retrying on the same handle. |
| 326 | // |
| 327 | // d.Seq is updated in place on success so a caller applying two batches |
| 328 | // in a row does not have to re-read the row. |
| 329 | // |
| 330 | // rowUpdates is the row's own columns (title, theme, rung — the ones a |
| 331 | // list or a link needs) to change alongside the document, in the SAME |
| 332 | // transaction as the update-log insert. Nil for every caller that only |
| 333 | // touches the document. Merged into the same `WHERE id = ? AND seq = ?` |
| 334 | // Updates call the seq bump already makes: that call is the optimistic |
| 335 | // lock, so folding the row's other columns into it costs nothing extra |
| 336 | // and means the row and the log commit or roll back together — a |
| 337 | // failure applying rowUpdates (a rejected rung, a constraint) now rolls |
| 338 | // back h.Ops' own DeckUpdate row too, rather than leaving the row |
| 339 | // diverged from the document's meta. |
| 340 | // |
| 341 | // g is the team-mode write guard (team_guard.go), run inside the |
| 342 | // transaction around everything it writes; nil outside team mode, and |
| 343 | // then the transaction is exactly what it always was. |
| 344 | func (a *app) applyOps(ctx context.Context, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any, g writeGuard) (*deck.Deck, error) { |
| 345 | err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 346 | return g.run(func() error { return applyOpsOn(ctx, tx, h, d, actor, ops, rowUpdates) }) |
| 347 | }) |
| 348 | if err != nil { |
| 349 | return nil, err |
| 350 | } |
| 351 | |
| 352 | // After the commit, not inside it: reading the view is another set |
| 353 | // of calls into the wasm module, and SQLite has one writer — doing |
| 354 | // it under the transaction would hold that connection for the whole |
| 355 | // round trip and serialise every other write behind it. |
| 356 | raw, err := h.JSON(ctx) |
| 357 | if err != nil { |
| 358 | return nil, fmt.Errorf("slides: read deck %s view: %w", d.Sqid, err) |
| 359 | } |
| 360 | view, err := deck.Parse(raw) |
| 361 | if err != nil { |
| 362 | return nil, err |
| 363 | } |
| 364 | |
| 365 | d.Seq++ |
| 366 | // After the commit, never inside it: a browser told about a seq a |
| 367 | // rolled-back transaction never wrote would fetch it and find |
| 368 | // nothing, and its cursor would sit one ahead of the deck for the |
| 369 | // rest of the session. |
| 370 | a.live.PublishSeq(d.Sqid, d.Seq) |
| 371 | // Also after the commit, and best effort: h now holds exactly the |
| 372 | // document through d.Seq, which is the one thing maybeSnapshot |
| 373 | // cannot check for itself. |
| 374 | a.maybeSnapshot(ctx, *d, h, d.Seq) |
| 375 | return view, nil |
| 376 | } |
| 377 | |
| 378 | // applyOpsOn persists one canonical batch in its caller's transaction. |
| 379 | // The caller owns the handle and discards it after rollback. No publication |
| 380 | // or snapshots may occur here: the transaction has not committed. |
| 381 | func applyOpsOn(ctx context.Context, tx *gorm.DB, h *core.Handle, d *Deck, actor string, ops []byte, rowUpdates map[string]any) error { |
| 382 | // A scene's author is the actor, never what the batch says |
| 383 | // (scene_writes.go). |
| 384 | ops, err := stampSceneOps(ops, actor) |
| 385 | if err != nil { |
| 386 | return err |
| 387 | } |
| 388 | update, err := h.Ops(ctx, ops) |
| 389 | if err != nil { |
| 390 | return fmt.Errorf("slides: apply ops to deck %s: %w", d.Sqid, err) |
| 391 | } |
| 392 | |
| 393 | next := d.Seq + 1 |
| 394 | if err := tx.Create(&DeckUpdate{ |
| 395 | DeckID: d.ID, |
| 396 | Seq: next, |
| 397 | Actor: actor, |
| 398 | Bytes: update, |
| 399 | CreatedAt: time.Now().UTC(), |
| 400 | }).Error; err != nil { |
| 401 | if errors.Is(err, gorm.ErrDuplicatedKey) { |
| 402 | // Somebody else's update is already sitting at this |
| 403 | // seq: the lost race, reported as the lost race. |
| 404 | return errDeckBusy |
| 405 | } |
| 406 | return fmt.Errorf("slides: record deck %s update %d: %w", d.Sqid, next, err) |
| 407 | } |
| 408 | |
| 409 | // Named columns off a map, never a bound struct (SKILL.md §4): |
| 410 | // "seq" is always present so the WHERE ... AND seq = ? clause |
| 411 | // above stays the sole optimistic lock, whether or not this |
| 412 | // call is also renaming the deck. |
| 413 | fields := map[string]any{"seq": next} |
| 414 | for k, v := range rowUpdates { |
| 415 | fields[k] = v |
| 416 | } |
| 417 | res := tx.Model(&Deck{}).Where("id = ? AND seq = ?", d.ID, d.Seq). |
| 418 | Updates(fields) |
| 419 | if res.Error != nil { |
| 420 | return fmt.Errorf("slides: bump deck %s seq: %w", d.Sqid, res.Error) |
| 421 | } |
| 422 | if res.RowsAffected != 1 { |
| 423 | return errDeckBusy |
| 424 | } |
| 425 | return nil |
| 426 | } |
| 427 | |
| 428 | // editDeck is applyOps with the handle's whole life around it: open the |
| 429 | // deck, apply, close. One retry on errDeckBusy, from a freshly opened |
| 430 | // document — the batch applied nothing, so replaying it against the |
| 431 | // state that beat us is the correct thing to do, and a second conflict |
| 432 | // means real contention rather than a race worth spinning on. |
| 433 | func (a *app) editDeck(ctx context.Context, d *Deck, actor string, ops []byte, rowUpdates map[string]any, g writeGuard) error { |
| 434 | var lastErr error |
| 435 | for attempt := 0; attempt < 2; attempt++ { |
| 436 | h, _, err := a.openDeck(ctx, *d) |
| 437 | if err != nil { |
| 438 | return err |
| 439 | } |
| 440 | _, err = a.applyOps(ctx, h, d, actor, ops, rowUpdates, g) |
| 441 | h.Close(ctx) |
| 442 | if err == nil { |
| 443 | return nil |
| 444 | } |
| 445 | lastErr = err |
| 446 | if !errors.Is(err, errDeckBusy) { |
| 447 | return err |
| 448 | } |
| 449 | // Re-read the row: our copy's Seq is what just lost. |
| 450 | if err := a.db.G.WithContext(ctx).First(d, d.ID).Error; err != nil { |
| 451 | return fmt.Errorf("slides: reload deck %s: %w", d.Sqid, err) |
| 452 | } |
| 453 | } |
| 454 | return lastErr |
| 455 | } |
| 456 | |
| 457 | // createDeckRow inserts the row, retrying on a sqid collision. The |
| 458 | // document itself is empty at this point — the caller's first op batch |
| 459 | // is what puts anything in it. |
| 460 | func (a *app) createDeckRow(ctx context.Context, owner User, title, theme string, g writeGuard) (Deck, error) { |
| 461 | var d Deck |
| 462 | err := a.guarded(ctx, g, func(db *gorm.DB) error { |
| 463 | var err error |
| 464 | d, err = createDeckRowOn(ctx, db, owner, title, theme) |
| 465 | return err |
| 466 | }) |
| 467 | return d, err |
| 468 | } |
| 469 | |
| 470 | func createDeckRowOn(ctx context.Context, db *gorm.DB, owner User, title, theme string) (Deck, error) { |
| 471 | now := time.Now().UTC() |
| 472 | var lastErr error |
| 473 | for attempt := 0; attempt < maxSqidAttempts; attempt++ { |
| 474 | sqid, err := newSqid() |
| 475 | if err != nil { |
| 476 | return Deck{}, err |
| 477 | } |
| 478 | d := Deck{ |
| 479 | Sqid: sqid, |
| 480 | Title: title, |
| 481 | OwnerID: owner.ID, |
| 482 | Rung: rungPrivate, // spec §5: every deck starts private |
| 483 | Theme: theme, |
| 484 | CreatedAt: now, |
| 485 | UpdatedAt: now, |
| 486 | } |
| 487 | err = db.WithContext(ctx).Create(&d).Error |
| 488 | if err == nil { |
| 489 | return d, nil |
| 490 | } |
| 491 | lastErr = err |
| 492 | if !errors.Is(err, gorm.ErrDuplicatedKey) { |
| 493 | break |
| 494 | } |
| 495 | } |
| 496 | return Deck{}, fmt.Errorf("slides: create deck: %w", lastErr) |
| 497 | } |
| 498 | |
| 499 | // --- request plumbing --- |
| 500 | |
| 501 | // viewer is the signed-in person, or a rendered 500 and false. Past |
| 502 | // RequireSession a failure here means the users row could not be read, |
| 503 | // not that nobody is signed in, so it is an error page and not a |
| 504 | // redirect. |
| 505 | func (a *app) viewer(w http.ResponseWriter, r *http.Request) (User, bool) { |
| 506 | u, outcome := a.currentUser(w, r) |
| 507 | switch outcome { |
| 508 | case sessionOK: |
| 509 | return u, true |
| 510 | case sessionOffboarded: |
| 511 | // currentUser answered for itself: the address is no longer |
| 512 | // admitted, so the person has been signed out and told why |
| 513 | // (auth.go's offboard). Not an internal error, and not a |
| 514 | // second answer written over the one already sent. |
| 515 | return User{}, false |
| 516 | default: |
| 517 | a.fail(w, r, "no current user past the session gate", nil) |
| 518 | return User{}, false |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | // fail logs why with a ref and renders the app's own 500. |
| 523 | func (a *app) fail(w http.ResponseWriter, r *http.Request, what string, err error) { |
| 524 | ref := rastrillo.NewRef() |
| 525 | a.logger.Error("slides: "+what, "err", err, "ref", ref) |
| 526 | a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref) |
| 527 | } |
| 528 | |
| 529 | // notFound is the answer for a deck that is not this person's to see — |
| 530 | // and for one that does not exist. Deliberately the same answer: see |
| 531 | // visibleDecks. |
| 532 | func (a *app) notFound(w http.ResponseWriter, r *http.Request) { |
| 533 | a.errorPage(w, r, http.StatusNotFound, kindDeck, "") |
| 534 | } |
| 535 | |
| 536 | // deckFor resolves the {sqid} in r to a deck u may read, answering 404 |
| 537 | // itself when there is none. |
| 538 | func (a *app) deckFor(w http.ResponseWriter, r *http.Request, u User) (Deck, bool) { |
| 539 | var d Deck |
| 540 | err := a.visibleDecks(r.Context(), u). |
| 541 | Where("decks.sqid = ?", chi.URLParam(r, "sqid")).Take(&d).Error |
| 542 | switch { |
| 543 | case err == nil: |
| 544 | return d, true |
| 545 | case errors.Is(err, gorm.ErrRecordNotFound) && a.teamUnknown(u): |
| 546 | // Team mode, standing unknown: the team rung was withheld, so |
| 547 | // "not here" cannot be told from "not readable right now". The |
| 548 | // retryable answer, for a deck that exists and one that does not |
| 549 | // alike. |
| 550 | a.teamUnavailable(w, r) |
| 551 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 552 | a.notFound(w, r) |
| 553 | default: |
| 554 | a.fail(w, r, "load deck", err) |
| 555 | } |
| 556 | return Deck{}, false |
| 557 | } |
| 558 | |
| 559 | // ownedDeckFor is deckFor for an owner's screen: settings, sharing and |
| 560 | // delete are the owner's, and a team member who can read the deck gets |
| 561 | // the same 404 as a stranger rather than a 403 that would confirm it |
| 562 | // exists. may is the one power the screen needs (team_owner.go): outside |
| 563 | // team mode every one of them is the owner's alone; in team mode a |
| 564 | // roster owner holds some of them on an orphan. |
| 565 | func (a *app) ownedDeckFor(w http.ResponseWriter, r *http.Request, u User, may func(context.Context, User, Deck) bool) (Deck, bool) { |
| 566 | d, ok := a.deckFor(w, r, u) |
| 567 | if !ok { |
| 568 | return Deck{}, false |
| 569 | } |
| 570 | if !may(r.Context(), u, d) { |
| 571 | if a.teamUnknown(u) { |
| 572 | a.teamUnavailable(w, r) |
| 573 | return Deck{}, false |
| 574 | } |
| 575 | a.notFound(w, r) |
| 576 | return Deck{}, false |
| 577 | } |
| 578 | return d, true |
| 579 | } |
| 580 | |
| 581 | // --- shared view data --- |
| 582 | |
| 583 | // selectOption is one entry of ui's field-select Options. |
| 584 | type selectOption struct { |
| 585 | Value string |
| 586 | Label string |
| 587 | Selected bool |
| 588 | } |
| 589 | |
| 590 | // choiceOption is one card of ui's choice-field Options. |
| 591 | type choiceOption struct { |
| 592 | Value string |
| 593 | Title string |
| 594 | Desc string |
| 595 | Checked bool |
| 596 | } |
| 597 | |
| 598 | // themeOptions builds the theme picker with current pre-selected. |
| 599 | func themeOptions(r *http.Request, current string) []selectOption { |
| 600 | opts := make([]selectOption, 0, len(themeIDs)) |
| 601 | for _, id := range themeIDs { |
| 602 | opts = append(opts, selectOption{ |
| 603 | Value: id, |
| 604 | Label: rastrillo.T(r, "slides.theme."+id), |
| 605 | Selected: id == current, |
| 606 | }) |
| 607 | } |
| 608 | return opts |
| 609 | } |
| 610 | |
| 611 | // rungOptions builds the rung radio group. Each card is a short title |
| 612 | // plus one explaining line, per choice-field's own contract — "Private" |
| 613 | // on its own does not say who that leaves out. |
| 614 | func rungOptions(r *http.Request, current string) []choiceOption { |
| 615 | opts := make([]choiceOption, 0, len(settableRungs)) |
| 616 | for _, rung := range settableRungs { |
| 617 | opts = append(opts, choiceOption{ |
| 618 | Value: rung, |
| 619 | Title: rastrillo.T(r, "slides.rung."+rung), |
| 620 | Desc: rastrillo.T(r, "slides.rung."+rung+".desc"), |
| 621 | Checked: rung == current, |
| 622 | }) |
| 623 | } |
| 624 | return opts |
| 625 | } |
| 626 | |
| 627 | // rungLabel is the pill's visible text. Always text: state is never |
| 628 | // colour alone. |
| 629 | func rungLabel(r *http.Request, rung string) string { |
| 630 | switch rung { |
| 631 | case rungPrivate, rungGranted, rungTeam: |
| 632 | return rastrillo.T(r, "slides.rung."+rung) |
| 633 | default: |
| 634 | // A rung nothing here knows: name the raw value rather than |
| 635 | // rendering an empty pill, so it is debuggable from the page. |
| 636 | return rung |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | // rungTone tints the pill. Private is the quiet default; team is the |
| 641 | // one worth noticing, because it is the rung that widens who can read. |
| 642 | func rungTone(rung string) string { |
| 643 | if rung == rungTeam { |
| 644 | return "positive" |
| 645 | } |
| 646 | return "neutral" |
| 647 | } |
| 648 | |
| 649 | // validTheme reports whether a submitted theme id is one of the six. |
| 650 | func validTheme(id string) bool { |
| 651 | for _, t := range themeIDs { |
| 652 | if t == id { |
| 653 | return true |
| 654 | } |
| 655 | } |
| 656 | return false |
| 657 | } |
| 658 | |
| 659 | // validRung reports whether a submitted rung is one a screen may set. |
| 660 | func validRung(rung string) bool { |
| 661 | for _, r := range settableRungs { |
| 662 | if r == rung { |
| 663 | return true |
| 664 | } |
| 665 | } |
| 666 | return false |
| 667 | } |
| 668 | |
| 669 | // --- GET / : the deck list --- |
| 670 | |
| 671 | // recentShelf is how many of the newest decks the list shows as covers |
| 672 | // rather than rows: one row of them across a desktop column. Docs' |
| 673 | // number, for Docs' reason (its handlers.go recentShelf). |
| 674 | const recentShelf = 5 |
| 675 | |
| 676 | // deckCard is one deck on the list, as either a cover on the shelf or a |
| 677 | // row under it. The same fields serve both, so a deck that ages off the |
| 678 | // shelf says the same things in its row. |
| 679 | type deckCard struct { |
| 680 | Href string |
| 681 | Title string |
| 682 | // Sub is the meta line: how many slides, and who made the last |
| 683 | // change (rowSub). |
| 684 | Sub string |
| 685 | // When is the last edit as a relative phrase (whenAgo), with the |
| 686 | // date itself in WhenTitle and the instant in WhenISO, for the |
| 687 | // <time> it is printed in. |
| 688 | When string |
| 689 | WhenTitle string |
| 690 | WhenISO string |
| 691 | RungLabel string |
| 692 | RungTone string |
| 693 | // Shared is true when the rung is not private: a cover names its |
| 694 | // rung only then, as text (Docs' shared note), where a row always |
| 695 | // carries the pill. |
| 696 | Shared bool |
| 697 | Cover deckCover |
| 698 | } |
| 699 | |
| 700 | // deckCover is a deck's first slide as the picture thumbs.go draws, or, |
| 701 | // for a deck with no slides (or one whose document would not open), an |
| 702 | // empty sheet in the deck's theme. |
| 703 | type deckCover struct { |
| 704 | // Src is the first slide's SVG, without its width hint: the template |
| 705 | // adds the one its size wants. Empty for the blank sheet. |
| 706 | Src string |
| 707 | // Bg is the theme's slide background, for the blank sheet. Always a |
| 708 | // hex colour from render's own table, never a deck author's value. |
| 709 | Bg string |
| 710 | } |
| 711 | |
| 712 | // decksPage is GET /. |
| 713 | type decksPage struct { |
| 714 | shell |
| 715 | Title string |
| 716 | // CanCreate shows the New deck button. In team mode only a member |
| 717 | // may create (teamMemberOnly), so nobody else is shown a button that |
| 718 | // answers 403; off team mode it is always true. |
| 719 | CanCreate bool |
| 720 | CreateLabel string |
| 721 | SearchLabel string |
| 722 | SearchPlace string |
| 723 | // Query is what was searched for, echoed back into the field so a |
| 724 | // result page can be edited and sent again. |
| 725 | Query string |
| 726 | Searching bool |
| 727 | // Recent is the newest few decks, as covers; Rows is every deck |
| 728 | // after them, or every match when Searching. |
| 729 | Recent []deckCard |
| 730 | Rows []deckCard |
| 731 | EarlierLabel string |
| 732 | EmptyTitle string |
| 733 | EmptyBody string |
| 734 | NoneTitle string |
| 735 | NoneBody string |
| 736 | ClearLabel string |
| 737 | // Partial is team mode's "we could not check your team access": |
| 738 | // the list holds the decks granted to this person and nothing on |
| 739 | // the team rung (team_answers.go's teamPartial). Always false |
| 740 | // outside team mode, where the template emits nothing for it. |
| 741 | Partial bool |
| 742 | PartialTitle string |
| 743 | PartialBody string |
| 744 | } |
| 745 | |
| 746 | // maxQuery bounds the search field. A title search longer than any |
| 747 | // title is a search for nothing; cutting it keeps the LIKE pattern |
| 748 | // small whatever the URL carries. |
| 749 | const maxQuery = 200 |
| 750 | |
| 751 | // likeEscaper escapes LIKE's two wildcards and its escape character, so |
| 752 | // a search for "100%" finds that and not everything starting "100". |
| 753 | var likeEscaper = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`) |
| 754 | |
| 755 | // decks serves GET /: every deck this person may open, most recently |
| 756 | // edited first — the newest few as their first slides, the rest as |
| 757 | // rows — or, with ?q=, the decks whose title holds those words. |
| 758 | // |
| 759 | // Each deck is opened once, for its slide count and its first slide's |
| 760 | // id. That costs one wasm instance per deck, because both live in the |
| 761 | // document and nothing else knows them. That is the honest price of not |
| 762 | // denormalising what a peer's update can change without this process |
| 763 | // noticing; it is fine at a small team's deck count and it is the first |
| 764 | // thing to revisit if this screen ever feels slow. |
| 765 | func (a *app) decks(w http.ResponseWriter, r *http.Request) { |
| 766 | u, ok := a.viewer(w, r) |
| 767 | if !ok { |
| 768 | return |
| 769 | } |
| 770 | |
| 771 | query := strings.TrimSpace(r.URL.Query().Get("q")) |
| 772 | if len(query) > maxQuery { |
| 773 | query = strings.ToValidUTF8(query[:maxQuery], "") |
| 774 | } |
| 775 | searching := query != "" |
| 776 | |
| 777 | scope := a.visibleDecks(r.Context(), u) |
| 778 | if searching { |
| 779 | scope = scope.Where(`decks.title LIKE ? ESCAPE '\'`, "%"+likeEscaper.Replace(query)+"%") |
| 780 | } |
| 781 | var rows []Deck |
| 782 | if err := scope.Order("decks.updated_at DESC, decks.id DESC").Find(&rows).Error; err != nil { |
| 783 | a.fail(w, r, "list decks", err) |
| 784 | return |
| 785 | } |
| 786 | |
| 787 | // The app root's <title> is the app's name alone (spec §10); a |
| 788 | // result page names what was searched for. |
| 789 | f := frame{} |
| 790 | if searching { |
| 791 | f = titled(rastrillo.Tf(r, "slides.decks.search.page", "q", query)) |
| 792 | } |
| 793 | page := decksPage{ |
| 794 | shell: a.shellFor(r, u, f), |
| 795 | Title: rastrillo.T(r, "slides.decks.title"), |
| 796 | CanCreate: a.member(u), |
| 797 | CreateLabel: rastrillo.T(r, "slides.decks.new"), |
| 798 | SearchLabel: rastrillo.T(r, "slides.decks.search.label"), |
| 799 | SearchPlace: rastrillo.T(r, "slides.decks.search.placeholder"), |
| 800 | Query: query, |
| 801 | Searching: searching, |
| 802 | EarlierLabel: rastrillo.T(r, "slides.decks.earlier"), |
| 803 | EmptyTitle: rastrillo.T(r, "slides.decks.empty.title"), |
| 804 | EmptyBody: rastrillo.T(r, "slides.decks.empty.body"), |
| 805 | NoneTitle: rastrillo.T(r, "slides.decks.search.none.title"), |
| 806 | NoneBody: rastrillo.T(r, "slides.decks.search.none.body"), |
| 807 | ClearLabel: rastrillo.T(r, "slides.decks.search.clear"), |
| 808 | } |
| 809 | by := a.lastChangeBy(r.Context(), rows) |
| 810 | now := time.Now() |
| 811 | cards := make([]deckCard, 0, len(rows)) |
| 812 | for _, d := range rows { |
| 813 | cards = append(cards, a.deckCardFor(r, d, by[d.ID], now)) |
| 814 | } |
| 815 | // A result is found by its title, so the shelf, which is about what |
| 816 | // was worked on last, has no place on a result page. |
| 817 | if searching { |
| 818 | page.Rows = cards |
| 819 | } else { |
| 820 | page.Recent, page.Rows = splitRecent(cards, recentShelf) |
| 821 | } |
| 822 | // After listing, of the same Access the list was built with |
| 823 | // (teamPartial): a lease that lapsed while listing marks it partial. |
| 824 | if a.teamPartial(u) { |
| 825 | page.Partial = true |
| 826 | page.PartialTitle = rastrillo.T(r, "slides.decks.partial.title") |
| 827 | page.PartialBody = rastrillo.T(r, "slides.decks.partial.body") |
| 828 | } |
| 829 | render(w, "decks", page) |
| 830 | } |
| 831 | |
| 832 | // splitRecent takes the first n cards for the shelf and leaves the rest |
| 833 | // for the rows. Nil, not empty, for a side with nothing on it, so the |
| 834 | // template's {{if}} reads the same either way. |
| 835 | func splitRecent(cards []deckCard, n int) (recent, rest []deckCard) { |
| 836 | if len(cards) == 0 { |
| 837 | return nil, nil |
| 838 | } |
| 839 | if len(cards) <= n { |
| 840 | return cards, nil |
| 841 | } |
| 842 | return cards[:n], cards[n:] |
| 843 | } |
| 844 | |
| 845 | // deckCardFor is one deck as the list shows it. |
| 846 | func (a *app) deckCardFor(r *http.Request, d Deck, by string, now time.Time) deckCard { |
| 847 | slides, first, counted := a.deckGlance(r.Context(), d) |
| 848 | card := deckCard{ |
| 849 | // A deck opens in the editor, as a document does in Docs. |
| 850 | Href: editorHref(d.Sqid), |
| 851 | Title: d.Title, |
| 852 | Sub: rowSub(r, slides, counted, by), |
| 853 | When: whenAgo(r, d.UpdatedAt, now), |
| 854 | WhenTitle: d.UpdatedAt.UTC().Format("2 January 2006, 15:04 UTC"), |
| 855 | WhenISO: d.UpdatedAt.UTC().Format(time.RFC3339), |
| 856 | RungLabel: rungLabel(r, d.Rung), |
| 857 | RungTone: rungTone(d.Rung), |
| 858 | Shared: d.Rung != rungPrivate, |
| 859 | } |
| 860 | if first != "" { |
| 861 | card.Cover.Src = "/d/" + d.Sqid + "/slides/" + first + ".svg" |
| 862 | } else { |
| 863 | card.Cover.Bg = coverBackground(d.Theme) |
| 864 | } |
| 865 | return card |
| 866 | } |
| 867 | |
| 868 | // coverBackground is the slide background of a theme, for an empty |
| 869 | // deck's blank cover: the deck still looks like itself before it has a |
| 870 | // slide. A theme nothing knows is paper's, as render does with one. |
| 871 | func coverBackground(theme string) string { |
| 872 | vars, ok := slidehtml.ThemeVars(theme) |
| 873 | if !ok { |
| 874 | vars, _ = slidehtml.ThemeVars(defaultTheme) |
| 875 | } |
| 876 | return vars["--slides-bg"] |
| 877 | } |
| 878 | |
| 879 | // lastChangeBy answers, for each deck, who made its most recent write, |
| 880 | // as a person reads it: an address for a person, the robot mark plus |
| 881 | // the principal for an agent (agents.go's actorLabels). |
| 882 | // |
| 883 | // Spec §6.2's actor column is what makes this possible at all, and |
| 884 | // spec §7.1 is why it is on the screen: an agent's write is a |
| 885 | // different kind of fact from a person's, and a list that showed them |
| 886 | // identically would be hiding the one thing worth knowing about a deck |
| 887 | // a program has been editing. |
| 888 | // |
| 889 | // One query for every row, not one per row: the subquery finds each |
| 890 | // deck's highest seq and the join reads that row's actor. A failure |
| 891 | // here is logged and the list renders without the line — the list is |
| 892 | // how a person reaches every deck, so it must not go down over a |
| 893 | // caption. |
| 894 | func (a *app) lastChangeBy(ctx context.Context, decks []Deck) map[int64]string { |
| 895 | if len(decks) == 0 { |
| 896 | return nil |
| 897 | } |
| 898 | ids := make([]int64, 0, len(decks)) |
| 899 | for _, d := range decks { |
| 900 | ids = append(ids, d.ID) |
| 901 | } |
| 902 | |
| 903 | var latest []struct { |
| 904 | DeckID int64 |
| 905 | Actor string |
| 906 | } |
| 907 | err := a.db.G.WithContext(ctx).Raw(` |
| 908 | SELECT u.deck_id AS deck_id, u.actor AS actor |
| 909 | FROM deck_updates u |
| 910 | JOIN (SELECT deck_id, MAX(seq) AS seq FROM deck_updates WHERE deck_id IN ? GROUP BY deck_id) m |
| 911 | ON m.deck_id = u.deck_id AND m.seq = u.seq`, ids).Scan(&latest).Error |
| 912 | if err != nil { |
| 913 | a.logger.Error("slides: read the last change on each deck", "err", err) |
| 914 | return nil |
| 915 | } |
| 916 | |
| 917 | actors := make([]string, 0, len(latest)) |
| 918 | for _, row := range latest { |
| 919 | actors = append(actors, row.Actor) |
| 920 | } |
| 921 | labels := a.actorLabels(ctx, actors) |
| 922 | |
| 923 | out := make(map[int64]string, len(latest)) |
| 924 | for _, row := range latest { |
| 925 | if label := labels[row.Actor]; label != "" { |
| 926 | out[row.DeckID] = label |
| 927 | } |
| 928 | } |
| 929 | return out |
| 930 | } |
| 931 | |
| 932 | // slideCount opens d far enough to count its slides. A deck that will |
| 933 | // not open is logged and reported as uncounted rather than failing the |
| 934 | // whole screen. |
| 935 | func (a *app) slideCount(ctx context.Context, d Deck) (int, bool) { |
| 936 | n, _, ok := a.deckGlance(ctx, d) |
| 937 | return n, ok |
| 938 | } |
| 939 | |
| 940 | // deckGlance opens d far enough to count its slides and name the first |
| 941 | // one, which is the deck's cover on the list. A deck that will not open |
| 942 | // is logged and reported as uncounted rather than failing the whole |
| 943 | // screen: the list is how a person reaches every OTHER deck, so one |
| 944 | // unreadable document must not take the other nine away with it. |
| 945 | func (a *app) deckGlance(ctx context.Context, d Deck) (slides int, first string, ok bool) { |
| 946 | h, view, err := a.openDeck(ctx, d) |
| 947 | if err != nil { |
| 948 | a.logger.Error("slides: open deck for the list", "deck", d.Sqid, "err", err) |
| 949 | return 0, "", false |
| 950 | } |
| 951 | defer h.Close(ctx) |
| 952 | // The cover is the first slide that is not parked. |
| 953 | if shown := view.ForReaders(); len(shown.Slides) > 0 { |
| 954 | first = shown.Slides[0].ID |
| 955 | } |
| 956 | return len(view.Slides), first, true |
| 957 | } |
| 958 | |
| 959 | // rowSub is a deck's meta line on the list: how many slides, and who |
| 960 | // made the last change. An uncounted deck (see deckGlance) shows no |
| 961 | // count rather than one that would be a guess, and a deck whose last |
| 962 | // actor could not be resolved shows no name rather than a raw |
| 963 | // "person:7". The time is not here: the list prints it on its own, in a |
| 964 | // <time>. |
| 965 | func rowSub(r *http.Request, slides int, counted bool, by string) string { |
| 966 | sub := "" |
| 967 | if counted { |
| 968 | switch slides { |
| 969 | case 0: |
| 970 | sub = rastrillo.T(r, "slides.decks.row.slides.none") |
| 971 | case 1: |
| 972 | sub = rastrillo.T(r, "slides.decks.row.slides.one") |
| 973 | default: |
| 974 | sub = rastrillo.Tf(r, "slides.decks.row.slides", "n", slides) |
| 975 | } |
| 976 | } |
| 977 | switch { |
| 978 | case by == "": |
| 979 | return sub |
| 980 | case sub == "": |
| 981 | return rastrillo.Tf(r, "slides.decks.row.by.only", "who", by) |
| 982 | default: |
| 983 | return rastrillo.Tf(r, "slides.decks.row.by", "sub", sub, "who", by) |
| 984 | } |
| 985 | } |
| 986 | |
| 987 | // whenWords is a day-grained relative phrase, falling back to the date |
| 988 | // itself once "n days ago" stops being easier to read than a date. It |
| 989 | // sits inside a sentence ("created today"), so it is lower case. |
| 990 | func whenWords(r *http.Request, t time.Time) string { |
| 991 | days := int(time.Since(t).Hours() / 24) |
| 992 | switch { |
| 993 | case days <= 0: |
| 994 | return rastrillo.T(r, "slides.when.today") |
| 995 | case days == 1: |
| 996 | return rastrillo.T(r, "slides.when.yesterday") |
| 997 | case days < 7: |
| 998 | return rastrillo.Tf(r, "slides.when.days", "n", days) |
| 999 | default: |
| 1000 | return rastrillo.Tf(r, "slides.when.on", "date", t.Format("2 January 2006")) |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | // whenAgo is the deck list's own relative time, standing alone under a |
| 1005 | // cover or at the end of a row: finer than whenWords on the day itself, |
| 1006 | // because the newest decks on the shelf are usually all from today and |
| 1007 | // "today" five times over tells them apart by nothing. Past a week it |
| 1008 | // is the date, short, with the year only when it is not this one. The |
| 1009 | // full date is in the <time>'s title beside it. |
| 1010 | func whenAgo(r *http.Request, t, now time.Time) string { |
| 1011 | d := now.Sub(t) |
| 1012 | switch { |
| 1013 | case d < time.Minute: |
| 1014 | return rastrillo.T(r, "slides.when.now") |
| 1015 | case d < time.Hour: |
| 1016 | n := int(d / time.Minute) |
| 1017 | if n == 1 { |
| 1018 | return rastrillo.T(r, "slides.when.minutes.one") |
| 1019 | } |
| 1020 | return rastrillo.Tf(r, "slides.when.minutes", "n", n) |
| 1021 | case d < 24*time.Hour: |
| 1022 | n := int(d / time.Hour) |
| 1023 | if n == 1 { |
| 1024 | return rastrillo.T(r, "slides.when.hours.one") |
| 1025 | } |
| 1026 | return rastrillo.Tf(r, "slides.when.hours", "n", n) |
| 1027 | case d < 48*time.Hour: |
| 1028 | return rastrillo.T(r, "slides.when.yesterday.alone") |
| 1029 | case d < 7*24*time.Hour: |
| 1030 | return rastrillo.Tf(r, "slides.when.days", "n", int(d/(24*time.Hour))) |
| 1031 | case t.Year() == now.Year(): |
| 1032 | return t.Format("2 Jan") |
| 1033 | default: |
| 1034 | return t.Format("2 Jan 2006") |
| 1035 | } |
| 1036 | } |
| 1037 | |
| 1038 | // --- GET /decks/new, POST /decks --- |
| 1039 | |
| 1040 | // A new deck is made at once and opened in the editor, with no title box |
| 1041 | // first (Docs' "New document", 2026-11): the list's New deck button is a |
| 1042 | // form that POSTs here, and the deck is named "Untitled deck" until |
| 1043 | // somebody names it where they are working on it. GET /decks/new stays, |
| 1044 | // for a link or a bookmark that still points at it: a page with that |
| 1045 | // one button on it. |
| 1046 | |
| 1047 | type deckNewPage struct { |
| 1048 | shell |
| 1049 | Title string |
| 1050 | Body string |
| 1051 | Submit string |
| 1052 | CancelHref string |
| 1053 | CancelLabel string |
| 1054 | Error string |
| 1055 | } |
| 1056 | |
| 1057 | func (a *app) newDeck(w http.ResponseWriter, r *http.Request) { |
| 1058 | u, ok := a.viewer(w, r) |
| 1059 | if !ok { |
| 1060 | return |
| 1061 | } |
| 1062 | if !a.teamMemberOnly(w, r, u) { |
| 1063 | return |
| 1064 | } |
| 1065 | render(w, "deck_new", a.newDeckPage(r, u, "")) |
| 1066 | } |
| 1067 | |
| 1068 | func (a *app) newDeckPage(r *http.Request, u User, problem string) deckNewPage { |
| 1069 | return deckNewPage{ |
| 1070 | shell: a.shellFor(r, u, titled(rastrillo.T(r, "slides.decks.new"))), |
| 1071 | Title: rastrillo.T(r, "slides.decks.new"), |
| 1072 | Body: rastrillo.T(r, "slides.decks.new.body"), |
| 1073 | Submit: rastrillo.T(r, "slides.decks.new.submit"), |
| 1074 | CancelHref: "/", |
| 1075 | CancelLabel: rastrillo.T(r, "slides.cancel"), |
| 1076 | Error: problem, |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | // createDeck serves POST /decks: the row, then the document's opening |
| 1081 | // batch — the title and theme in meta, and one title slide carrying the |
| 1082 | // same words, so a new deck opens on something rather than on nothing — |
| 1083 | // and then the editor. |
| 1084 | // |
| 1085 | // Both fields are optional. With no title (the list's button sends |
| 1086 | // none) the deck is "Untitled deck", in the reader's language; with no |
| 1087 | // theme it is the default. A theme that is sent must be one of the six. |
| 1088 | func (a *app) createDeck(w http.ResponseWriter, r *http.Request) { |
| 1089 | u, ok := a.viewer(w, r) |
| 1090 | if !ok { |
| 1091 | return |
| 1092 | } |
| 1093 | if !a.teamMemberOnly(w, r, u) { |
| 1094 | return |
| 1095 | } |
| 1096 | |
| 1097 | title := strings.TrimSpace(r.PostFormValue("title")) |
| 1098 | untitled := title == "" |
| 1099 | if untitled { |
| 1100 | title = rastrillo.T(r, "slides.deck.untitled") |
| 1101 | } |
| 1102 | theme := r.PostFormValue("theme") |
| 1103 | if theme == "" { |
| 1104 | theme = defaultTheme |
| 1105 | } |
| 1106 | if !validTheme(theme) { |
| 1107 | w.WriteHeader(http.StatusUnprocessableEntity) |
| 1108 | render(w, "deck_new", a.newDeckPage(r, u, rastrillo.T(r, "slides.deck.theme.invalid"))) |
| 1109 | return |
| 1110 | } |
| 1111 | |
| 1112 | g := a.memberGuard(r.Context(), u) |
| 1113 | d, err := a.createDeckRow(r.Context(), u, title, theme, g) |
| 1114 | if a.guardRefused(w, r, err) { |
| 1115 | return |
| 1116 | } |
| 1117 | if err != nil { |
| 1118 | a.fail(w, r, "create deck", err) |
| 1119 | return |
| 1120 | } |
| 1121 | open := openingOps |
| 1122 | if untitled { |
| 1123 | open = blankOpeningOps |
| 1124 | } |
| 1125 | ops, err := open(title, theme) |
| 1126 | if err != nil { |
| 1127 | a.fail(w, r, "build the opening ops", err) |
| 1128 | return |
| 1129 | } |
| 1130 | if err := a.editDeck(r.Context(), &d, actorFor(u), ops, nil, g); err != nil { |
| 1131 | if a.guardRefused(w, r, err) { |
| 1132 | return |
| 1133 | } |
| 1134 | a.fail(w, r, "write the opening ops", err) |
| 1135 | return |
| 1136 | } |
| 1137 | http.Redirect(w, r, "/d/"+d.Sqid+"/edit", http.StatusSeeOther) |
| 1138 | } |
| 1139 | |
| 1140 | // openingOps is a brand-new deck's first batch: meta, one flow slide on |
| 1141 | // the `title` template, and a level-1 heading carrying the deck's name. |
| 1142 | func openingOps(title, theme string) ([]byte, error) { |
| 1143 | slide, err := newID() |
| 1144 | if err != nil { |
| 1145 | return nil, err |
| 1146 | } |
| 1147 | heading, err := newID() |
| 1148 | if err != nil { |
| 1149 | return nil, err |
| 1150 | } |
| 1151 | return opsJSON([]op{ |
| 1152 | {"op": "set_meta", "title": title, "theme": theme}, |
| 1153 | {"op": "add_slide", "id": slide, "layout": "flow", "template": "title"}, |
| 1154 | {"op": "add_block", "slide": slide, "id": heading, "type": "heading", |
| 1155 | "props": map[string]any{"level": 1}, "region": "heading", "markdown": title}, |
| 1156 | }) |
| 1157 | } |
| 1158 | |
| 1159 | // blankOpeningOps is the first batch of a deck made with no name (the |
| 1160 | // list's New deck, which opens in the editor): the same title slide as |
| 1161 | // fixtures/slide-layouts.mjs's "title" layout, its heading and subtitle |
| 1162 | // empty, so the editor shows "Add a title" and "Add text" to type into |
| 1163 | // rather than the words "Untitled deck" to select and replace. The |
| 1164 | // deck's own title is still "Untitled deck" until it is renamed. |
| 1165 | func blankOpeningOps(title, theme string) ([]byte, error) { |
| 1166 | slide, err := newID() |
| 1167 | if err != nil { |
| 1168 | return nil, err |
| 1169 | } |
| 1170 | heading, err := newID() |
| 1171 | if err != nil { |
| 1172 | return nil, err |
| 1173 | } |
| 1174 | sub, err := newID() |
| 1175 | if err != nil { |
| 1176 | return nil, err |
| 1177 | } |
| 1178 | return opsJSON([]op{ |
| 1179 | {"op": "set_meta", "title": title, "theme": theme}, |
| 1180 | {"op": "add_slide", "id": slide, "layout": "flow", "template": "title"}, |
| 1181 | {"op": "add_block", "slide": slide, "id": heading, "type": "heading", |
| 1182 | "props": map[string]any{"level": 1}, "region": "heading", "markdown": ""}, |
| 1183 | {"op": "add_block", "slide": slide, "id": sub, "type": "text", |
| 1184 | "props": map[string]any{"size": "l"}, "region": "body", "markdown": ""}, |
| 1185 | }) |
| 1186 | } |
| 1187 | |
| 1188 | // --- GET/POST /d/{sqid}/settings --- |
| 1189 | // |
| 1190 | // The deck's title and theme as a scriptless form. Nothing links it as a |
| 1191 | // destination any more: the editor's inspector holds both (with Docs' |
| 1192 | // shape, a deck's settings are an inspector, not a page), and who can |
| 1193 | // open the deck is on the share page. It stays for somebody with |
| 1194 | // scripts off — the editor's <noscript> links it — and the POST still |
| 1195 | // takes a rung, for a caller that posts one (the share page's form is |
| 1196 | // the screen that does now). |
| 1197 | |
| 1198 | type deckSettingsPage struct { |
| 1199 | shell |
| 1200 | Title string |
| 1201 | Action string |
| 1202 | TitleLabel string |
| 1203 | TitleValue string |
| 1204 | ThemeLabel string |
| 1205 | Themes []selectOption |
| 1206 | // AccessHref is the share page, where who can open the deck is |
| 1207 | // chosen now (share.go's saveDeckAccess); empty for somebody who |
| 1208 | // may not share it. |
| 1209 | AccessHref string |
| 1210 | AccessBody string |
| 1211 | AccessLabel string |
| 1212 | Submit string |
| 1213 | CancelHref string |
| 1214 | CancelLabel string |
| 1215 | DeleteHref string |
| 1216 | DeleteLabel string |
| 1217 | DeleteBody string |
| 1218 | BackHref string |
| 1219 | BackLabel string |
| 1220 | Errors map[string]string |
| 1221 | } |
| 1222 | |
| 1223 | func (a *app) settingsPage(r *http.Request, u User, d Deck, title, theme string, errs map[string]string) deckSettingsPage { |
| 1224 | base := "/d/" + d.Sqid |
| 1225 | page := deckSettingsPage{ |
| 1226 | shell: a.shellFor(r, u, onDeck(rastrillo.T(r, "slides.deck.settings"), d.Title)), |
| 1227 | Title: rastrillo.T(r, "slides.deck.settings"), |
| 1228 | Action: base + "/settings", |
| 1229 | TitleLabel: rastrillo.T(r, "slides.deck.title.label"), |
| 1230 | TitleValue: title, |
| 1231 | ThemeLabel: rastrillo.T(r, "slides.deck.theme.label"), |
| 1232 | Themes: themeOptions(r, theme), |
| 1233 | Submit: rastrillo.T(r, "slides.deck.settings.submit"), |
| 1234 | // The settings page is the scripts-off fallback now (the editor's |
| 1235 | // inspector is everyone else's), so its ways out go to the viewer, |
| 1236 | // which works without scripts, not to /d/{sqid} — that opens the |
| 1237 | // editor and its "needs scripts" notice (Claude Fable, #43). |
| 1238 | CancelHref: viewerStart(d.Sqid), |
| 1239 | CancelLabel: rastrillo.T(r, "slides.cancel"), |
| 1240 | DeleteHref: base + "/delete", |
| 1241 | DeleteLabel: rastrillo.T(r, "slides.deck.delete"), |
| 1242 | DeleteBody: rastrillo.T(r, "slides.deck.delete.lead"), |
| 1243 | BackHref: viewerStart(d.Sqid), |
| 1244 | BackLabel: rastrillo.T(r, "slides.deck.back"), |
| 1245 | Errors: errs, |
| 1246 | } |
| 1247 | // Who can open the deck is the share page's now (Docs' place for |
| 1248 | // general access); this page says where it went. |
| 1249 | if a.mayShareDeck(r.Context(), u, d) { |
| 1250 | page.AccessHref = base + "/share" |
| 1251 | page.AccessBody = rastrillo.T(r, "slides.deck.settings.access") |
| 1252 | page.AccessLabel = rastrillo.T(r, "slides.share.action") |
| 1253 | } |
| 1254 | // A roster owner on an orphan (team_owner.go) is offered what they |
| 1255 | // may change and nothing more: no delete. Outside team mode the |
| 1256 | // owner may and the page is as it always was. |
| 1257 | if !a.mayDeleteDeck(r.Context(), u, d) { |
| 1258 | page.DeleteHref = "" |
| 1259 | } |
| 1260 | return page |
| 1261 | } |
| 1262 | |
| 1263 | func (a *app) deckSettings(w http.ResponseWriter, r *http.Request) { |
| 1264 | u, ok := a.viewer(w, r) |
| 1265 | if !ok { |
| 1266 | return |
| 1267 | } |
| 1268 | d, ok := a.ownedDeckFor(w, r, u, a.mayRetitleDeck) |
| 1269 | if !ok { |
| 1270 | return |
| 1271 | } |
| 1272 | render(w, "deck_settings", a.settingsPage(r, u, d, d.Title, d.Theme, nil)) |
| 1273 | } |
| 1274 | |
| 1275 | // saveDeckSettings serves POST /d/{sqid}/settings. |
| 1276 | // |
| 1277 | // Title and theme live in two places — the row the list reads and the |
| 1278 | // document everyone edits — so both are written, and both go through |
| 1279 | // editDeck's rowUpdates so they land in the SAME transaction as the |
| 1280 | // update-log insert applyOps makes. A rejected row write (a rung a |
| 1281 | // constraint refuses, say) now rolls the document change back too, |
| 1282 | // rather than leaving the row's title/theme diverged from what the |
| 1283 | // document's meta says — the earlier two-transaction shape's window. |
| 1284 | func (a *app) saveDeckSettings(w http.ResponseWriter, r *http.Request) { |
| 1285 | u, ok := a.viewer(w, r) |
| 1286 | if !ok { |
| 1287 | return |
| 1288 | } |
| 1289 | d, ok := a.ownedDeckFor(w, r, u, a.mayRetitleDeck) |
| 1290 | if !ok { |
| 1291 | return |
| 1292 | } |
| 1293 | |
| 1294 | p := form.Parse(r, form.Field{Name: "title", Required: true}) |
| 1295 | title := p.String("title") |
| 1296 | theme := r.PostFormValue("theme") |
| 1297 | rung := r.PostFormValue("rung") |
| 1298 | // The form no longer carries the rung (it is the share page's): a |
| 1299 | // POST without one leaves it where it is. |
| 1300 | if rung == "" { |
| 1301 | rung = d.Rung |
| 1302 | } |
| 1303 | if !a.mayChangeRung(r.Context(), u, d) { |
| 1304 | // Team mode, a roster owner on an orphan (team_owner.go): title |
| 1305 | // and theme only. A rung posted anyway must be the deck's own, |
| 1306 | // never a narrowing. |
| 1307 | if rung != d.Rung { |
| 1308 | a.errorPage(w, r, http.StatusForbidden, kindStatus, "") |
| 1309 | return |
| 1310 | } |
| 1311 | } |
| 1312 | errs := map[string]string{} |
| 1313 | if !p.OK() { |
| 1314 | errs["Title"] = rastrillo.T(r, "slides.deck.title.required") |
| 1315 | } |
| 1316 | if !validTheme(theme) { |
| 1317 | errs["Theme"] = rastrillo.T(r, "slides.deck.theme.invalid") |
| 1318 | } |
| 1319 | // The deck's own rung passes even when it is one no screen sets |
| 1320 | // (granted): leaving it alone is not choosing it. |
| 1321 | if rung != d.Rung && !validRung(rung) { |
| 1322 | errs["Rung"] = rastrillo.T(r, "slides.deck.rung.invalid") |
| 1323 | } |
| 1324 | if len(errs) > 0 { |
| 1325 | w.WriteHeader(http.StatusUnprocessableEntity) |
| 1326 | render(w, "deck_settings", a.settingsPage(r, u, d, p.Echo()["title"], theme, errs)) |
| 1327 | return |
| 1328 | } |
| 1329 | |
| 1330 | ops, err := opsJSON([]op{{"op": "set_meta", "title": title, "theme": theme}}) |
| 1331 | if err != nil { |
| 1332 | a.fail(w, r, "build the settings ops", err) |
| 1333 | return |
| 1334 | } |
| 1335 | rowUpdates := map[string]any{"title": title, "theme": theme, "rung": rung} |
| 1336 | if err := a.editDeck(r.Context(), &d, actorFor(u), ops, rowUpdates, a.memberGuard(r.Context(), u)); err != nil { |
| 1337 | if a.guardRefused(w, r, err) { |
| 1338 | return |
| 1339 | } |
| 1340 | a.fail(w, r, "write the settings ops", err) |
| 1341 | return |
| 1342 | } |
| 1343 | http.Redirect(w, r, viewerStart(d.Sqid), http.StatusSeeOther) |
| 1344 | } |
| 1345 | |
| 1346 | // --- GET/POST /d/{sqid}/delete --- |
| 1347 | |
| 1348 | type deckDeletePage struct { |
| 1349 | shell |
| 1350 | Title string |
| 1351 | Body string |
| 1352 | Action string |
| 1353 | Label string |
| 1354 | CancelHref string |
| 1355 | CancelLabel string |
| 1356 | BackHref string |
| 1357 | BackLabel string |
| 1358 | } |
| 1359 | |
| 1360 | // confirmDeleteDeck serves GET /d/{sqid}/delete: the destructive |
| 1361 | // action's own URL and its own page, per the app's own convention. No |
| 1362 | // modal, no JavaScript, and a GET that changes nothing. |
| 1363 | func (a *app) confirmDeleteDeck(w http.ResponseWriter, r *http.Request) { |
| 1364 | u, ok := a.viewer(w, r) |
| 1365 | if !ok { |
| 1366 | return |
| 1367 | } |
| 1368 | d, ok := a.ownedDeckFor(w, r, u, a.mayDeleteDeck) |
| 1369 | if !ok { |
| 1370 | return |
| 1371 | } |
| 1372 | base := "/d/" + d.Sqid |
| 1373 | render(w, "deck_delete", deckDeletePage{ |
| 1374 | shell: a.shellFor(r, u, frame{parts: []string{rastrillo.Tf(r, "slides.deck.delete.title", "title", d.Title)}, context: d.Title}), |
| 1375 | Title: rastrillo.Tf(r, "slides.deck.delete.title", "title", d.Title), |
| 1376 | Body: rastrillo.T(r, "slides.deck.delete.body"), |
| 1377 | Action: base + "/delete", |
| 1378 | Label: rastrillo.T(r, "slides.deck.delete.confirm"), |
| 1379 | CancelHref: base, |
| 1380 | CancelLabel: rastrillo.T(r, "slides.cancel"), |
| 1381 | BackHref: base, |
| 1382 | BackLabel: rastrillo.T(r, "slides.deck.back"), |
| 1383 | }) |
| 1384 | } |
| 1385 | |
| 1386 | // deleteDeck serves POST /d/{sqid}/delete. The row, its whole update |
| 1387 | // log and its grants go in one transaction: a deck's updates without |
| 1388 | // their deck are unreachable bytes nothing will ever replay, and a |
| 1389 | // grant to a deck that is gone is a permission pointing at nothing. |
| 1390 | // |
| 1391 | // The presentations go too, and they are the one part with a second |
| 1392 | // half. A session outliving its deck is a live pairing code and a |
| 1393 | // projector holding a talk that can never move again, so the rows go |
| 1394 | // in the same transaction; but every page watching one is parked on |
| 1395 | // the stream, and the stream only ever says anything because the hub |
| 1396 | // does. So the live sessions are read inside the transaction and told |
| 1397 | // after the commit — never before, because an "ended" for a delete |
| 1398 | // that then rolled back would stop a talk that is still running. |
| 1399 | func (a *app) deleteDeck(w http.ResponseWriter, r *http.Request) { |
| 1400 | u, ok := a.viewer(w, r) |
| 1401 | if !ok { |
| 1402 | return |
| 1403 | } |
| 1404 | d, ok := a.ownedDeckFor(w, r, u, a.mayDeleteDeck) |
| 1405 | if !ok { |
| 1406 | return |
| 1407 | } |
| 1408 | |
| 1409 | var live []Presentation |
| 1410 | var fonts []string |
| 1411 | g := a.memberGuard(r.Context(), u) |
| 1412 | // Under the font library's lock, as every change to who holds a font |
| 1413 | // file is (library.go): the deck's DeckFont rows go in the |
| 1414 | // transaction, and a file no library and no other deck still names |
| 1415 | // goes after the commit. |
| 1416 | a.fontMu.Lock() |
| 1417 | defer a.fontMu.Unlock() |
| 1418 | err := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error { |
| 1419 | return g.run(func() error { return deleteDeckTx(tx, d, &live, &fonts) }) |
| 1420 | }) |
| 1421 | if a.guardRefused(w, r, err) { |
| 1422 | return |
| 1423 | } |
| 1424 | if err != nil { |
| 1425 | a.fail(w, r, "delete deck", err) |
| 1426 | return |
| 1427 | } |
| 1428 | for _, ref := range fonts { |
| 1429 | a.dropFontObject(r.Context(), ref) |
| 1430 | } |
| 1431 | // Every projector, phone and follower watching one of this deck's |
| 1432 | // talks, told at once that it is over. |
| 1433 | for _, p := range live { |
| 1434 | a.hub.Publish(p.Sqid, present.Event{Ended: true}) |
| 1435 | } |
| 1436 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 1437 | } |
| 1438 | |
| 1439 | // deleteDeckTx is deleteDeck's transaction: every row of d, the live |
| 1440 | // presentations it ended in live, to be told after the commit, and the |
| 1441 | // font files the deck had recorded in fonts, for their objects to go if |
| 1442 | // nothing else names them. The deck row goes by its own owner_id, which |
| 1443 | // ownedDeckFor (mayDeleteDeck) confirmed is the viewer's. |
| 1444 | func deleteDeckTx(tx *gorm.DB, d Deck, live *[]Presentation, fonts *[]string) error { |
| 1445 | *live = nil |
| 1446 | *fonts = nil |
| 1447 | if err := tx.Where("deck_id = ? AND ended_at IS NULL", d.ID). |
| 1448 | Find(live).Error; err != nil { |
| 1449 | return err |
| 1450 | } |
| 1451 | if err := tx.Model(&DeckFont{}).Where("deck_id = ?", d.ID).Pluck("ref", fonts).Error; err != nil { |
| 1452 | return err |
| 1453 | } |
| 1454 | if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckFont{}).Error; err != nil { |
| 1455 | return err |
| 1456 | } |
| 1457 | if err := tx.Where("presentation_id IN (?)", |
| 1458 | tx.Model(&Presentation{}).Select("id").Where("deck_id = ?", d.ID)). |
| 1459 | Delete(&PresentationPress{}).Error; err != nil { |
| 1460 | return err |
| 1461 | } |
| 1462 | if err := tx.Where("presentation_id IN (?)", |
| 1463 | tx.Model(&Presentation{}).Select("id").Where("deck_id = ?", d.ID)). |
| 1464 | Delete(&PresentationLink{}).Error; err != nil { |
| 1465 | return err |
| 1466 | } |
| 1467 | if err := tx.Where("deck_id = ?", d.ID).Delete(&Presentation{}).Error; err != nil { |
| 1468 | return err |
| 1469 | } |
| 1470 | if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckUpdate{}).Error; err != nil { |
| 1471 | return err |
| 1472 | } |
| 1473 | // The snapshots and the verified-asset rows are derived from |
| 1474 | // the deck and read by nothing but it: a snapshot left behind |
| 1475 | // is a whole copy of the document nothing can reach, and an |
| 1476 | // asset row a verification for a deck that no longer exists. |
| 1477 | if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckSnapshot{}).Error; err != nil { |
| 1478 | return err |
| 1479 | } |
| 1480 | if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckAsset{}).Error; err != nil { |
| 1481 | return err |
| 1482 | } |
| 1483 | if err := tx.Where("deck_id = ?", d.ID).Delete(&SceneBundle{}).Error; err != nil { |
| 1484 | return err |
| 1485 | } |
| 1486 | // And the upload receipts (models.go's AssetUpload): a receipt |
| 1487 | // is registrable only into the deck it was staged for, so one |
| 1488 | // whose deck is gone is a row nothing can ever spend. |
| 1489 | if err := tx.Where("deck_id = ?", d.ID).Delete(&AssetUpload{}).Error; err != nil { |
| 1490 | return err |
| 1491 | } |
| 1492 | if err := tx.Where("deck_id = ?", d.ID).Delete(&DeckGrant{}).Error; err != nil { |
| 1493 | return err |
| 1494 | } |
| 1495 | // The share links go too. A link outliving its deck is a live |
| 1496 | // URL that can only ever answer 404, and leaving one behind |
| 1497 | // would mean the one row in this database that grants |
| 1498 | // unauthenticated read is also the one nothing cleans up. |
| 1499 | if err := tx.Where("deck_id = ?", d.ID).Delete(&ShareLink{}).Error; err != nil { |
| 1500 | return err |
| 1501 | } |
| 1502 | return tx.Where("id = ? AND owner_id = ?", d.ID, d.OwnerID).Delete(&Deck{}).Error |
| 1503 | } |
| 1504 | |