oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// presentation.go is presenting: the session row, the fullscreen
2// surface, the presenter view, the phone remote and the audience's
3// follow.
4//
5// The one idea, spec §3.4 and ruling 5: presenting is a SERVER-SIDE
6// SESSION. There is one row that says which slide is on the screen,
7// and the projector, the presenter's second window, the phone in their
8// hand and every follower all read and write that same row. Nothing
9// here is a peer-to-peer arrangement between browsers, so there is no
10// state that can disagree with itself; the SSE stream
11// (internal/slides/present) is a notification that the row moved, not
12// the place the row lives.
13//
14// Three capabilities, deliberately different in strength:
15//
16// - The session SQID is a VIEWING capability, exactly like a share
17// link: anybody who has the address may watch the fullscreen
18// surface. It is what makes "put this on the projector" a URL.
19// - The REMOTE TOKEN is the driving capability, and the only thing
20// that may move the deck. It is 32 bytes, stored as a hash, and
21// shown once — the share link's construction and the share link's
22// reason (share.go).
23// - The PAIRING CODE is neither on its own. It is six sayable
24// characters that name a live session so a phone can find it; the
25// token still has to arrive with it. A code alone being enough
26// would make every talk in the building drivable by whoever
27// guessed six characters.
28//
29// The speaker notes follow the strongest of the three: the presenter's
30// own session, or the remote token. Never the sqid, because the sqid
31// is what goes on a projector.
32//
33// AN AUDIENCE NEVER LEARNS THE SQID (codex 5). Somebody following
34// along arrived with a share link and stays behind it: the page, the
35// slide fragments, the stream and the pictures are all `/s/{token}`
36// routes, each of which resolves the token again, so revoking the link
37// stops them mid-talk. Before the codex review, following handed the
38// session sqid to the browser and every later read went to `/p/…`,
39// which asks only for a live session — so a revoked link kept working
40// until the talk ended. The sqid is a projector address, and a
41// projector address is not something to give an audience.
42package slides
43
44import (
45 "amadan.net/oficina/estilo.git/chrome"
46 "crypto/rand"
47 "crypto/sha256"
48 "crypto/subtle"
49 "encoding/base64"
50 "encoding/hex"
51 "encoding/json"
52 "errors"
53 "fmt"
54 "html/template"
55 "io"
56 "net/http"
57 "net/url"
58 "strconv"
59 "strings"
60 "time"
61
62 "amadan.net/oficina/slides/internal/slides/deck"
63 "amadan.net/oficina/slides/internal/slides/present"
64 slidehtml "amadan.net/oficina/slides/internal/slides/render"
65 "amadan.net/rastrillo/rastrillo"
66 "amadan.net/rastrillo/rastrillo/sessions"
67 "github.com/go-chi/chi/v5"
68 "github.com/skip2/go-qrcode"
69 "gorm.io/gorm"
70)
71
72// --- what a session is, and how long it lasts ---
73
74// presentTTL is how long a session stays live without being ended.
75// Spec §3.4: "ended explicitly or after 12 hours". A talk nobody
76// closed must not still be driveable tomorrow morning by whoever still
77// has the phone URL in a browser tab.
78const presentTTL = 12 * time.Hour
79
80// codeAlphabet is the pairing code's: no O or 0, no I or 1, because
81// this is the one string in the app a person reads off a projector and
82// types on a phone. Upper case for the same reason — it is read aloud.
83const codeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
84
85// codeLength is six characters: 32^6 is a billion, which is not a
86// keyspace anybody brute-forces through a web form, and the code is
87// not a capability on its own anyway (this file's own comment).
88const codeLength = 6
89
90// remoteTokenBytes is the remote capability's randomness — the share
91// link's 32 bytes, for the share link's reason (share.go).
92const remoteTokenBytes = 32
93
94// maxCodeAttempts bounds the retry loop when a freshly minted code is
95// already in use by another live session. Collisions are rare and real:
96// unique among live sessions is a small set, but it is not empty.
97const maxCodeAttempts = 8
98
99// newRemoteToken mints the remote's capability: base64url, nothing to
100// escape in a URL and nothing to trim.
101func newRemoteToken() (string, error) {
102 raw := make([]byte, remoteTokenBytes)
103 if _, err := rand.Read(raw); err != nil {
104 return "", fmt.Errorf("slides: generate remote token: %w", err)
105 }
106 return base64.RawURLEncoding.EncodeToString(raw), nil
107}
108
109// hashRemoteToken is the stored form. The same construction as
110// hashShareToken and written out again rather than shared, because the
111// two are separate protocol decisions that happen to agree today: a
112// change to how share links are stored must not silently change what
113// every live remote's stored hash means.
114func hashRemoteToken(token string) string {
115 sum := sha256.Sum256([]byte(token))
116 return hex.EncodeToString(sum[:])
117}
118
119// remoteTokenOK compares the presented token with the stored hash in
120// constant time. Hashes, not tokens: hashing first means the compare
121// is over two fixed-length strings, so not even the length of the
122// stored secret leaks through timing.
123//
124// An empty token is refused before anything else. Without this, a
125// session whose hash column was somehow empty would be driveable by
126// anyone posting no token at all.
127func remoteTokenOK(p Presentation, token string) bool {
128 if token == "" || p.RemoteTokenHash == "" {
129 return false
130 }
131 return subtle.ConstantTimeCompare([]byte(hashRemoteToken(token)), []byte(p.RemoteTokenHash)) == 1
132}
133
134// newCode mints a pairing code.
135func newCode() (string, error) {
136 raw := make([]byte, codeLength)
137 if _, err := rand.Read(raw); err != nil {
138 return "", fmt.Errorf("slides: generate pairing code: %w", err)
139 }
140 out := make([]byte, codeLength)
141 for i, b := range raw {
142 // The modulo bias decks.go's newSqid documents applies here
143 // too, and matters even less: the code is not a secret, it is
144 // a name a person types.
145 out[i] = codeAlphabet[int(b)%len(codeAlphabet)]
146 }
147 return string(out), nil
148}
149
150// livePresentations scopes a query to the sessions that are still
151// running: not ended, and not older than the TTL. Every read that
152// looks for a session to USE goes through it; presentationFor is the
153// one place that reads outside it, because telling somebody their talk
154// is over needs the row that says so.
155func (a *app) livePresentations(r *http.Request) *gorm.DB {
156 return a.db.G.WithContext(r.Context()).Model(&Presentation{}).
157 Where("ended_at IS NULL AND started_at > ?", time.Now().UTC().Add(-presentTTL))
158}
159
160// presentationOver reports whether p has finished, either way it can.
161func presentationOver(p Presentation) bool {
162 return p.EndedAt != nil || time.Since(p.StartedAt) > presentTTL
163}
164
165// eventFor is the one conversion between the column and the wire.
166//
167// Presentation.Slide is a 0-based index into the document; every URL
168// in this app and every stream event carries the 1-based number a
169// person sees (?slide=3 is the third slide). Both conventions are
170// right in their own place and the seam between them is here, so no
171// other function in the app has to hold both in its head.
172//
173// A Positional session's event carries its absolute position too
174// (presenting_position.go); one begun before that carries the three
175// fields it always did.
176func eventFor(p Presentation) present.Event {
177 e := present.Event{
178 Slide: p.Slide + 1,
179 Blackout: p.Blackout,
180 Ended: p.EndedAt != nil,
181 }
182 if p.Positional {
183 e.Position = &present.Position{
184 SlideID: p.SlideID, Step: p.Step, Mode: p.Mode, Seq: p.Seq, TimerAt: timerMillis(p.TimerAt),
185 }
186 }
187 return e
188}
189
190// timerMillis is when a talk's timer started, in Unix ms as the wire
191// says it, or nil while it waits for the first press.
192func timerMillis(at *time.Time) *int64 {
193 if at == nil {
194 return nil
195 }
196 ms := at.UnixMilli()
197 return &ms
198}
199
200// --- resolving a session from a request ---
201
202// presentationFor resolves the {session} sqid, answering for itself:
203// 404 for a session that does not exist, 410 for one that is over.
204//
205// The two answers say different things on purpose. A talk that
206// finished is GONE — somebody following a link to yesterday's session
207// should be told it ended rather than left wondering whether they
208// typed the address wrong. A sqid that never existed is a 404, and a
209// dead pairing code is a 404 too (remotePair), because neither should
210// confirm anything to a stranger who is guessing.
211func (a *app) presentationFor(w http.ResponseWriter, r *http.Request) (Presentation, bool) {
212 p, ok := a.presentationRow(w, r)
213 if !ok {
214 return Presentation{}, false
215 }
216 // Team mode: the talk stands on its presenter's reach to the deck
217 // (team_present.go). Gone ends it, and it is over like any other.
218 switch reach, _ := a.presentationStands(r.Context(), p); reach {
219 case presenterGone:
220 a.gone(w, r)
221 return Presentation{}, false
222 case presenterUnknown:
223 a.teamUnavailable(w, r)
224 return Presentation{}, false
225 }
226 return p, true
227}
228
229// presentationRow is presentationFor before team mode's presenter check:
230// the row, 404 or 410. The projector's stream starts here, because it
231// holds rather than refuses while the presenter's standing is unknown
232// (streamPresentation).
233func (a *app) presentationRow(w http.ResponseWriter, r *http.Request) (Presentation, bool) {
234 var p Presentation
235 err := a.db.G.WithContext(r.Context()).
236 Where("sqid = ?", chi.URLParam(r, "session")).Take(&p).Error
237 switch {
238 case err == nil:
239 case errors.Is(err, gorm.ErrRecordNotFound):
240 a.notFound(w, r)
241 return Presentation{}, false
242 default:
243 a.fail(w, r, "load presentation", err)
244 return Presentation{}, false
245 }
246 if presentationOver(p) {
247 a.gone(w, r)
248 return Presentation{}, false
249 }
250 return p, true
251}
252
253// gone renders the 410: the app's own error page, with words of its
254// own, because the framework catalog words five statuses and this is
255// not one of them (ui/partials/error-page.html).
256func (a *app) gone(w http.ResponseWriter, r *http.Request) {
257 a.errorPage(w, r, http.StatusGone, kindStatus, "")
258}
259
260// deckOf loads the deck a session is presenting. No visibility check:
261// the session sqid IS the capability that reached this handler, the
262// same way a share link is (share.go's sharedDeck).
263func (a *app) deckOf(w http.ResponseWriter, r *http.Request, p Presentation) (Deck, bool) {
264 var d Deck
265 err := a.db.G.WithContext(r.Context()).Take(&d, p.DeckID).Error
266 switch {
267 case err == nil:
268 return d, true
269 case errors.Is(err, gorm.ErrRecordNotFound):
270 a.notFound(w, r)
271 default:
272 a.fail(w, r, "load a presented deck", err)
273 }
274 return Deck{}, false
275}
276
277// admittedPresenter is who is signed in on this request, as an actor
278// string, or "" for nobody, put through the same admission every
279// signed-in route makes: currentUser, the allowlist recheck (and
280// offboarding), the team roster, a Home identity. The cookie is a
281// capability on the /p/ routes (mayDrive, presentPair), so it must not
282// be a weaker one than on the routes behind RequireSession.
283//
284// Every screen in this file is mounted outside the signed-in group, so
285// the session is read from the cookie here (as optionalViewer reads it)
286// and handed to currentUser as RequireSession would hand it. Nobody
287// being signed in is the ordinary case (a phone, a projector), not a
288// failure.
289//
290// answered is true when currentUser has already written the answer: an
291// address no longer admitted has been signed out and its talks ended
292// (auth.go's offboard), or team standing could not be read. The caller
293// writes nothing more.
294func (a *app) admittedPresenter(w http.ResponseWriter, r *http.Request) (actor string, answered bool) {
295 if a.auth == nil || a.sessions == nil {
296 return "", false
297 }
298 s, ok := a.sessions.From(r)
299 if !ok || s.Subject == "" {
300 return "", false
301 }
302 u, outcome := a.currentUser(w, sessions.WithSession(r, s))
303 switch outcome {
304 case sessionOK:
305 return actorFor(u), false
306 case sessionOffboarded:
307 return "", true
308 }
309 return "", false
310}
311
312// --- POST /d/{sqid}/present ---
313
314// startPresenting opens a session for a deck, or picks up the one this
315// person already has open on it, and lands them on the session's own
316// slide (S12).
317//
318// Reachable by anybody who can open the deck (visibleDecks), not the
319// owner alone: presenting is reading out loud, and a team member who
320// can read a deck can read it to a room.
321//
322// One live session per deck per presenter (spec §3.4). Pressing
323// Present again rejoins the row and changes nothing on it, so a phone
324// already paired stays paired (S19): the presenter drives by being
325// signed in (presenting_position.go's mayDrive), and a new session
326// starts with no remote token at all until a phone is paired.
327func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) {
328 u, ok := a.viewer(w, r)
329 if !ok {
330 return
331 }
332 d, ok := a.deckFor(w, r, u)
333 if !ok {
334 return
335 }
336
337 actor := actorFor(u)
338 g := a.deckGuard(r.Context(), u, d)
339
340 var p Presentation
341 err := a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor).
342 Order("started_at DESC").Take(&p).Error
343 switch {
344 case err == nil:
345 // Rejoining: the row keeps its sqid, its position, its code
346 // and its token, so every page and phone already on the talk
347 // stays on it.
348 case errors.Is(err, gorm.ErrRecordNotFound):
349 p, err = a.createPresentation(r, d, actor, "", g)
350 if a.guardRefused(w, r, err) {
351 return
352 }
353 if err != nil {
354 a.fail(w, r, "start a presentation", err)
355 return
356 }
357 default:
358 a.fail(w, r, "look for a live presentation", err)
359 return
360 }
361
362 http.Redirect(w, r, "/p/"+p.Sqid, http.StatusSeeOther)
363}
364
365// createPresentation writes the row, retrying on a code already in use
366// by another live session and on the vanishingly unlikely sqid
367// collision the unique index would refuse.
368//
369// g is the team-mode write guard for the presenter on d, around the
370// insert; nil outside team mode.
371//
372// Every new session is Positional, starting where deck.Start says. An
373// empty token stores no hash, which no token matches (remoteTokenOK).
374func (a *app) createPresentation(r *http.Request, d Deck, actor, token string, g writeGuard) (Presentation, error) {
375 h, view, err := a.openDeck(r.Context(), d)
376 if err != nil {
377 return Presentation{}, err
378 }
379 h.Close(r.Context())
380 start, slide := startPosition(view)
381 tokenHash := ""
382 if token != "" {
383 tokenHash = hashRemoteToken(token)
384 }
385 for attempt := 0; attempt < maxCodeAttempts; attempt++ {
386 sqid, err := newSqid()
387 if err != nil {
388 return Presentation{}, err
389 }
390 code, err := newCode()
391 if err != nil {
392 return Presentation{}, err
393 }
394 var taken int64
395 if err := a.livePresentations(r).Where("code = ?", code).Count(&taken).Error; err != nil {
396 return Presentation{}, err
397 }
398 if taken > 0 {
399 continue
400 }
401 p := Presentation{
402 Sqid: sqid,
403 DeckID: d.ID,
404 Actor: actor,
405 Code: code,
406 RemoteTokenHash: tokenHash,
407 StartedAt: time.Now().UTC(),
408 Slide: slide,
409 SlideID: start.Slide,
410 Mode: string(start.Mode),
411 Positional: true,
412 }
413 err = a.guarded(r.Context(), g, func(db *gorm.DB) error { return db.Create(&p).Error })
414 if err == nil {
415 return p, nil
416 }
417 // A typed check, not a search for "UNIQUE" in the message:
418 // rastrillo's db.Open sets GORM's TranslateError, so a
419 // violated index arrives as gorm.ErrDuplicatedKey whatever the
420 // driver phrased it as — and a string match is a retry loop
421 // resting on wording nobody in this repo controls.
422 if !errors.Is(err, gorm.ErrDuplicatedKey) {
423 return Presentation{}, err
424 }
425 }
426 return Presentation{}, errors.New("slides: no free pairing code after several attempts")
427}
428
429// --- the pages ---
430
431// presentShellFor is the chrome of the four capability screens: none.
432// They are reachable with no session at all — a projector, a phone, a
433// stranger holding a follow link — and shown full screen, on a lectern
434// or in somebody's hand, so they take no bar (shared chrome spec §12.1,
435// Slides). They used to carry the share-link shell, which showed a
436// signed-in presenter "Account → Sign in".
437func presentShellFor(r *http.Request, parts ...string) shell {
438 return shell{Frame: Frame{
439 Chrome: chrome.Bar{App: chrome.App{Name: appName}},
440 TitleParts: parts,
441 Theme: chrome.ThemeAttr(chrome.Appearance(r)),
442 Bare: true,
443 }}
444}
445
446// commandButton is one control: an op, and what it says. Each renders
447// as its own <form>, which is what makes the remote work with scripts
448// off (spec §8).
449type commandButton struct {
450 Op string
451 Label string
452 Slide string
453 // Press is the press id the form sends (presenting_position.go),
454 // fresh on every render, so a form resubmitted by a reload counts
455 // once and each new page makes new presses.
456 Press string
457}
458
459// controls is the shared button block (templates/present_controls.html).
460// A pointer on a page's view data, so a page with nobody entitled to
461// drive simply has none rather than rendering dead buttons.
462type controls struct {
463 Action string
464 Token string
465 Buttons []commandButton
466}
467
468// surfacePage is the fullscreen surface: GET /p/{session}, and the
469// audience's follow view, which is the same page read-only.
470type surfacePage struct {
471 shell
472 Title string
473 // Session is the presentation's sqid, and is EMPTY on the
474 // audience's follow view (codex 5): a share-link holder must not
475 // learn the address the projector is on, because that address is a
476 // capability their own revocation cannot reach.
477 Session string
478 // StreamHref and FragmentHref are the two URLs static/present.js
479 // uses, handed down rather than built in the browser — so which
480 // capability a surface reads under is decided here, once, by the
481 // handler that knows. FragmentHref carries {n} where the slide
482 // number goes.
483 StreamHref string
484 FragmentHref string
485 // Token is present only for a request entitled to drive, and it is
486 // what the script reads to send a keystroke. A page without it is
487 // read-only in the markup AND in the script, unless Drives says the
488 // presenter's own cookie drives it (data-drives).
489 Token string
490 Drives bool
491
492 // SlideID is the drawn slide's id on a session with a position
493 // (data-slide-id): a slide is known by it, since the number of a
494 // slide can be another slide's after a reorder (static/present.js).
495 SlideID string
496
497 HasSlide bool
498 Slide template.HTML
499 // Scenes is what the slide's scene blocks run (scene_pages.go), nil
500 // when it shows none.
501 Scenes map[string]pageScene
502 // Now is the 1-based slide number events carry (eventFor), and
503 // Total the slides a reader may see. Place and Places are what the
504 // counter and the progress bar say: for a session with a position,
505 // the slide's place in the talk being given (talkPlace).
506 Now int
507 Total int
508 Place int
509 Places int
510 Counter string
511 // Stepped marks a session with a position, whose slide is drawn at
512 // Step (the surface's data-step), so static/present.js can apply
513 // the next step in place. Mode is the talk being given (data-mode):
514 // a change of it refreshes the counter and the bar.
515 Stepped bool
516 Step int
517 Mode string
518 // Announce is what the surface's live region says when it changes
519 // to this slide in place (static/present.js): "Slide 3 of 12:
520 // Revenue".
521 Announce string
522
523 Blackout bool
524 BlackoutLabel string
525
526 ProgressLabel string
527 PagerLabel string
528 PrevLabel string
529 NextLabel string
530 PrevHref string
531 NextHref string
532 Controls *controls
533
534 NotesHref string
535 NotesLabel string
536
537 // Bundle is set on the slide window of a session with a position,
538 // for whoever may drive it: the presenter bundle
539 // (fixtures/slide-window.mjs) moves it at once, from the talk it
540 // holds in memory (TalkHref), instead of static/present.js. Its
541 // sentences come down unfilled: the counter, what the live region
542 // says, and that the window is waiting for the network. P opens the
543 // presenter window (PresenterHref).
544 Bundle string
545 TalkHref string
546 PresenterHref string
547 ProgressWords string
548 AnnounceWords string
549 WaitingWords string
550 // The empty talk's state, hidden until every slide is parked or
551 // gone while the window is open (slide-window.mjs).
552 TalkEmptyTitle string
553 TalkEmptyBody string
554
555 // Refresh is the follow view's scriptless heartbeat: a meta
556 // refresh, so an audience with no JavaScript still moves with the
557 // presenter. Off on the presenter's own surface, where a refresh
558 // mid-sentence would be worse than a stale slide.
559 Refresh bool
560 BackHref string
561 BackLabel string
562
563 EmptyTitle string
564 EmptyBody string
565}
566
567// presenterPage is GET /p/{session}/notes: the second screen.
568type presenterPage struct {
569 shell
570 Title string
571 DeckTitle string
572 Session string
573 Token string
574 // Drives: the signed-in presenter drives this view by their cookie
575 // (data-drives), with no token.
576 Drives bool
577
578 Now int
579 Counter string
580 CurrentLabel string
581 Current template.HTML
582 NextLabel string
583 Next template.HTML
584 HasNext bool
585 // Mode: see presented.
586 Mode string
587
588 NotesLabel string
589 Notes template.HTML
590 NoNotes string
591
592 Blackout bool
593 BlackoutLabel string
594
595 ClockLabel string
596 Clock string
597 Started string
598 Elapsed string
599 StartedAt int64
600 // ElapsedTemplate is the catalog's own pattern, unsubstituted, so
601 // static/present.js can keep the elapsed line ticking without a
602 // sentence of English being written in a .js file.
603 ElapsedTemplate string
604
605 // The pairing block, rendered once: only for the presenter's own
606 // session, and only on the one request that carries the token.
607 Pair *pairing
608 Controls *controls
609 StageHref string
610 StageLabel string
611 DeckHref string
612 DeckLabel string
613 ToolsLabel string
614}
615
616// remotePage is GET /p/{session}/remote: the phone.
617type remotePage struct {
618 shell
619 Title string
620 DeckTitle string
621 Session string
622
623 Now int
624 Counter string
625 CurrentLabel string
626 Current template.HTML
627 NextLabel string
628 Next template.HTML
629 HasNext bool
630 // Stepped, Step, StepCount, Mode and SlideID: see presented.
631 Stepped bool
632 Step int
633 StepCount string
634 Mode string
635 SlideID string
636
637 NotesLabel string
638 Notes template.HTML
639 NoNotes string
640
641 Blackout bool
642 BlackoutLabel string
643
644 Controls *controls
645 PresenterHref string
646 PresenterLabel string
647 ToolsLabel string
648}
649
650// pairPage is GET /r/{code}: the way in for a code somebody typed.
651type pairPage struct {
652 shell
653 Title string
654 Body string
655 Action string
656 Code string
657 CodeLabel string
658 CodeHint string
659 TokenLabel string
660 TokenHint string
661 Submit string
662 Error string
663}
664
665// --- GET /p/{session} ---
666
667// presentSurface is the fullscreen surface — the projector.
668//
669// Three requests land here and it answers all three from one path:
670// the page itself, the same page with ?slide=N for a scriptless
671// reader, and ?fragment=1 for the script, which swaps the slide
672// without reloading. The fragment is the SAME render as the page's
673// own, deliberately: two renderers for one slide is two ways for the
674// projector to be wrong.
675func (a *app) presentSurface(w http.ResponseWriter, r *http.Request) {
676 p, ok := a.presentationFor(w, r)
677 if !ok {
678 return
679 }
680 d, ok := a.deckOf(w, r, p)
681 if !ok {
682 return
683 }
684 a.renderSurface(w, r, d, p, surfaceOptions{
685 token: r.URL.Query().Get("t"),
686 // The projector's own address, which is the address it is
687 // already on: nothing is disclosed by saying so.
688 base: "/p/" + p.Sqid,
689 session: p.Sqid,
690 stream: "/p/" + p.Sqid + "/stream",
691 //nolint:goconst // one URL, spelled where it is decided
692 fragment: "/p/" + p.Sqid + "?slide={n}&fragment=1",
693 })
694}
695
696// surfaceOptions is what differs between the projector and the
697// audience's follow view — which is very little, which is the point.
698type surfaceOptions struct {
699 // token, when it is the session's, makes the pager a pair of
700 // command forms rather than a pair of local links.
701 token string
702 // base is the capability this surface reads under: "/p/{sqid}" for
703 // a projector, "/s/{token}" for somebody following a share link.
704 // The pictures hang off it (assetBaseFor), so an <img> on this page
705 // is fetchable by exactly whoever is looking at it and by nobody
706 // else.
707 base string
708 // session is the sqid, and is deliberately not derived from p:
709 // putting it on the page is a disclosure, and the follow view does
710 // not make it (codex 5).
711 session string
712 // stream and fragment are the two URLs the script uses. fragment
713 // carries {n} where the slide number goes.
714 stream string
715 fragment string
716 // follow marks the audience's copy: a meta refresh, a way back to
717 // browsing, and never a control.
718 follow bool
719 backHref string
720 backLabel string
721}
722
723func (a *app) renderSurface(w http.ResponseWriter, r *http.Request, d Deck, p Presentation, opt surfaceOptions) {
724 // Who drives from here is decided first: the presenter's cookie is
725 // put through admission (mayDrive), which may answer for itself.
726 // The follow view never drives.
727 drives := false
728 if !opt.follow {
729 var answered bool
730 if drives, _, answered = a.mayDrive(w, r, p, opt.token); answered {
731 return
732 }
733 }
734 h, view, err := a.openDeck(r.Context(), d)
735 if err != nil {
736 a.fail(w, r, "open deck", err)
737 return
738 }
739 defer h.Close(r.Context())
740 view = view.ForReaders()
741
742 q := r.URL.Query()
743 sh := presentShellFor(r, view.Meta.Title)
744 // The projector and the follow view swap slides in place
745 // (static/present.js), so the gate waits for every family of the
746 // deck before the first one is shown, and a swap that brings in
747 // another (the deck changed mid-talk) waits for it too.
748 sh.Fonts = newFontGate(r, view, opt.base)
749 page := surfacePage{
750 shell: sh,
751 Title: view.Meta.Title,
752 Session: opt.session,
753 StreamHref: opt.stream,
754 FragmentHref: opt.fragment,
755 }
756 if len(view.Slides) == 0 {
757 page.EmptyTitle = rastrillo.T(r, "slides.viewer.empty.title")
758 page.EmptyBody = rastrillo.T(r, "slides.viewer.empty.body")
759 render(w, "present", page)
760 return
761 }
762
763 // The session's own slide is what this shows, unless the request
764 // named one: ?slide=N is how a scriptless reader pages, and how
765 // the script fetches the slide an event just named.
766 index := clampSlide(p.Slide, len(view.Slides))
767 live := true
768 // A session with a position draws its slide at a step: the
769 // session's, or the one ?step=k names (stepPlace).
770 var reveal *int
771 if p.Positional {
772 at, ok := stepPlace(view, p, q)
773 if !ok {
774 a.notFound(w, r)
775 return
776 }
777 index, live, reveal = at.index, at.live, &at.step
778 } else if raw := q.Get("slide"); raw != "" {
779 n, ok := slideIndex(raw, len(view.Slides))
780 if !ok {
781 a.notFound(w, r)
782 return
783 }
784 index, live = n, false
785 }
786
787 // Neither the projector nor the audience has a session, so the
788 // pictures go under whichever capability this surface IS
789 // (assets.go): the presentation's for a projector, the share
790 // link's for a follower.
791 html, err := slidehtml.SlideWith(view, index, slidehtml.Desktop,
792 slidehtml.Options{AssetBase: assetBaseFor(opt.base), Reveal: reveal, QRAlt: qrAlt(r),
793 QR: a.followCodes(r.Context(), d, view, opt.base)})
794 if err != nil {
795 a.fail(w, r, "render slide", err)
796 return
797 }
798 if q.Get("fragment") == "1" {
799 // The bare slide, for the script's swap. No layout, and no
800 // cache: it is one moment of a live session.
801 w.Header().Set("Content-Type", "text/html; charset=utf-8")
802 w.Header().Set("Cache-Control", "no-store")
803 io.WriteString(w, string(html))
804 return
805 }
806
807 page.HasSlide = true
808 page.Slide = html
809 page.Scenes = scenesShown(view, opt.base, index)
810 page.Now = index + 1
811 page.Total = len(view.Slides)
812 page.Place, page.Places = page.Now, page.Total
813 if reveal != nil {
814 mode := positionOf(p).Mode
815 page.Stepped, page.Step, page.Mode = true, *reveal, string(mode)
816 page.SlideID = view.Slides[index].ID
817 page.Place, page.Places = talkPlace(view, mode, index)
818 }
819 page.Counter = rastrillo.Tf(r, "slides.present.progress", "n", page.Place, "total", page.Places)
820 page.Announce = rastrillo.Tf(r, "slides.slide.announce", "n", page.Now, "total", page.Total, "title", slideLabel(r, view.Slides[index], page.Now))
821 page.ProgressLabel = rastrillo.T(r, "slides.present.progress.label")
822 page.PagerLabel = rastrillo.T(r, "slides.viewer.pager")
823 page.PrevLabel = rastrillo.T(r, "slides.present.prev")
824 page.NextLabel = rastrillo.T(r, "slides.present.next")
825 // Blacking out is the session's state, so it applies to the
826 // session's own slide and not to a page somebody scrolled off to.
827 page.Blackout = p.Blackout && live
828 page.BlackoutLabel = rastrillo.T(r, "slides.present.blacked")
829
830 switch {
831 case opt.follow:
832 page.Refresh = true
833 page.BackHref = opt.backHref
834 page.BackLabel = opt.backLabel
835 case drives:
836 // Whoever holds the remote drives the session from here too:
837 // the pager posts commands, so the projector's own next button
838 // moves the talk rather than only this browser. So does the
839 // presenter, signed in (S19): the slide window they open from
840 // the presenter window drives, and so does the one a talk
841 // begun before positions rejoins on (Present again).
842 token := ""
843 if remoteTokenOK(p, opt.token) {
844 token = opt.token
845 }
846 page.Token = token
847 page.Drives = true
848 back, next := pressLabels(r, p)
849 page.Controls = &controls{
850 Action: "/p/" + p.Sqid + "/command",
851 Token: token,
852 Buttons: withPressIDs([]commandButton{
853 {Op: "prev", Label: back},
854 {Op: "next", Label: next},
855 }),
856 }
857 page.NotesHref = "/p/" + p.Sqid + "/notes"
858 if token != "" {
859 page.NotesHref += "?t=" + url.QueryEscape(token)
860 }
861 page.NotesLabel = rastrillo.T(r, "slides.present.notes.title")
862 if p.Positional {
863 page.Bundle = presenterBundlePath()
864 page.TalkHref = "/p/" + p.Sqid + "/talk"
865 if token != "" {
866 page.TalkHref += "?t=" + url.QueryEscape(token)
867 }
868 page.PresenterHref = page.NotesHref
869 page.ProgressWords = rastrillo.T(r, "slides.present.progress")
870 page.AnnounceWords = rastrillo.T(r, "slides.slide.announce")
871 page.WaitingWords = rastrillo.T(r, "slides.present.waiting")
872 page.TalkEmptyTitle = rastrillo.T(r, "slides.present.empty.title")
873 page.TalkEmptyBody = rastrillo.T(r, "slides.present.empty.body")
874 }
875 default:
876 // A watcher may page through the deck on their own screen
877 // without moving anybody else's: ordinary links, no session
878 // write, and the next event puts them back on the presenter's
879 // slide.
880 if index > 0 {
881 page.PrevHref = opt.base + "?slide=" + strconv.Itoa(index)
882 }
883 if index+1 < len(view.Slides) {
884 page.NextHref = opt.base + "?slide=" + strconv.Itoa(index+2)
885 }
886 }
887 render(w, "present", page)
888}
889
890// clampSlide keeps a stored index inside a deck that may have lost
891// slides since the session started. A deck that shrank mid-talk is a
892// real thing an editor can do, and the surface showing the last slide
893// beats it showing a 500.
894func clampSlide(index, count int) int {
895 if index < 0 || count == 0 {
896 return 0
897 }
898 if index >= count {
899 return count - 1
900 }
901 return index
902}
903
904// --- GET /p/{session}/notes ---
905
906// presenterNotes is the presenter view: what is on screen, what is
907// next, the notes, the clock, and — once — how to pair a phone.
908//
909// Who may read it: whoever may drive the talk (mayDrive), the
910// presenter's own signed-in session or whoever holds the remote token.
911// Never the session sqid alone, which is the address that goes on a
912// projector.
913//
914// A session with a position gets the presenter window
915// (presenter_window.go); one begun before keeps this view.
916func (a *app) presenterNotes(w http.ResponseWriter, r *http.Request) {
917 p, ok := a.presentationFor(w, r)
918 if !ok {
919 return
920 }
921 token := r.URL.Query().Get("t")
922 drives, actor, answered := a.mayDrive(w, r, p, token)
923 if answered {
924 return
925 }
926 if !drives {
927 a.notFound(w, r)
928 return
929 }
930 if p.Positional {
931 a.presenterWindow(w, r, p, token)
932 return
933 }
934 holder := remoteTokenOK(p, token)
935 // Let in by the cookie (mayDrive's actor), or, holding the token
936 // too, signed in as the presenter as well.
937 presenter := actor != ""
938 if holder && p.Actor != "" {
939 signedIn, answered := a.admittedPresenter(w, r)
940 if answered {
941 return
942 }
943 presenter = signedIn == p.Actor
944 }
945 d, ok := a.deckOf(w, r, p)
946 if !ok {
947 return
948 }
949 h, view, err := a.openDeck(r.Context(), d)
950 if err != nil {
951 a.fail(w, r, "open deck", err)
952 return
953 }
954 defer h.Close(r.Context())
955 view = view.ForReaders()
956
957 now := time.Now().UTC()
958 page := presenterPage{
959 shell: presentShellFor(r, rastrillo.T(r, "slides.present.notes.title"), view.Meta.Title),
960 Title: rastrillo.T(r, "slides.present.notes.title"),
961 DeckTitle: view.Meta.Title,
962 Session: p.Sqid,
963
964 CurrentLabel: rastrillo.T(r, "slides.present.current"),
965 NextLabel: rastrillo.T(r, "slides.present.next.label"),
966 NotesLabel: rastrillo.T(r, "slides.viewer.notes"),
967 NoNotes: rastrillo.T(r, "slides.notes.none"),
968
969 Blackout: p.Blackout,
970 BlackoutLabel: rastrillo.T(r, "slides.present.blacked"),
971
972 ClockLabel: rastrillo.T(r, "slides.present.clock"),
973 Clock: clockWords(now),
974 Started: rastrillo.Tf(r, "slides.present.started", "when", clockWords(p.StartedAt)),
975 Elapsed: rastrillo.Tf(r, "slides.present.elapsed", "n", int(now.Sub(p.StartedAt).Minutes())),
976 StartedAt: p.StartedAt.Unix(),
977 // T rather than Tf: the pattern with its {n} intact.
978 ElapsedTemplate: rastrillo.T(r, "slides.present.elapsed"),
979
980 DeckHref: "/d/" + d.Sqid,
981 DeckLabel: rastrillo.T(r, "slides.deck.back"),
982 ToolsLabel: rastrillo.T(r, "slides.viewer.tools"),
983 }
984 shown := presentedFor(r, view, p)
985 page.Now, page.Counter, page.Current = shown.Now, shown.Counter, shown.Current
986 page.Next, page.HasNext, page.Notes = shown.Next, shown.HasNext, shown.Notes
987 page.Mode = shown.Mode
988
989 // The controls are the driver's: the phone's token, or the
990 // presenter's own cookie on a talk they rejoined (Present again
991 // issues no token, so a talk begun before positions would otherwise
992 // come back as a watcher's).
993 switch {
994 case holder:
995 page.Token = token
996 page.Controls = commandControls(r, p, token)
997 page.StageHref = "/p/" + p.Sqid + "?t=" + url.QueryEscape(token)
998 page.StageLabel = rastrillo.T(r, "slides.present.stage")
999 case presenter:
1000 page.Drives = true
1001 page.Controls = commandControls(r, p, "")
1002 page.StageHref = "/p/" + p.Sqid
1003 page.StageLabel = rastrillo.T(r, "slides.present.stage")
1004 }
1005 // Once, and only to the person presenting: the token is in this
1006 // URL, so the pairing block is what that one request is FOR.
1007 // Coming back to the page without it — from a bookmark, from the
1008 // browser's history — shows the talk and no capability.
1009 if holder && presenter {
1010 pair, err := a.pairingFor(r, p, token)
1011 if err != nil {
1012 a.fail(w, r, "render the pairing QR", err)
1013 return
1014 }
1015 page.Pair = &pair
1016 }
1017 render(w, "present_notes", page)
1018}
1019
1020// pairing is what pairs a phone: the code, the remote's address with
1021// the token in it, and the QR that carries both
1022// (templates/present_pairing.html).
1023type pairing struct {
1024 Title string
1025 Body string
1026 CodeLabel string
1027 Code string
1028 URLLabel string
1029 RemoteURL string
1030 QR template.HTML
1031}
1032
1033// pairingFor is p's pairing with token, in the request's language.
1034func (a *app) pairingFor(r *http.Request, p Presentation, token string) (pairing, error) {
1035 remoteURL := a.cfg.Origin + "/r/" + p.Code + "?t=" + token
1036 qr, err := qrSVG(remoteURL, rastrillo.Tf(r, "slides.present.pair.qr", "code", p.Code))
1037 if err != nil {
1038 return pairing{}, err
1039 }
1040 return pairing{
1041 Title: rastrillo.T(r, "slides.present.pair.title"),
1042 Body: rastrillo.T(r, "slides.present.pair.body"),
1043 CodeLabel: rastrillo.T(r, "slides.present.pair.code"),
1044 Code: p.Code,
1045 URLLabel: rastrillo.T(r, "slides.present.pair.url"),
1046 RemoteURL: remoteURL,
1047 QR: qr,
1048 }, nil
1049}
1050
1051// --- POST /p/{session}/pair ---
1052
1053// presentPairPage is the pairing page the window's menu opens.
1054type presentPairPage struct {
1055 shell
1056 Title string
1057 Body string
1058 Pair pairing
1059}
1060
1061// presentPair pairs a phone (spec §6 "Who may drive"): a new remote
1062// token replaces the old one, which drives and reads nothing from then
1063// on, and the answer shows the new one, once.
1064//
1065// Only the presenter, signed in, may pair: never the token, which is
1066// the phone's and would otherwise let a phone pass itself on, and never
1067// the session sqid, which is on the projector. Anybody else gets the
1068// 404 every capability screen gives; a talk that is over is a 410.
1069// csrf.Protect (app.go) keeps another site from pairing through the
1070// presenter's browser, and no-store keeps the token out of every cache.
1071func (a *app) presentPair(w http.ResponseWriter, r *http.Request) {
1072 p, ok := a.presentationFor(w, r)
1073 if !ok {
1074 return
1075 }
1076 if p.Actor == "" {
1077 a.notFound(w, r)
1078 return
1079 }
1080 actor, answered := a.admittedPresenter(w, r)
1081 if answered {
1082 return
1083 }
1084 if actor != p.Actor {
1085 a.notFound(w, r)
1086 return
1087 }
1088 token, err := newRemoteToken()
1089 if err != nil {
1090 a.fail(w, r, "mint a remote token", err)
1091 return
1092 }
1093 // ended_at in the WHERE, as every write here has: pairing that
1094 // races End presenting loses rather than arming a finished talk.
1095 res := a.db.G.WithContext(r.Context()).Model(&Presentation{}).
1096 Where("id = ? AND ended_at IS NULL", p.ID).
1097 Update("remote_token_hash", hashRemoteToken(token))
1098 switch {
1099 case res.Error != nil:
1100 a.fail(w, r, "pair a phone", res.Error)
1101 return
1102 case res.RowsAffected == 0:
1103 a.gone(w, r)
1104 return
1105 }
1106 pair, err := a.pairingFor(r, p, token)
1107 if err != nil {
1108 a.fail(w, r, "render the pairing QR", err)
1109 return
1110 }
1111 d, ok := a.deckOf(w, r, p)
1112 if !ok {
1113 return
1114 }
1115 w.Header().Set("Cache-Control", "no-store")
1116 render(w, "present_pair", presentPairPage{
1117 shell: presentShellFor(r, pair.Title, d.Title),
1118 Title: pair.Title,
1119 Body: pair.Body,
1120 Pair: pair,
1121 })
1122}
1123
1124// clockWords is a wall clock a presenter can read at a glance. UTC and
1125// said so: the server has no idea what time zone the room is in, and a
1126// clock that is quietly an hour out is worse than one that names its
1127// zone. static/present.js replaces it with the browser's own local
1128// time when there is a script to do it.
1129func clockWords(t time.Time) string {
1130 return t.UTC().Format("15:04") + " UTC"
1131}
1132
1133// presented is the two slides and the notes every presenting screen
1134// shows: the one on the projector, the one coming next, and the notes
1135// for the one that is up.
1136//
1137// The two slides are PICTURES — an <img> of the session's own SVG
1138// thumbnail (thumbs.go) — and not renderings of the slide. Both
1139// screens show them small beside the notes somebody is reading while
1140// talking, and a whole live copy of a slide is a lot of DOM for a
1141// picture: two of them on a phone, re-laid-out on every rotation, over
1142// a hotel wifi. The projector at /p/{session} still gets the real
1143// rendering, because that one is the slide.
1144type presented struct {
1145 // Now is the 1-based slide these were rendered for — the number the
1146 // stream's events carry — and it goes on the page's script root as
1147 // data-slide, so static/present.js knows what it is already showing.
1148 // Without it the script took the page to be on slide 0, the first
1149 // event "moved" it, and the page reloaded itself on every load
1150 // (polish audit B3).
1151 Now int
1152 Counter string
1153 Current template.HTML
1154 Next template.HTML
1155 HasNext bool
1156 Notes template.HTML
1157 // For a session with a position: Stepped, the step it is at (the
1158 // page's data-step, so the remote reloads for a step too), and
1159 // "step 2 of 4" for a slide with presses, empty for one without.
1160 // The pictures stay the finished slides (P3). Mode is the talk being
1161 // given (the page's data-mode, so it reloads when that changes: the
1162 // counter and the slide coming next both depend on it).
1163 Stepped bool
1164 Step int
1165 StepCount string
1166 Mode string
1167 // SlideID is the slide's id, on a session with a position
1168 // (data-slide-id): present.js knows a slide by it.
1169 SlideID string
1170}
1171
1172// presentedFor builds them. A slide that will not draw leaves its half
1173// empty rather than failing the page: the presenter view is what
1174// somebody is reading WHILE talking, and half of it beats an error
1175// page.
1176func presentedFor(r *http.Request, view *deck.Deck, p Presentation) presented {
1177 count := len(view.Slides)
1178 if count == 0 {
1179 return presented{}
1180 }
1181 index := clampSlide(p.Slide, count)
1182 n, total := index+1, count
1183 next := index + 1
1184 var out presented
1185 if p.Positional {
1186 var presses int
1187 index, out.Step, presses = sessionPlace(view, p)
1188 out.Stepped = true
1189 out.SlideID = view.Slides[index].ID
1190 mode := positionOf(p).Mode
1191 out.Mode = string(mode)
1192 n, total = talkPlace(view, mode, index)
1193 next = nextInTalk(view, mode, index)
1194 if presses > 0 {
1195 out.StepCount = rastrillo.Tf(r, "slides.present.step.count", "n", out.Step, "total", presses)
1196 }
1197 }
1198 out.Now = index + 1
1199 out.Counter = rastrillo.Tf(r, "slides.present.progress", "n", n, "total", total)
1200 out.Current = slideThumbImg(r, view, p, index)
1201 if next >= 0 && next < count {
1202 out.HasNext = true
1203 out.Next = slideThumbImg(r, view, p, next)
1204 }
1205 if s := view.Slides[index]; len(s.Notes) > 0 {
1206 out.Notes = slidehtml.Notes(s.Notes)
1207 }
1208 return out
1209}
1210
1211// slideThumbImg is one small rendering: the session's thumbnail route,
1212// with the slide's own label as the alt.
1213//
1214// The alt and the picture's own <title> say the same words on purpose.
1215// A screen reader announces an image by its alt and never opens the
1216// file to find the title inside it; a person who opens the SVG on its
1217// own has only the title. Neither surface should be the one without a
1218// name.
1219//
1220// No cache-buster on the URL: the route answers
1221// `max-age=0, must-revalidate`, so a browser revalidates every time
1222// and gets a 304 for a slide that has not changed. The editor's strip
1223// carries a seq because there the src has to CHANGE for the browser to
1224// ask at all.
1225func slideThumbImg(r *http.Request, view *deck.Deck, p Presentation, index int) template.HTML {
1226 s := view.Slides[index]
1227 return template.HTML(fmt.Sprintf(
1228 `<img slides-thumb-img src="/p/%s/slides/%s.svg" alt="%s" width="1920" height="1080">`,
1229 template.HTMLEscapeString(p.Sqid),
1230 template.HTMLEscapeString(s.ID),
1231 template.HTMLEscapeString(slideLabel(r, s, index+1))))
1232}
1233
1234// commandControls is the four-button block the presenter view and the
1235// remote both carry. One function, so the two screens cannot drift on
1236// what a button is called or what it does — including the blackout
1237// label, which says which way it goes rather than lighting up.
1238func commandControls(r *http.Request, p Presentation, token string) *controls {
1239 blackout := rastrillo.T(r, "slides.present.blackout")
1240 if p.Blackout {
1241 blackout = rastrillo.T(r, "slides.present.unblackout")
1242 }
1243 back, next := pressLabels(r, p)
1244 return &controls{
1245 Action: "/p/" + p.Sqid + "/command",
1246 Token: token,
1247 Buttons: withPressIDs([]commandButton{
1248 {Op: "prev", Label: back},
1249 {Op: "next", Label: next},
1250 {Op: "blackout", Label: blackout},
1251 {Op: "end", Label: rastrillo.T(r, "slides.present.end")},
1252 }),
1253 }
1254}
1255
1256// --- GET /p/{session}/remote ---
1257
1258// remote is the phone: the slide that is up, the one coming, the
1259// notes, and four buttons big enough to hit without looking.
1260//
1261// The token is the whole permission, so a wrong one is a 404 like
1262// every other capability in this app.
1263func (a *app) remote(w http.ResponseWriter, r *http.Request) {
1264 p, ok := a.presentationFor(w, r)
1265 if !ok {
1266 return
1267 }
1268 token := r.URL.Query().Get("t")
1269 if !remoteTokenOK(p, token) {
1270 a.notFound(w, r)
1271 return
1272 }
1273 d, ok := a.deckOf(w, r, p)
1274 if !ok {
1275 return
1276 }
1277 h, view, err := a.openDeck(r.Context(), d)
1278 if err != nil {
1279 a.fail(w, r, "open deck", err)
1280 return
1281 }
1282 defer h.Close(r.Context())
1283 view = view.ForReaders()
1284
1285 page := remotePage{
1286 shell: presentShellFor(r, rastrillo.T(r, "slides.remote.title"), view.Meta.Title),
1287 Title: rastrillo.T(r, "slides.remote.title"),
1288 DeckTitle: view.Meta.Title,
1289 Session: p.Sqid,
1290 CurrentLabel: rastrillo.T(r, "slides.present.current"),
1291 NextLabel: rastrillo.T(r, "slides.present.next.label"),
1292 NotesLabel: rastrillo.T(r, "slides.viewer.notes"),
1293 NoNotes: rastrillo.T(r, "slides.notes.none"),
1294 Blackout: p.Blackout,
1295 BlackoutLabel: rastrillo.T(r, "slides.present.blacked"),
1296 Controls: commandControls(r, p, token),
1297 PresenterHref: "/p/" + p.Sqid + "/notes?t=" + url.QueryEscape(token),
1298 PresenterLabel: rastrillo.T(r, "slides.present.notes.title"),
1299 ToolsLabel: rastrillo.T(r, "slides.viewer.tools"),
1300 }
1301 shown := presentedFor(r, view, p)
1302 page.Now, page.Counter, page.Current = shown.Now, shown.Counter, shown.Current
1303 page.Next, page.HasNext, page.Notes = shown.Next, shown.HasNext, shown.Notes
1304 page.Stepped, page.Step, page.StepCount = shown.Stepped, shown.Step, shown.StepCount
1305 page.SlideID = shown.SlideID
1306 page.Mode = shown.Mode
1307 render(w, "remote", page)
1308}
1309
1310// --- GET /r/{code} ---
1311
1312// remotePair is where a scanned QR and a typed code both land.
1313//
1314// With the token in the URL — the QR carries both halves — it is a
1315// redirect to the remote and nothing else. Without it, it is a form
1316// asking for the code and the key, because the code alone is not a
1317// capability and this page must not pretend otherwise.
1318func (a *app) remotePair(w http.ResponseWriter, r *http.Request) {
1319 q := r.URL.Query()
1320 code := strings.ToUpper(strings.TrimSpace(chi.URLParam(r, "code")))
1321 token := q.Get("t")
1322
1323 // A code typed into the form arrives as a query on whatever code's
1324 // page the form was rendered on, so the form's own answer is a
1325 // redirect to the page for the code that was typed. That is what
1326 // lets one route serve both the scan and the typing.
1327 if typed := strings.ToUpper(strings.TrimSpace(q.Get("code"))); typed != "" && typed != code {
1328 if !validCode(typed) {
1329 a.notFound(w, r)
1330 return
1331 }
1332 to := "/r/" + typed
1333 if token != "" {
1334 to += "?t=" + url.QueryEscape(token)
1335 }
1336 http.Redirect(w, r, to, http.StatusSeeOther)
1337 return
1338 }
1339
1340 var p Presentation
1341 err := a.livePresentations(r).Where("code = ?", code).Order("started_at DESC").Take(&p).Error
1342 switch {
1343 case err == nil:
1344 case errors.Is(err, gorm.ErrRecordNotFound):
1345 // A dead code is a 404, never a 410: "this code was real
1346 // yesterday" is not something to tell somebody guessing.
1347 a.notFound(w, r)
1348 return
1349 default:
1350 a.fail(w, r, "resolve a pairing code", err)
1351 return
1352 }
1353
1354 if token != "" && remoteTokenOK(p, token) {
1355 http.Redirect(w, r, "/p/"+p.Sqid+"/remote?t="+url.QueryEscape(token), http.StatusSeeOther)
1356 return
1357 }
1358
1359 page := pairPage{
1360 shell: presentShellFor(r, rastrillo.T(r, "slides.remote.pair.title")),
1361 Title: rastrillo.T(r, "slides.remote.pair.title"),
1362 Body: rastrillo.T(r, "slides.remote.pair.body"),
1363 Action: "/r/" + code,
1364 Code: code,
1365 CodeLabel: rastrillo.T(r, "slides.remote.pair.code"),
1366 CodeHint: rastrillo.T(r, "slides.remote.pair.code.hint"),
1367 TokenLabel: rastrillo.T(r, "slides.remote.pair.token"),
1368 TokenHint: rastrillo.T(r, "slides.remote.pair.token.hint"),
1369 Submit: rastrillo.T(r, "slides.remote.pair.submit"),
1370 }
1371 if token != "" {
1372 // The code is live and the key is not its own: say so on the
1373 // form rather than answering 404, which would send somebody
1374 // mistyping a key round the houses.
1375 page.Error = rastrillo.T(r, "slides.remote.pair.error")
1376 w.WriteHeader(http.StatusUnprocessableEntity)
1377 }
1378 render(w, "remote_pair", page)
1379}
1380
1381// validCode keeps a typed code inside the alphabet before it becomes a
1382// URL: the redirect above builds a path out of it.
1383func validCode(code string) bool {
1384 if len(code) != codeLength {
1385 return false
1386 }
1387 for _, c := range code {
1388 if !strings.ContainsRune(codeAlphabet, c) {
1389 return false
1390 }
1391 }
1392 return true
1393}
1394
1395// --- GET /p/{session}/stream ---
1396
1397// The stream's timings, and the reasons, are Docs'
1398// (internal/docs/stream.go): a per-write deadline because rastrillo
1399// serve leaves WriteTimeout off for exactly this handler's sake, a
1400// heartbeat because it is what makes that deadline ever fire, and a
1401// TTL because platform hibernation is default-on and a projector left
1402// on overnight must not pin the instance awake.
1403const (
1404 streamWriteDeadline = 30 * time.Second
1405 streamHeartbeat = 15 * time.Second
1406 streamTTL = 5 * time.Minute
1407)
1408
1409// streamTrace, when a test sets it, is told when a presentation stream
1410// enters a hold and what ended one ("caught up by an event", "… by a
1411// ping", "… on retry"), so the test can order its steps against the
1412// hold rather than against a clock. Nil in production.
1413var streamTrace func(state string)
1414
1415func traceStream(state string) {
1416 if streamTrace != nil {
1417 streamTrace(state)
1418 }
1419}
1420
1421// presentStream is the session's SSE feed: `event: slide` carrying the
1422// whole state as JSON, one event on connect, and a comment ping in
1423// between.
1424//
1425// Unlike Docs' stream, what travels here IS the state rather than an
1426// advisory cursor — a presentation has no "fetch what you missed"
1427// endpoint to make an advisory notification safe. That is why the hub
1428// drops a subscriber that falls behind instead of skipping events
1429// (internal/slides/present), and why the connect event matters: a
1430// dropped page reconnects and is immediately right again.
1431func (a *app) presentStream(w http.ResponseWriter, r *http.Request) {
1432 // Not presentationFor: a projector's EventSource that is answered a
1433 // 503 fails for good, so in team mode the stream opens while the
1434 // presenter's standing is unknown and holds (streamPresentation). A
1435 // presenter who is gone is still the 410.
1436 p, ok := a.presentationRow(w, r)
1437 if !ok {
1438 return
1439 }
1440 if reach, _ := a.presentationStands(r.Context(), p); reach == presenterGone {
1441 a.gone(w, r)
1442 return
1443 }
1444 a.streamPresentation(w, r, p, nil)
1445}
1446
1447// streamPresentation is the SSE body, shared by the session's own
1448// stream and the share link's (codex 5). `alive`, when it is not nil,
1449// is re-asked before every write: it is how a follower's stream ends
1450// the moment the link they arrived with is revoked, rather than
1451// carrying on to the end of the talk because the session is still
1452// live. One indexed read per event and per 15-second ping, which is
1453// the price of a revocation that means something.
1454func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Presentation, alive func() bool) {
1455 fl, ok := w.(http.Flusher)
1456 if !ok {
1457 a.fail(w, r, "stream: the ResponseWriter does not flush", nil)
1458 return
1459 }
1460 if a.stopping() {
1461 drained(w)
1462 return
1463 }
1464
1465 // Subscribe BEFORE re-reading the row, never after (Docs' note): a
1466 // command landing between the two must produce a redundant event,
1467 // which costs one repaint, where the other order would let it fall
1468 // into the gap and leave the projector a slide behind for the rest
1469 // of the talk.
1470 ch, stop := a.hub.Subscribe(p.Sqid)
1471 defer stop()
1472
1473 var current Presentation
1474 if err := a.db.G.WithContext(r.Context()).Take(&current, p.ID).Error; err != nil {
1475 a.fail(w, r, "read a presentation for the stream", err)
1476 return
1477 }
1478
1479 rc := http.NewResponseController(w)
1480 w.Header().Set("Content-Type", "text/event-stream")
1481 w.Header().Set("Cache-Control", "no-store")
1482 w.WriteHeader(http.StatusOK)
1483 fl.Flush()
1484
1485 // Team mode: the talk stands on its presenter's reach, re-decided
1486 // before every delivery and again when the presenter's Member lease
1487 // runs out (team_present.go). A presenter who is gone ends the talk
1488 // and the stream. While the presenter's standing cannot be read the
1489 // stream is HELD: open, delivering nothing but comment pings,
1490 // re-asking at streamHoldRetry (the roster's RetryAfter), and sent the talk's current state
1491 // the moment it can be read again — a projector's EventSource fails
1492 // for good on a 503, so ending the stream would blank the room
1493 // (Fable #33, note 1). Outside team mode renewC is nil and
1494 // presentationStands always stands.
1495 var renew *time.Timer
1496 var renewC <-chan time.Time
1497 defer func() {
1498 if renew != nil {
1499 renew.Stop()
1500 }
1501 }()
1502 held := false
1503 stands := func() bool {
1504 if a.team == nil {
1505 return true
1506 }
1507 reach, next := a.presentationStands(r.Context(), p)
1508 switch reach {
1509 case presenterGone:
1510 return false
1511 case presenterUnknown:
1512 if !held {
1513 traceStream("held")
1514 }
1515 held, next = true, streamHoldRetry
1516 default:
1517 held = false
1518 }
1519 switch {
1520 case next <= 0:
1521 renewC = nil
1522 case renew == nil:
1523 renew = time.NewTimer(next)
1524 renewC = renew.C
1525 default:
1526 renew.Reset(next)
1527 renewC = renew.C
1528 }
1529 return true
1530 }
1531
1532 send := func(text string) bool {
1533 // The deadline error is ignored deliberately: a
1534 // ResponseWriter that cannot set deadlines still streams,
1535 // unbounded. A write error ends the handler, because it means
1536 // the client is gone.
1537 _ = rc.SetWriteDeadline(time.Now().Add(streamWriteDeadline))
1538 if _, err := io.WriteString(w, text); err != nil {
1539 return false
1540 }
1541 fl.Flush()
1542 return true
1543 }
1544 // deliver is the one place a position is written to this stream:
1545 // the connect event, the catch-up after a hold, and every event the
1546 // hub sends all go through it.
1547 //
1548 // lastSeq is the newest position sequence it has written. Two
1549 // presses commit in order but publish from their own goroutines, so
1550 // the older one's event can reach the hub second, and a catch-up
1551 // can write the row before an event published earlier arrives. An
1552 // event at or below lastSeq is one of those, or a repeat of what
1553 // the page has, and is not written. lastSeq moves only when an
1554 // event is written, so nothing newer than the page has is lost.
1555 // Sequence 0 is a session begun before positions existed, or the
1556 // ended event endPresentationsOf publishes, and is always written.
1557 var lastSeq int64
1558 deliver := func(e present.Event) bool {
1559 var seq int64
1560 if e.Position != nil {
1561 seq = e.Position.Seq
1562 }
1563 if seq != 0 && seq <= lastSeq {
1564 return true
1565 }
1566 body, err := json.Marshal(e)
1567 if err != nil {
1568 return false
1569 }
1570 if !send("event: slide\ndata: " + string(body) + "\n\n") {
1571 return false
1572 }
1573 lastSeq = max(lastSeq, seq)
1574 return true
1575 }
1576 // catchUp is what a held stream owes when the presenter's standing
1577 // returns: the talk as it is now, read afresh.
1578 catchUp := func() bool {
1579 var now Presentation
1580 if err := a.db.G.WithContext(r.Context()).Take(&now, p.ID).Error; err != nil {
1581 return false
1582 }
1583 return deliver(eventFor(now))
1584 }
1585 // open runs the checks before any write: false ends the stream. A
1586 // stream that was held and stands again is caught up first, so
1587 // whatever the caller writes next is compared with the row. why
1588 // names the caller, for traceStream.
1589 open := func(why string) bool {
1590 if alive != nil && !alive() {
1591 return false
1592 }
1593 wasHeld := held
1594 if !stands() {
1595 return false
1596 }
1597 if held || !wasHeld {
1598 return true
1599 }
1600 traceStream("caught up by " + why)
1601 return catchUp()
1602 }
1603 // ping is the heartbeat, which a held stream still sends.
1604 ping := func() bool {
1605 return open("a ping") && send(": ping\n\n")
1606 }
1607 // event is one of the hub's events. A held stream drops it; the
1608 // catch-up writes the row when the hold ends.
1609 event := func(e present.Event) bool {
1610 if !open("an event") {
1611 return false
1612 }
1613 return held || deliver(e)
1614 }
1615
1616 if !event(eventFor(current)) {
1617 return
1618 }
1619
1620 heartbeat := time.NewTimer(streamHeartbeat)
1621 defer heartbeat.Stop()
1622 ttl := time.NewTimer(streamTTL)
1623 defer ttl.Stop()
1624
1625 for {
1626 select {
1627 case <-r.Context().Done():
1628 // The client went away.
1629 return
1630 case <-a.draining.done():
1631 // The process is stopping, which never cancels a request's
1632 // context (drain.go). A clean end: the projector's
1633 // EventSource reconnects to whichever instance answers next,
1634 // and its connect event re-reads the truth from the row.
1635 return
1636 case <-ttl.C:
1637 // A clean close: the browser reopens if it still wants
1638 // one, and a parked tab does not.
1639 return
1640 case e, ok := <-ch:
1641 if !ok {
1642 // Dropped for falling behind. Ending the response is
1643 // the right answer: EventSource reconnects, and the
1644 // connect event re-reads the truth from the row.
1645 return
1646 }
1647 if !event(e) {
1648 return
1649 }
1650 heartbeat.Reset(streamHeartbeat)
1651 case <-heartbeat.C:
1652 if !ping() {
1653 return
1654 }
1655 heartbeat.Reset(streamHeartbeat)
1656 case <-renewC:
1657 wasHeld := held
1658 if !stands() {
1659 return
1660 }
1661 if wasHeld && !held {
1662 traceStream("caught up on retry")
1663 if !catchUp() {
1664 return
1665 }
1666 }
1667 }
1668 }
1669}
1670
1671// --- POST /p/{session}/command ---
1672
1673// errPresentationEnded is the transaction's own refusal: the row was
1674// ended by somebody else between this request resolving it and the
1675// UPDATE. It becomes a 410, the same answer the GET would have given.
1676var errPresentationEnded = errors.New("slides: the presentation ended")
1677
1678// presentCommand is the one write every driving surface makes: next,
1679// prev, goto, blackout, end. A Positional session takes more ops, and
1680// its signed-in presenter may drive without the token
1681// (presenting_position.go); the rest of this comment is the index path.
1682//
1683// The token is the whole permission — a form field for a browser, a
1684// bearer for anything else, which is the seam a native remote will use
1685// (spec §3.4: "a native remote later speaks exactly present, command
1686// and the stream"). Note that a non-browser caller must still send an
1687// Origin header: csrf.Protect covers this router app-wide, and being
1688// covered by it is worth more than sparing a native client one header.
1689//
1690// The write is a transaction with `ended_at IS NULL` in the WHERE, so
1691// a command racing the End button loses rather than reviving a talk
1692// that is over.
1693func (a *app) presentCommand(w http.ResponseWriter, r *http.Request) {
1694 p, ok := a.presentationFor(w, r)
1695 if !ok {
1696 return
1697 }
1698 // A session with an absolute position is driven by presses
1699 // (presenting_position.go). What follows is the index path, kept
1700 // as it was for the sessions begun before positions existed.
1701 if p.Positional {
1702 a.presentPress(w, r, p)
1703 return
1704 }
1705 // The token, or the presenter's own cookie (mayDrive): a talk
1706 // rejoined through Present is still theirs to drive.
1707 drives, presenter, answered := a.mayDrive(w, r, p, pressToken(r))
1708 if answered {
1709 return
1710 }
1711 if !drives {
1712 a.notFound(w, r)
1713 return
1714 }
1715
1716 op := r.PostFormValue("op")
1717 // The slide count is what bounds next and goto, and it costs a
1718 // document open — so only the three ops that move the deck pay for
1719 // it. Blackout and end do not need to know how long the deck is.
1720 count := 0
1721 if op == "next" || op == "prev" || op == "goto" {
1722 d, ok := a.deckOf(w, r, p)
1723 if !ok {
1724 return
1725 }
1726 h, view, err := a.openDeck(r.Context(), d)
1727 if err != nil {
1728 a.fail(w, r, "open deck", err)
1729 return
1730 }
1731 count = len(view.ForReaders().Slides)
1732 h.Close(r.Context())
1733 if count == 0 {
1734 a.errorPage(w, r, http.StatusUnprocessableEntity, kindStatus, "")
1735 return
1736 }
1737 }
1738
1739 var updated Presentation
1740 err := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
1741 var cur Presentation
1742 if err := tx.Where("id = ? AND ended_at IS NULL", p.ID).Take(&cur).Error; err != nil {
1743 if errors.Is(err, gorm.ErrRecordNotFound) {
1744 return errPresentationEnded
1745 }
1746 return err
1747 }
1748 changes, err := commandChanges(op, r.PostFormValue("slide"), cur, count)
1749 if err != nil {
1750 return err
1751 }
1752 // A map, not a struct: the explicit column allowlist SKILL.md
1753 // §4 asks for, so nothing a form carries can reach a column
1754 // this handler did not name.
1755 res := tx.Model(&Presentation{}).
1756 Where("id = ? AND ended_at IS NULL", p.ID).Updates(changes)
1757 if res.Error != nil {
1758 return res.Error
1759 }
1760 if res.RowsAffected == 0 {
1761 return errPresentationEnded
1762 }
1763 return tx.Take(&updated, p.ID).Error
1764 })
1765 switch {
1766 case err == nil:
1767 case errors.Is(err, errPresentationEnded):
1768 a.gone(w, r)
1769 return
1770 case errors.Is(err, errBadCommand):
1771 a.errorPage(w, r, http.StatusUnprocessableEntity, kindStatus, "")
1772 return
1773 default:
1774 a.fail(w, r, "apply a presentation command", err)
1775 return
1776 }
1777
1778 // Everybody watching, at once: the presenter's laptop, the phone,
1779 // and every follower.
1780 a.hub.Publish(p.Sqid, eventFor(updated))
1781 // The actor is the CAPABILITY, not the person who started the talk
1782 // (codex 5's sibling, codex 15). A remote token is transferable by
1783 // design — that is the feature: it goes on a phone, and the phone
1784 // may be somebody else's. So this write cannot name a person, and
1785 // naming p.Actor anyway made §6.2's "every write names its real
1786 // actor" false for exactly the writes nobody could vouch for.
1787 // `remote:<session>` says what actually authenticated, and the
1788 // issuer rides beside it so the trail still reaches somebody
1789 // answerable.
1790 // The presenter's own cookie names the presenter.
1791 actor := remoteActor(p)
1792 if presenter != "" {
1793 actor = presenter
1794 }
1795 a.logger.Info("slides: presentation command",
1796 "session", p.Sqid, "op", op, "slide", updated.Slide,
1797 "actor", actor, "issuer", p.Actor)
1798
1799 // A browser form goes back to the page it came from — same-origin
1800 // only, checked against the origin the app resolved, so this can
1801 // never be an open redirect. Anything else gets a 204: there is no
1802 // page to return to.
1803 if ref := r.Header.Get("Referer"); ref != "" && a.sameOrigin(ref) {
1804 http.Redirect(w, r, ref, http.StatusSeeOther)
1805 return
1806 }
1807 w.WriteHeader(http.StatusNoContent)
1808}
1809
1810// remoteActor is spec §6.2's actor string for a presentation remote —
1811// the third kind, beside decks.go's `person:<id>` and agents.go's
1812// `agent:<id>`, and the only one that names no principal at all.
1813//
1814// It is deliberately anonymous (§6.2, codex 15). The remote token is a
1815// transferable capability: the presenter shows a QR to the room, or
1816// hands their phone to a colleague, and the server has no way to say
1817// who is holding it. Writing `person:<the presenter>` on those commands
1818// was a claim about identity the app could not support. This one is
1819// honest — "whoever held the remote for this session" — and the
1820// session's own Actor is logged beside it, so the person who issued the
1821// capability is still named.
1822func remoteActor(p Presentation) string { return "remote:" + p.Sqid }
1823
1824// errBadCommand is an op, or a goto's slide, that is not one this
1825// session can do.
1826var errBadCommand = errors.New("slides: not a command")
1827
1828// commandChanges is the whole decision a command makes, as the columns
1829// it writes. Split out from the transaction so it is one readable
1830// switch rather than a switch inside a closure inside a handler.
1831func commandChanges(op, slide string, cur Presentation, count int) (map[string]any, error) {
1832 switch op {
1833 case "next":
1834 return map[string]any{"slide": clampSlide(cur.Slide+1, count)}, nil
1835 case "prev":
1836 return map[string]any{"slide": clampSlide(cur.Slide-1, count)}, nil
1837 case "goto":
1838 n, err := strconv.Atoi(slide)
1839 if err != nil || n < 1 || n > count {
1840 return nil, errBadCommand
1841 }
1842 return map[string]any{"slide": n - 1}, nil
1843 case "blackout":
1844 // A toggle rather than a value, because the button that sends
1845 // it says which way it goes and the room is the source of
1846 // truth for whether the screen is black.
1847 return map[string]any{"blackout": !cur.Blackout}, nil
1848 case "end":
1849 return map[string]any{"ended_at": time.Now().UTC()}, nil
1850 default:
1851 return nil, errBadCommand
1852 }
1853}
1854
1855// bearerToken reads `Authorization: Bearer <token>`, the shape a
1856// native remote or an agent will use.
1857func bearerToken(r *http.Request) string {
1858 h := r.Header.Get("Authorization")
1859 const prefix = "Bearer "
1860 if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
1861 return ""
1862 }
1863 return strings.TrimSpace(h[len(prefix):])
1864}
1865
1866// sameOrigin reports whether a URL is this app's own — the check
1867// behind the command's 303, and the reason it cannot be turned into an
1868// open redirect by a crafted Referer.
1869func (a *app) sameOrigin(raw string) bool {
1870 u, err := url.Parse(raw)
1871 if err != nil || u.Scheme == "" || u.Host == "" {
1872 return false
1873 }
1874 return u.Scheme+"://"+u.Host == a.cfg.Origin
1875}
1876
1877// --- audience follow, from a share link ---
1878
1879// liveSessionFor finds the session somebody is currently presenting
1880// this deck in, if there is one. The most recent, when a deck somehow
1881// has two: the one that started last is the one being given.
1882func (a *app) liveSessionFor(r *http.Request, deckID int64) (Presentation, bool) {
1883 var p Presentation
1884 err := a.livePresentations(r).Where("deck_id = ?", deckID).
1885 Order("started_at DESC").Take(&p).Error
1886 if err != nil {
1887 if !errors.Is(err, gorm.ErrRecordNotFound) {
1888 a.logger.Error("slides: look for a live presentation", "deck", deckID, "err", err)
1889 }
1890 return Presentation{}, false
1891 }
1892 // Team mode: a talk whose presenter no longer reaches the deck is no
1893 // talk to follow (team_present.go), and one that cannot be decided
1894 // now is not followed either; the share link's own deck still is.
1895 if reach, _ := a.presentationStands(r.Context(), p); reach != presenterReaches {
1896 return Presentation{}, false
1897 }
1898 return p, true
1899}
1900
1901// followPresenter renders the audience's copy of the surface: the
1902// presenter's own slide, read-only, with a way back to browsing.
1903//
1904// Read-only is enforced by there being nothing to press — no token
1905// reaches this page, so its script has nothing to send and its markup
1906// has no form. An audience that could drive the talk would not be an
1907// audience.
1908//
1909// And every URL on it is `base`, which is the share link (codex 5):
1910// the pictures, the fragments the script swaps in and the stream it
1911// subscribes to. The session sqid appears nowhere, so there is no
1912// address here that outlives the capability it came with.
1913func (a *app) followPresenter(w http.ResponseWriter, r *http.Request, d Deck, p Presentation, base string) {
1914 a.renderSurface(w, r, d, p, surfaceOptions{
1915 follow: true,
1916 base: base,
1917 stream: base + "/stream",
1918 fragment: base + "?follow=1&slide={n}&fragment=1",
1919 // No session: see surfacePage.Session.
1920 backHref: base,
1921 backLabel: rastrillo.T(r, "slides.follow.browse"),
1922 })
1923}
1924
1925// --- the QR ---
1926
1927// qrSVG draws the pairing QR as an inline SVG.
1928//
1929// Inline rather than an <img> with a data URI: it is markup the page
1930// already has, so it costs no second request and no base64 padding,
1931// and role="img" with a label naming the code is what makes it
1932// meaningful to somebody who cannot see it — the label says the code,
1933// which is the actual information the picture carries.
1934//
1935// Black on white, fixed, rather than currentColor: a QR is read by a
1936// camera looking for contrast, and a code that inverted itself in dark
1937// mode would scan on half the phones in the room.
1938func qrSVG(text, label string) (template.HTML, error) {
1939 q, err := qrcode.New(text, qrcode.Medium)
1940 if err != nil {
1941 return "", fmt.Errorf("slides: build a QR: %w", err)
1942 }
1943 bitmap := q.Bitmap()
1944 size := len(bitmap)
1945 if size == 0 {
1946 return "", errors.New("slides: empty QR")
1947 }
1948
1949 // One path for every dark module, rather than one <rect> each: the
1950 // same picture in about a fifth of the bytes.
1951 var path strings.Builder
1952 for y, row := range bitmap {
1953 for x, dark := range row {
1954 if dark {
1955 fmt.Fprintf(&path, "M%d %dh1v1h-1z", x, y)
1956 }
1957 }
1958 }
1959
1960 var svg strings.Builder
1961 fmt.Fprintf(&svg, `<svg slides-qr xmlns="http://www.w3.org/2000/svg" viewBox="0 0 %d %d" width="180" height="180" role="img" aria-label="%s">`,
1962 size, size, template.HTMLEscapeString(label))
1963 fmt.Fprintf(&svg, `<rect width="%d" height="%d" fill="#ffffff"/>`, size, size)
1964 fmt.Fprintf(&svg, `<path fill="#000000" d="%s"/></svg>`, path.String())
1965 return template.HTML(svg.String()), nil
1966}
1967