oficina / slides Public

Presenting: an absolute position, ordered by the server

New sessions are Positional: the row holds the talk as slide id, step,
mode and black, plus a sequence and a timer. Each press to
/p/{session}/command runs in one transaction that settles the stored
position into the deck and applies the move, so crossing presses from
the laptop and the phone both count. A press id already applied answers
the position and moves nothing; the newest 64 ids per session are kept.

The signed-in presenter may drive without a token, and pressing Present
again rejoins the talk without replacing a paired phone's token. It now
lands on /p/{session}. Sessions begun before this keep the index path.

Migration 0009 adds the position columns and presentation_presses.
Tests pair a phone through the row until POST /p/{session}/pair exists.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 987fffab1393a23b6b4bc849688b9f910367d9aa parent 03f5da5
10 files changed, +1,119 −75
  • internal/slides/decks.go +5 −0
  • internal/slides/migrations/0009_alter_presentations.sql +16 −0
  • internal/slides/migrations/schema.sql +5 −1
  • internal/slides/models.go +30 −0
  • internal/slides/present/hub.go +14 −2
  • internal/slides/presentation.go +49 −32
  • internal/slides/presenting_position.go +371 −0
  • internal/slidestest/browser_present_test.go +30 −29
  • internal/slidestest/present_position_test.go +562 −0
  • internal/slidestest/present_test.go +37 −11
diff --git a/internal/slides/decks.go b/internal/slides/decks.go
index 75b6bd0..089492f 100644
--- a/internal/slides/decks.go
+++ b/internal/slides/decks.go
@@ -1429,6 +1429,11 @@ func deleteDeckTx(tx *gorm.DB, d Deck, live *[]Presentation) error {
Find(live).Error; err != nil {
return err
}
+ if err := tx.Where("presentation_id IN (?)",
+ tx.Model(&Presentation{}).Select("id").Where("deck_id = ?", d.ID)).
+ Delete(&PresentationPress{}).Error; err != nil {
+ return err
+ }
if err := tx.Where("deck_id = ?", d.ID).Delete(&Presentation{}).Error; err != nil {
return err
}
diff --git a/internal/slides/migrations/0009_alter_presentations.sql b/internal/slides/migrations/0009_alter_presentations.sql
new file mode 100644
index 0000000..2d04249
--- /dev/null
+++ b/internal/slides/migrations/0009_alter_presentations.sql
@@ -0,0 +1,16 @@
+ALTER TABLE `presentations` ADD `slide_id` text;
+
+ALTER TABLE `presentations` ADD `step` integer;
+
+ALTER TABLE `presentations` ADD `mode` text;
+
+ALTER TABLE `presentations` ADD `seq` integer;
+
+ALTER TABLE `presentations` ADD `positional` numeric;
+
+ALTER TABLE `presentations` ADD `timer_at` datetime;
+
+CREATE TABLE `presentation_presses` (`presentation_id` integer,`press_id` text,`created_at` datetime);
+
+CREATE UNIQUE INDEX `idx_presentation_presses_press` ON `presentation_presses`(`presentation_id`,`press_id`);
+
diff --git a/internal/slides/migrations/schema.sql b/internal/slides/migrations/schema.sql
index be36895..dd0c6d3 100644
--- a/internal/slides/migrations/schema.sql
+++ b/internal/slides/migrations/schema.sql
@@ -15,7 +15,9 @@ CREATE TABLE `deck_updates` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` in
CREATE TABLE `decks` (`id` integer PRIMARY KEY AUTOINCREMENT,`sqid` text,`title` text,`owner_id` integer,`rung` text,`theme` text,`seq` integer,`created_at` datetime,`updated_at` datetime);
-CREATE TABLE `presentations` (`id` integer PRIMARY KEY AUTOINCREMENT,`sqid` text,`deck_id` integer,`actor` text,`slide` integer,`blackout` numeric,`code` text,`remote_token_hash` text,`started_at` datetime,`ended_at` datetime);
+CREATE TABLE `presentation_presses` (`presentation_id` integer,`press_id` text,`created_at` datetime);
+
+CREATE TABLE `presentations` (`id` integer PRIMARY KEY AUTOINCREMENT,`sqid` text,`deck_id` integer,`actor` text,`slide` integer,`blackout` numeric,`code` text,`remote_token_hash` text,`started_at` datetime,`ended_at` datetime, `slide_id` text, `step` integer, `mode` text, `seq` integer, `positional` numeric, `timer_at` datetime);
CREATE TABLE `share_links` (`id` integer PRIMARY KEY AUTOINCREMENT,`deck_id` integer,`token_hash` text,`actor` text,`views` integer,`created_at` datetime,`revoked_at` datetime);
@@ -43,6 +45,8 @@ CREATE INDEX `idx_decks_owner_id` ON `decks`(`owner_id`);
CREATE UNIQUE INDEX `idx_decks_sqid` ON `decks`(`sqid`);
+CREATE UNIQUE INDEX `idx_presentation_presses_press` ON `presentation_presses`(`presentation_id`,`press_id`);
+
CREATE INDEX `idx_presentations_code` ON `presentations`(`code`);
CREATE INDEX `idx_presentations_deck_id` ON `presentations`(`deck_id`);
diff --git a/internal/slides/models.go b/internal/slides/models.go
index 1ba8768..e00f7b4 100644
--- a/internal/slides/models.go
+++ b/internal/slides/models.go
@@ -17,6 +17,7 @@ var Models = []any{
&DeckGrant{},
&ShareLink{},
&Presentation{},
+ &PresentationPress{},
&Agent{},
}
@@ -346,6 +347,35 @@ type Presentation struct {
RemoteTokenHash string
StartedAt time.Time
EndedAt *time.Time
+
+ // The talk's absolute position (deck.Position), for a session that
+ // is Positional: the slide by id, the press on it, and the mode.
+ // Slide above stays in step with SlideID, as the slide's index in
+ // the full talk (deck.TalkOrder), so the 1-based number every URL
+ // and stream event carries still means the same slide.
+ SlideID string
+ Step int
+ Mode string
+ // Seq counts the presses the server has applied. A window compares
+ // the seq of a position it hears with the newest it has applied, so
+ // a late answer can never move it backwards.
+ Seq int64
+ // Positional is false for a session begun before positions existed
+ // (and NULL in its row, which reads as false). Such a session keeps
+ // moving by Slide alone for its remaining hours.
+ Positional bool
+ // TimerAt is when the talk's timer started: the first move, not the
+ // session opening. Nil until then and after a timer-reset.
+ TimerAt *time.Time
+}
+
+// PresentationPress is one press id a session has applied, so that a
+// press sent twice (a window that did not hear its answer) counts once.
+// Only the newest 64 per session are kept (presenting_position.go).
+type PresentationPress struct {
+ PresentationID int64 `gorm:"uniqueIndex:idx_presentation_presses_press"`
+ PressID string `gorm:"uniqueIndex:idx_presentation_presses_press"`
+ CreatedAt time.Time
}
// Agent is one non-human principal that may drive this instance's
diff --git a/internal/slides/present/hub.go b/internal/slides/present/hub.go
index 6b02635..1b2ea71 100644
--- a/internal/slides/present/hub.go
+++ b/internal/slides/present/hub.go
@@ -32,10 +32,11 @@ import "sync"
// than approximately.
//
// The JSON tags are the wire format of the stream's `event: slide`
-// data (presentation.go), and static/present.js reads these three
+// data (presentation.go), and static/present.js reads the first three
// names. Changing one is changing the protocol.
type Event struct {
- // Slide is the 0-based index of the slide being shown.
+ // Slide is the 1-based number of the slide being shown
+ // (presentation.go's eventFor).
Slide int `json:"slide"`
// Blackout is whether the screen is blacked out. Carried
// separately from the slide because coming back from a blackout
@@ -45,6 +46,17 @@ type Event struct {
// following rather than sitting on a slide that will never move
// again.
Ended bool `json:"ended"`
+
+ // The absolute position, for a session that has one
+ // (presenting_position.go): the slide by id, the press on it, the
+ // mode, and the session's sequence, which a window compares so a
+ // late event never moves it backwards. All four are left out for a
+ // session begun before positions existed, whose events stay the
+ // three fields above.
+ SlideID string `json:"slideId,omitempty"`
+ Step int `json:"step,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ Seq int64 `json:"seq,omitempty"`
}
// subscriberBuffer is how many events a subscriber may fall behind by
diff --git a/internal/slides/presentation.go b/internal/slides/presentation.go
index aa5c20b..b56b1ef 100644
--- a/internal/slides/presentation.go
+++ b/internal/slides/presentation.go
@@ -169,12 +169,20 @@ func presentationOver(p Presentation) bool {
// person sees (?slide=3 is the third slide). Both conventions are
// right in their own place and the seam between them is here, so no
// other function in the app has to hold both in its head.
+//
+// A Positional session's event carries its absolute position too
+// (presenting_position.go); one begun before that carries the three
+// fields it always did.
func eventFor(p Presentation) present.Event {
- return present.Event{
+ e := present.Event{
Slide: p.Slide + 1,
Blackout: p.Blackout,
Ended: p.EndedAt != nil,
}
+ if p.Positional {
+ e.SlideID, e.Step, e.Mode, e.Seq = p.SlideID, p.Step, p.Mode, p.Seq
+ }
+ return e
}
// --- resolving a session from a request ---
@@ -290,19 +298,18 @@ func (a *app) presenterActor(r *http.Request) string {
// --- POST /d/{sqid}/present ---
// startPresenting opens a session for a deck, or picks up the one this
-// person already has open on it, and lands them on the presenter view
-// with the remote's capability in the URL — once.
+// person already has open on it, and lands them on the session's own
+// slide (S12).
//
// Reachable by anybody who can open the deck (visibleDecks), not the
// owner alone: presenting is reading out loud, and a team member who
// can read a deck can read it to a room.
//
// One live session per deck per presenter (spec §3.4). Pressing
-// Present again reuses the row and mints a FRESH remote token, which
-// is the one surprising thing in this handler and is deliberate: only
-// the hash is stored, so the old token cannot be shown again, and a
-// presenter view with no working buttons would be worse than a phone
-// that has to be re-paired. The pairing block says so.
+// Present again rejoins the row and changes nothing on it, so a phone
+// already paired stays paired (S19): the presenter drives by being
+// signed in (presenting_position.go's mayDrive), and a new session
+// starts with no remote token at all until a phone is paired.
func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) {
u, ok := a.viewer(w, r)
if !ok {
@@ -313,35 +320,19 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) {
return
}
- token, err := newRemoteToken()
- if err != nil {
- a.fail(w, r, "mint a remote token", err)
- return
- }
actor := actorFor(u)
g := a.deckGuard(r.Context(), u, d)
var p Presentation
- err = a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor).
+ err := a.livePresentations(r).Where("deck_id = ? AND actor = ?", d.ID, actor).
Order("started_at DESC").Take(&p).Error
switch {
case err == nil:
- // Re-pairing an open session: the row keeps its sqid, its
- // slide and its code, so every page already watching it stays
- // watching the same talk.
- if err := a.guarded(r.Context(), g, func(db *gorm.DB) error {
- return db.Model(&Presentation{}).
- Where("id = ? AND ended_at IS NULL", p.ID).
- Update("remote_token_hash", hashRemoteToken(token)).Error
- }); err != nil {
- if a.guardRefused(w, r, err) {
- return
- }
- a.fail(w, r, "re-pair a presentation", err)
- return
- }
+ // Rejoining: the row keeps its sqid, its position, its code
+ // and its token, so every page and phone already on the talk
+ // stays on it.
case errors.Is(err, gorm.ErrRecordNotFound):
- p, err = a.createPresentation(r, d, actor, token, g)
+ p, err = a.createPresentation(r, d, actor, "", g)
if a.guardRefused(w, r, err) {
return
}
@@ -354,7 +345,7 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) {
return
}
- http.Redirect(w, r, "/p/"+p.Sqid+"/notes?t="+token, http.StatusSeeOther)
+ http.Redirect(w, r, "/p/"+p.Sqid, http.StatusSeeOther)
}
// createPresentation writes the row, retrying on a code already in use
@@ -363,7 +354,20 @@ func (a *app) startPresenting(w http.ResponseWriter, r *http.Request) {
//
// g is the team-mode write guard for the presenter on d, around the
// insert; nil outside team mode.
+//
+// Every new session is Positional, starting where deck.Start says. An
+// empty token stores no hash, which no token matches (remoteTokenOK).
func (a *app) createPresentation(r *http.Request, d Deck, actor, token string, g writeGuard) (Presentation, error) {
+ h, view, err := a.openDeck(r.Context(), d)
+ if err != nil {
+ return Presentation{}, err
+ }
+ h.Close(r.Context())
+ start, slide := startPosition(view)
+ tokenHash := ""
+ if token != "" {
+ tokenHash = hashRemoteToken(token)
+ }
for attempt := 0; attempt < maxCodeAttempts; attempt++ {
sqid, err := newSqid()
if err != nil {
@@ -385,8 +389,12 @@ func (a *app) createPresentation(r *http.Request, d Deck, actor, token string, g
DeckID: d.ID,
Actor: actor,
Code: code,
- RemoteTokenHash: hashRemoteToken(token),
+ RemoteTokenHash: tokenHash,
StartedAt: time.Now().UTC(),
+ Slide: slide,
+ SlideID: start.Slide,
+ Mode: string(start.Mode),
+ Positional: true,
}
err = a.guarded(r.Context(), g, func(db *gorm.DB) error { return db.Create(&p).Error })
if err == nil {
@@ -1333,7 +1341,9 @@ func (a *app) streamPresentation(w http.ResponseWriter, r *http.Request, p Prese
var errPresentationEnded = errors.New("slides: the presentation ended")
// presentCommand is the one write every driving surface makes: next,
-// prev, goto, blackout, end.
+// prev, goto, blackout, end. A Positional session takes more ops, and
+// its signed-in presenter may drive without the token
+// (presenting_position.go); the rest of this comment is the index path.
//
// The token is the whole permission — a form field for a browser, a
// bearer for anything else, which is the seam a native remote will use
@@ -1350,6 +1360,13 @@ func (a *app) presentCommand(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // A session with an absolute position is driven by presses
+ // (presenting_position.go). What follows is the index path, kept
+ // as it was for the sessions begun before positions existed.
+ if p.Positional {
+ a.presentPress(w, r, p)
+ return
+ }
token := r.PostFormValue("t")
if token == "" {
token = bearerToken(r)
diff --git a/internal/slides/presenting_position.go b/internal/slides/presenting_position.go
new file mode 100644
index 0000000..abdca20
--- /dev/null
+++ b/internal/slides/presenting_position.go
@@ -0,0 +1,371 @@
+// presenting_position.go is the server's half of an absolute position
+// (spec S13 and S18): a session that is Positional holds the talk as
+// {slide id, step, mode, black}, and every press that reaches
+// POST /p/{session}/command is applied to it in the order it arrives.
+//
+// Ordering is the point. A laptop and a phone that both press next from
+// step 2 must reach step 4, so a press is never "go to step 3": it is a
+// move, applied inside one transaction to whatever the row says now
+// (deck.Advance). A window that did not hear its answer sends the same
+// press again, so each carries an id and an id already applied answers
+// the position without moving it.
+//
+// Sessions begun before this existed have Positional false and keep
+// presentation.go's index path, untouched, for their remaining hours.
+package slides
+
+import (
+ "errors"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/slides/internal/slides/deck"
+ "gorm.io/gorm"
+)
+
+// pressIDPattern is what a press id may be: base64url, from 16
+// characters (12 random bytes) to 43 (32). Anything else is refused
+// rather than stored, so the table holds nothing a caller made up in a
+// shape nobody expected.
+var pressIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,43}$`)
+
+// keptPresses is how many press ids a session remembers. A press is
+// only ever resent by the window that sent it, within seconds, so the
+// newest 64 cover any burst a clicker can make.
+const keptPresses = 64
+
+// pressCommand is one press as the command form carries it.
+type pressCommand struct {
+ Op, Slide, Press, AtSlide, AtMode string
+ AtStep int
+}
+
+// positionAnswer is what a press answers when JSON was asked for: the
+// position after it, the session's sequence, and the deck's own (the
+// same seq apiGetDeck serves), so a window learns from any answer that
+// the deck changed under it.
+type positionAnswer struct {
+ Slide string `json:"slide"`
+ Step int `json:"step"`
+ Mode string `json:"mode"`
+ Black bool `json:"black"`
+ Seq int64 `json:"seq"`
+ DeckSeq int64 `json:"deckSeq"`
+}
+
+// mayDrive is who may move a Positional session: whoever holds the
+// remote token, or the presenter themselves, signed in (S19). The
+// cookie being enough is why the app-wide origin check (app.go's
+// csrf.Protect) matters here: another site cannot make the presenter's
+// browser press.
+func (a *app) mayDrive(r *http.Request, p Presentation, token string) bool {
+ if remoteTokenOK(p, token) {
+ return true
+ }
+ if p.Actor == "" {
+ return false
+ }
+ return a.presenterActor(r) == p.Actor
+}
+
+// presentPress is presentCommand for a Positional session.
+func (a *app) presentPress(w http.ResponseWriter, r *http.Request, p Presentation) {
+ token := r.PostFormValue("t")
+ if token == "" {
+ token = bearerToken(r)
+ }
+ if !a.mayDrive(r, p, token) {
+ a.notFound(w, r)
+ return
+ }
+ cmd, err := pressCommandFrom(r)
+ if err != nil {
+ a.errorPage(w, r, http.StatusUnprocessableEntity, kindStatus, "")
+ return
+ }
+
+ answer, err := a.applyPress(r, p, cmd)
+ switch {
+ case err == nil:
+ case errors.Is(err, errPresentationEnded):
+ a.gone(w, r)
+ return
+ case errors.Is(err, errBadCommand):
+ a.errorPage(w, r, http.StatusUnprocessableEntity, kindStatus, "")
+ return
+ default:
+ a.fail(w, r, "apply a press", err)
+ return
+ }
+
+ // The actor is what authenticated, as presentCommand says: the
+ // remote's capability, or the presenter's own session.
+ actor := p.Actor
+ if remoteTokenOK(p, token) {
+ actor = remoteActor(p)
+ }
+ a.logger.Info("slides: presentation press",
+ "session", p.Sqid, "op", cmd.Op, "slide", answer.Slide, "step", answer.Step,
+ "seq", answer.Seq, "actor", actor, "issuer", p.Actor)
+
+ if strings.Contains(r.Header.Get("Accept"), "application/json") {
+ a.writeJSON(w, http.StatusOK, answer)
+ return
+ }
+ if ref := r.Header.Get("Referer"); ref != "" && a.sameOrigin(ref) {
+ http.Redirect(w, r, ref, http.StatusSeeOther)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// pressCommandFrom reads the form. A press id, a step or a mode that is
+// present but malformed is errBadCommand; the op itself is checked when
+// it is applied.
+func pressCommandFrom(r *http.Request) (pressCommand, error) {
+ cmd := pressCommand{
+ Op: r.PostFormValue("op"),
+ Slide: r.PostFormValue("slide"),
+ Press: r.PostFormValue("press"),
+ AtSlide: r.PostFormValue("at_slide"),
+ AtMode: r.PostFormValue("at_mode"),
+ }
+ if cmd.Press != "" && !pressIDPattern.MatchString(cmd.Press) {
+ return pressCommand{}, errBadCommand
+ }
+ if raw := r.PostFormValue("at_step"); raw != "" {
+ n, err := strconv.Atoi(raw)
+ if err != nil {
+ return pressCommand{}, errBadCommand
+ }
+ cmd.AtStep = n
+ }
+ switch deck.Mode(cmd.AtMode) {
+ case "", deck.ModeCore, deck.ModeFull:
+ default:
+ return pressCommand{}, errBadCommand
+ }
+ return cmd, nil
+}
+
+// applyPress applies one press to the session, in one transaction, and
+// tells everybody watching.
+//
+// The row is locked by the transaction itself. This is SQLite
+// (rastrillo/db), which has no SELECT … FOR UPDATE, and rastrillo's
+// write pool is a single connection: a transaction holds it from its
+// first statement to its commit, so two presses cannot interleave, and
+// the second reads the row the first wrote. The deck is read on the
+// same connection, so the position and deckSeq agree with each other.
+func (a *app) applyPress(r *http.Request, p Presentation, cmd pressCommand) (positionAnswer, error) {
+ ctx := r.Context()
+ now := time.Now().UTC()
+ var updated Presentation
+ var deckSeq int64
+ moved := false
+ err := a.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ var cur Presentation
+ if err := tx.Where("id = ? AND ended_at IS NULL", p.ID).Take(&cur).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return errPresentationEnded
+ }
+ return err
+ }
+ var d Deck
+ if err := tx.Take(&d, cur.DeckID).Error; err != nil {
+ return err
+ }
+ deckSeq = d.Seq
+
+ if cmd.Press != "" {
+ var seen int64
+ if err := tx.Model(&PresentationPress{}).
+ Where("presentation_id = ? AND press_id = ?", cur.ID, cmd.Press).
+ Count(&seen).Error; err != nil {
+ return err
+ }
+ if seen > 0 {
+ // Sent twice: where the talk is, and nothing else.
+ updated = cur
+ return nil
+ }
+ }
+
+ h, view, err := a.openDeckOn(ctx, tx, d)
+ if err != nil {
+ return err
+ }
+ h.Close(ctx)
+ changes, err := pressChanges(view, cur, cmd, now)
+ if err != nil {
+ return err
+ }
+ // A map, as presentCommand's: only the columns named here.
+ res := tx.Model(&Presentation{}).
+ Where("id = ? AND ended_at IS NULL", cur.ID).Updates(changes)
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected == 0 {
+ return errPresentationEnded
+ }
+ if cmd.Press != "" {
+ if err := rememberPress(tx, cur.ID, cmd.Press, now); err != nil {
+ return err
+ }
+ }
+ moved = true
+ return tx.Take(&updated, cur.ID).Error
+ })
+ if err != nil {
+ return positionAnswer{}, err
+ }
+ if moved {
+ a.hub.Publish(p.Sqid, eventFor(updated))
+ }
+ return positionAnswer{
+ Slide: updated.SlideID,
+ Step: updated.Step,
+ Mode: updated.Mode,
+ Black: updated.Blackout,
+ Seq: updated.Seq,
+ DeckSeq: deckSeq,
+ }, nil
+}
+
+// rememberPress records a press id and forgets all but the session's
+// newest keptPresses. Newest by rowid: the table has no key of its own,
+// and SQLite hands out rowids in insertion order while the largest is
+// never deleted, which the trim guarantees.
+func rememberPress(tx *gorm.DB, presentationID int64, press string, now time.Time) error {
+ if err := tx.Create(&PresentationPress{
+ PresentationID: presentationID,
+ PressID: press,
+ CreatedAt: now,
+ }).Error; err != nil {
+ return err
+ }
+ return tx.Exec(`DELETE FROM presentation_presses
+ WHERE presentation_id = ? AND rowid NOT IN (
+ SELECT rowid FROM presentation_presses
+ WHERE presentation_id = ? ORDER BY rowid DESC LIMIT ?)`,
+ presentationID, presentationID, keptPresses).Error
+}
+
+// moveOps are the presses that move the talk, and so start its timer.
+var moveOps = map[string]string{
+ "next": "next",
+ "prev": "back",
+ "first": "first",
+ "last": "last",
+ "goto": "goto",
+}
+
+// pressChanges is the whole decision a press makes, as the columns it
+// writes: settle the stored position into the deck as it is now, then
+// apply the move.
+func pressChanges(view *deck.Deck, cur Presentation, cmd pressCommand, now time.Time) (map[string]any, error) {
+ changes := map[string]any{"seq": cur.Seq + 1}
+ if cmd.Op == "end" {
+ changes["ended_at"] = now
+ return changes, nil
+ }
+
+ // The stored slide number is the hint for a slide deleted since:
+ // the talk lands on the one that followed it (deck.SettleNear).
+ pos := deck.SettleNear(view, positionOf(cur), cur.Slide)
+ move, isMove := moveOps[cmd.Op]
+ switch {
+ case isMove:
+ mv := deck.Move{Op: move}
+ if cmd.Op == "goto" {
+ id, err := gotoTarget(view, cmd.Slide)
+ if err != nil {
+ return nil, err
+ }
+ mv.Slide = id
+ }
+ pos = deck.Advance(view, pos, mv)
+ case cmd.Op == "blackout":
+ pos = deck.Advance(view, pos, deck.Move{Op: "black"})
+ case cmd.Op == "mode":
+ pos = deck.Advance(view, pos, deck.Move{Op: "mode"})
+ case cmd.Op == "resume":
+ // The window that moved offline wins (S18): its position,
+ // settled into the deck as the server has it.
+ mode := deck.Mode(cmd.AtMode)
+ if mode == "" {
+ mode = pos.Mode
+ }
+ pos = deck.Settle(view, deck.Position{Slide: cmd.AtSlide, Step: cmd.AtStep, Mode: mode, Black: pos.Black})
+ isMove = true
+ case cmd.Op == "timer-reset":
+ changes["timer_at"] = nil
+ default:
+ return nil, errBadCommand
+ }
+ if isMove && cur.TimerAt == nil {
+ changes["timer_at"] = now
+ }
+ changes["slide_id"] = pos.Slide
+ changes["step"] = pos.Step
+ changes["mode"] = string(pos.Mode)
+ changes["blackout"] = pos.Black
+ changes["slide"] = fullIndex(view, pos.Slide)
+ return changes, nil
+}
+
+// positionOf is the row's position.
+func positionOf(p Presentation) deck.Position {
+ mode := deck.Mode(p.Mode)
+ if mode != deck.ModeFull {
+ mode = deck.ModeCore
+ }
+ return deck.Position{Slide: p.SlideID, Step: p.Step, Mode: mode, Black: p.Blackout}
+}
+
+// gotoTarget is the slide a goto names: a slide's id, or its 1-based
+// number in the full talk, which is what a scriptless form sends. An id
+// the deck no longer has passes through, and deck.Advance leaves the
+// talk where it is; a number outside the talk is refused, as it always
+// was.
+func gotoTarget(view *deck.Deck, slide string) (string, error) {
+ if slide == "" {
+ return "", errBadCommand
+ }
+ for _, s := range view.Slides {
+ if s.ID == slide {
+ return slide, nil
+ }
+ }
+ if n, err := strconv.Atoi(slide); err == nil {
+ full := deck.TalkOrder(view, deck.ModeFull)
+ if n < 1 || n > len(full) {
+ return "", errBadCommand
+ }
+ return view.Slides[full[n-1]].ID, nil
+ }
+ return slide, nil
+}
+
+// fullIndex is the 0-based place of the slide with this id in the full
+// talk: the value Presentation.Slide holds, so that slide number N means
+// the same slide to every page. 0 for nowhere (an empty talk).
+func fullIndex(view *deck.Deck, id string) int {
+ for n, i := range deck.TalkOrder(view, deck.ModeFull) {
+ if view.Slides[i].ID == id {
+ return n
+ }
+ }
+ return 0
+}
+
+// startPosition is where a new session begins: deck.Start, with the
+// stored slide number in step with it.
+func startPosition(view *deck.Deck) (deck.Position, int) {
+ start := deck.Start(view)
+ return start, fullIndex(view, start.Slide)
+}
diff --git a/internal/slidestest/browser_present_test.go b/internal/slidestest/browser_present_test.go
index b9cedfa..1fec644 100644
--- a/internal/slidestest/browser_present_test.go
+++ b/internal/slidestest/browser_present_test.go
@@ -16,6 +16,7 @@ import (
"testing"
"time"
+ "amadan.net/rastrillo/rastrillo/harness"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
@@ -26,8 +27,8 @@ import (
// than a long document: its slide is bounded by the viewport and its
// controls are overlaid where the presenter can still reach them.
func TestBrowserProjectorFitsTheViewport(t *testing.T) {
- rig, mailer := newRig(t)
- browserSignIn(t, rig, mailer)
+ rig, served := newRigApp(t, nil)
+ browserSignIn(t, rig, served.mailer)
var deck string
rig.Run(chromedp.Evaluate(`(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`, &deck))
@@ -35,17 +36,7 @@ func TestBrowserProjectorFitsTheViewport(t *testing.T) {
t.Fatalf("the deck list links no deck: %q", deck)
}
- var path string
- rig.Run(
- chromedp.Navigate(rig.Origin+deck+"?slide=1"),
- chromedp.Click(`form[action$="/present"] button`, chromedp.ByQuery),
- waitFor(`location.pathname.endsWith('/notes')`),
- chromedp.Evaluate(`location.pathname + location.search`, &path),
- )
- m := notesLocation.FindStringSubmatch(path)
- if m == nil {
- t.Fatalf("Present landed on %q, want /p/{session}/notes?t={token}", path)
- }
+ session, token := browserPresent(t, rig, served, deck)
for _, viewport := range []struct{ width, height int }{{1920, 1080}, {1280, 720}} {
t.Run(fmt.Sprintf("%dx%d", viewport.width, viewport.height), func(t *testing.T) {
@@ -58,7 +49,7 @@ func TestBrowserProjectorFitsTheViewport(t *testing.T) {
}
rig.Run(
emulation.SetDeviceMetricsOverride(int64(viewport.width), int64(viewport.height), 1, false),
- chromedp.Navigate(rig.Origin+m[1]+"?t="+m[2]),
+ chromedp.Navigate(rig.Origin+session+"?t="+token),
chromedp.WaitVisible(`[slides-bar]`, chromedp.ByQuery),
chromedp.Evaluate(`(() => {
window.scrollTo(0, 1);
@@ -82,7 +73,27 @@ func TestBrowserProjectorFitsTheViewport(t *testing.T) {
}
}
-var notesLocation = regexp.MustCompile(`^(/p/[23456789abcdefghjkmnpqrstuvwxyz]{10})/notes\?t=([A-Za-z0-9_-]{43})$`)
+// sessionLocation is where Present lands: the session's own slide (S12).
+var sessionLocation = regexp.MustCompile(`^/p/[23456789abcdefghjkmnpqrstuvwxyz]{10}$`)
+
+// browserPresent presses Present on the deck the browser is signed in
+// to, waits for the slide it lands on, and pairs a phone through the
+// row (pairThroughRow). It returns the session's path, /p/{session},
+// and the remote token.
+func browserPresent(t *testing.T, rig *harness.Rig, served *testApp, deck string) (string, string) {
+ t.Helper()
+ var path string
+ rig.Run(
+ chromedp.Navigate(rig.Origin+deck+"?slide=1"),
+ chromedp.Click(`form[action$="/present"] button`, chromedp.ByQuery),
+ waitFor(`/^\/p\/[^/]+$/.test(location.pathname)`),
+ chromedp.Evaluate(`location.pathname + location.search`, &path),
+ )
+ if !sessionLocation.MatchString(path) {
+ t.Fatalf("Present landed on %q, want /p/{session}", path)
+ }
+ return path, pairThroughRow(t, served, path[len("/p/"):])
+}
// TestBrowserPresentingScreensHoldStill: the presenter view and the
// phone remote each load once and then stay put while nothing
@@ -90,8 +101,8 @@ var notesLocation = regexp.MustCompile(`^(/p/[23456789abcdefghjkmnpqrstuvwxyz]{1
// which is how those two pages follow a talk (present.js reloads them
// rather than re-rendering two slides and the notes itself).
func TestBrowserPresentingScreensHoldStill(t *testing.T) {
- rig, mailer := newRig(t)
- browserSignIn(t, rig, mailer)
+ rig, served := newRigApp(t, nil)
+ browserSignIn(t, rig, served.mailer)
// Every top-level navigation the tab makes, reloads included.
var loads atomic.Int64
@@ -107,18 +118,8 @@ func TestBrowserPresentingScreensHoldStill(t *testing.T) {
t.Fatalf("the deck list links no deck: %q", deck)
}
- var path string
- rig.Run(
- chromedp.Navigate(rig.Origin+deck+"?slide=1"),
- chromedp.Click(`form[action$="/present"] button`, chromedp.ByQuery),
- waitFor(`location.pathname.endsWith('/notes')`),
- chromedp.Evaluate(`location.pathname + location.search`, &path),
- )
- m := notesLocation.FindStringSubmatch(path)
- if m == nil {
- t.Fatalf("Present landed on %q, want /p/{session}/notes?t={token}", path)
- }
- session, token := m[1], m[2]
+ session, token := browserPresent(t, rig, served, deck)
+ rig.Run(chromedp.Navigate(rig.Origin + session + "/notes?t=" + token))
// holdsStill waits for the page to settle and the stream to have
// said its piece (one event on connect), then counts loads over a
diff --git a/internal/slidestest/present_position_test.go b/internal/slidestest/present_position_test.go
new file mode 100644
index 0000000..573e447
--- /dev/null
+++ b/internal/slidestest/present_position_test.go
@@ -0,0 +1,562 @@
+package slidestest
+
+import (
+ "bufio"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// pressAnswer is the server's answer to a press asked for as JSON: the
+// talk's absolute position after it, the session's own sequence and the
+// deck's (presenting_position.go's positionAnswer).
+type pressAnswer struct {
+ Slide string `json:"slide"`
+ Step int `json:"step"`
+ Mode string `json:"mode"`
+ Black bool `json:"black"`
+ Seq int64 `json:"seq"`
+ DeckSeq int64 `json:"deckSeq"`
+}
+
+// newPressID is what a window sends with each press: 16 random bytes,
+// base64url, so a press sent twice can be told from two presses.
+func newPressID(t *testing.T) string {
+ t.Helper()
+ raw := make([]byte, 16)
+ if _, err := rand.Read(raw); err != nil {
+ t.Fatalf("press id: %v", err)
+ }
+ return base64.RawURLEncoding.EncodeToString(raw)
+}
+
+// pressRequest is one press as a window posts it: a form, asking for
+// JSON, with a browser's same-origin evidence. token is sent when it is
+// not empty and cookies when there are some, because who may drive is
+// half of what these tests are about.
+func pressRequest(t *testing.T, a *testApp, session, token string, form url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder {
+ t.Helper()
+ body := url.Values{}
+ for k, vs := range form {
+ body[k] = vs
+ }
+ if token != "" {
+ body.Set("t", token)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/p/"+session+"/command", strings.NewReader(body.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, req)
+ return rec
+}
+
+// press sends one press and insists on a JSON position back.
+func press(t *testing.T, a *testApp, session, token string, form url.Values, cookies []*http.Cookie) pressAnswer {
+ t.Helper()
+ rec := pressRequest(t, a, session, token, form, cookies)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("press %v: status %d, want 200\n%s", form, rec.Code, rec.Body)
+ }
+ if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
+ t.Fatalf("press %v: Content-Type %q, want JSON", form, ct)
+ }
+ var out pressAnswer
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+ t.Fatalf("press %v: %v\n%s", form, err, rec.Body)
+ }
+ return out
+}
+
+// op is a press's form: the op and a fresh press id.
+func op(t *testing.T, name string) url.Values {
+ return url.Values{"op": {name}, "press": {newPressID(t)}}
+}
+
+// stepsDeck is a talk to press through, made over the API: "steps"
+// with four presses, "plain" with none, "extra" for the full talk only,
+// "parked" in no talk, and "last". It returns the deck's path.
+func stepsDeck(t *testing.T, a *testApp, cookies []*http.Cookie) string {
+ t.Helper()
+ token := mintAgent(t, a, cookies, "steps-deck")
+ sqid := apiDeck(t, a, token, "Steps")
+ view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK)
+ slides, _ := view["slides"].([]any)
+ var ops []string
+ for _, s := range slides {
+ id, _ := s.(map[string]any)["id"].(string)
+ ops = append(ops, `{"op":"remove_slide","id":`+quote(id)+`}`)
+ }
+ ops = append(ops, `{"op":"add_slide","id":"steps","layout":"flow","template":"title-body"}`)
+ for i, word := range []string{"one", "two", "three", "four"} {
+ id := quote("b" + string(rune('1'+i)))
+ ops = append(ops,
+ `{"op":"add_block","slide":"steps","id":`+id+`,"type":"text","region":"body","markdown":`+quote(word)+`}`,
+ `{"op":"set_block","slide":"steps","id":`+id+`,"step":`+string(rune('1'+i))+`}`)
+ }
+ for _, id := range []string{"plain", "extra", "parked", "last"} {
+ ops = append(ops, `{"op":"add_slide","id":`+quote(id)+`,"layout":"flow","template":"title-body"}`)
+ }
+ ops = append(ops,
+ `{"op":"set_slide","id":"extra","talk":"full"}`,
+ `{"op":"set_slide","id":"parked","talk":"parked"}`)
+ apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK)
+ return "/d/" + sqid
+}
+
+// rowPosition reads the session's position straight off its row.
+func rowPosition(t *testing.T, a *testApp, session string) (slideID string, step int, seq int64) {
+ t.Helper()
+ row := a.db.G.Raw("SELECT slide_id, step, seq FROM presentations WHERE sqid = ?", session).Row()
+ if err := row.Scan(&slideID, &step, &seq); err != nil {
+ t.Fatalf("read the session's position: %v", err)
+ }
+ return slideID, step, seq
+}
+
+// openStream opens the session's SSE stream on a real server.
+func openStream(t *testing.T, a *testApp, path string) *bufio.Reader {
+ t.Helper()
+ srv := httptest.NewServer(a)
+ t.Cleanup(srv.Close)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ t.Cleanup(cancel)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil)
+ if err != nil {
+ t.Fatalf("build the stream request: %v", err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("open the stream: %v", err)
+ }
+ t.Cleanup(func() { resp.Body.Close() })
+ return bufio.NewReader(resp.Body)
+}
+
+// streamEvent is the stream's event, with the position fields.
+type streamEvent struct {
+ Slide int `json:"slide"`
+ Blackout bool `json:"blackout"`
+ Ended bool `json:"ended"`
+ SlideID string `json:"slideId"`
+ Step int `json:"step"`
+ Mode string `json:"mode"`
+ Seq int64 `json:"seq"`
+}
+
+func nextPositionEvent(t *testing.T, r *bufio.Reader) streamEvent {
+ t.Helper()
+ var e streamEvent
+ data := nextSlideEvent(t, r)
+ if err := json.Unmarshal([]byte(data), &e); err != nil {
+ t.Fatalf("the stream's event %q: %v", data, err)
+ }
+ return e
+}
+
+// TestLaptopAndPhoneCrossingPressesBothCount: the laptop and the phone
+// both press next from step 2 of a four-step slide at the same moment.
+// The server orders them, so the talk reaches step 4 rather than one
+// of the presses being lost (S18).
+func TestLaptopAndPhoneCrossingPressesBothCount(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ press(t, a, session, token, op(t, "next"), nil)
+ at := press(t, a, session, token, op(t, "next"), nil)
+ if at.Slide != "steps" || at.Step != 2 {
+ t.Fatalf("two nexts reached %+v, want steps at step 2", at)
+ }
+
+ var wg sync.WaitGroup
+ answers := make([]pressAnswer, 2)
+ codes := make([]int, 2)
+ start := make(chan struct{})
+ for i := range 2 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ var rec *httptest.ResponseRecorder
+ if i == 0 {
+ rec = pressRequest(t, a, session, "", op(t, "next"), cookies) // the laptop
+ } else {
+ rec = pressRequest(t, a, session, token, op(t, "next"), nil) // the phone
+ }
+ codes[i] = rec.Code
+ _ = json.Unmarshal(rec.Body.Bytes(), &answers[i])
+ }()
+ }
+ close(start)
+ wg.Wait()
+
+ for i, code := range codes {
+ if code != http.StatusOK {
+ t.Fatalf("press %d: status %d, want 200", i, code)
+ }
+ }
+ if answers[0].Seq == answers[1].Seq {
+ t.Errorf("both presses answered seq %d; each press must move the sequence", answers[0].Seq)
+ }
+ slide, step, seq := rowPosition(t, a, session)
+ if slide != "steps" || step != 4 {
+ t.Errorf("after two crossing presses the talk is at %s step %d, want steps step 4", slide, step)
+ }
+ if seq != at.Seq+2 {
+ t.Errorf("after two crossing presses seq is %d, want %d", seq, at.Seq+2)
+ }
+}
+
+// TestAPressSentTwiceCountsOnce: a window that did not hear its answer
+// sends the same press again. The second answers where the talk is,
+// moves nothing, publishes nothing and leaves the sequence alone. Only
+// the newest 64 ids are kept per session.
+func TestAPressSentTwiceCountsOnce(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+ events := openStream(t, a, "/p/"+session+"/stream")
+ nextPositionEvent(t, events) // the connect event
+
+ form := op(t, "next")
+ first := press(t, a, session, token, form, nil)
+ again := press(t, a, session, token, form, nil)
+ if again != first {
+ t.Errorf("the press sent again answered %+v, want the same position %+v", again, first)
+ }
+ if first.Slide != "steps" || first.Step != 1 {
+ t.Errorf("one next answered %+v, want steps at step 1", first)
+ }
+ if _, step, seq := rowPosition(t, a, session); step != 1 || seq != first.Seq {
+ t.Errorf("after a repeated press the row is at step %d seq %d, want step 1 seq %d", step, seq, first.Seq)
+ }
+
+ // The stream heard the first and nothing for the second: the event
+ // after the first press's is the next press's own.
+ if e := nextPositionEvent(t, events); e.Seq != first.Seq || e.Step != 1 || e.SlideID != "steps" {
+ t.Errorf("the first press's event is %+v, want steps step 1 seq %d", e, first.Seq)
+ }
+ second := press(t, a, session, token, op(t, "next"), nil)
+ if e := nextPositionEvent(t, events); e.Seq != second.Seq {
+ t.Errorf("the event after the repeat is seq %d, want the next press's seq %d", e.Seq, second.Seq)
+ }
+
+ // A malformed press id is refused, and moves nothing.
+ bad := url.Values{"op": {"next"}, "press": {"short"}}
+ if rec := pressRequest(t, a, session, token, bad, nil); rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("a press id of %q: status %d, want 422", "short", rec.Code)
+ }
+
+ // Sixty-four more presses push the first id out, and the table
+ // keeps sixty-four for the session.
+ for range 64 {
+ press(t, a, session, token, op(t, "blackout"), nil)
+ }
+ var kept int64
+ if err := a.db.G.Raw(`SELECT COUNT(*) FROM presentation_presses
+ WHERE presentation_id = (SELECT id FROM presentations WHERE sqid = ?)`, session).Scan(&kept).Error; err != nil {
+ t.Fatalf("count press ids: %v", err)
+ }
+ if kept != 64 {
+ t.Errorf("the session keeps %d press ids, want 64", kept)
+ }
+ _, _, before := rowPosition(t, a, session)
+ if late := press(t, a, session, token, form, nil); late.Seq != before+1 {
+ t.Errorf("a press id older than the newest 64 answered seq %d, want it counted as new (%d)", late.Seq, before+1)
+ }
+}
+
+// TestResumeTakesTheWindowsPosition: a window that pressed while the
+// network was down sends resume with where it got to, and the server
+// takes it, settled into the deck.
+func TestResumeTakesTheWindowsPosition(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ press(t, a, session, token, op(t, "next"), nil) // the phone, meanwhile
+
+ form := op(t, "resume")
+ form.Set("at_slide", "extra")
+ form.Set("at_step", "0")
+ form.Set("at_mode", "full")
+ got := press(t, a, session, "", form, cookies)
+ if got.Slide != "extra" || got.Step != 0 || got.Mode != "full" {
+ t.Errorf("resume answered %+v, want extra step 0 in full", got)
+ }
+ // The stored number is the slide's place in the full talk.
+ surface := mustGet(t, a, "/p/"+session, http.StatusOK, nil).Body.String()
+ if !strings.Contains(surface, `data-slide="3"`) {
+ t.Errorf("after resuming on the third slide of the full talk the surface does not say slide 3:\n%s", surface)
+ }
+
+ // A step past the slide's presses settles onto its last.
+ form = op(t, "resume")
+ form.Set("at_slide", "steps")
+ form.Set("at_step", "9")
+ form.Set("at_mode", "core")
+ if got := press(t, a, session, "", form, cookies); got.Slide != "steps" || got.Step != 4 || got.Mode != "core" {
+ t.Errorf("resume past the last press answered %+v, want steps step 4 in core", got)
+ }
+
+ // A mode that is not one is refused.
+ form = op(t, "resume")
+ form.Set("at_slide", "steps")
+ form.Set("at_mode", "sideways")
+ if rec := pressRequest(t, a, session, "", form, cookies); rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("resume in mode sideways: status %d, want 422", rec.Code)
+ }
+}
+
+// TestPresentAgainLeavesThePhonePaired: pressing Present again rejoins
+// the talk and leaves the phone's token working (S19).
+func TestPresentAgainLeavesThePhonePaired(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ path := sampleDeck(t, a, cookies)
+ session, token := startPresenting(t, a, path, cookies)
+
+ rec := post(t, a, path+"/present", nil, cookies...)
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("pressing Present again: status %d, want 303\n%s", rec.Code, rec.Body)
+ }
+ if loc := rec.Header().Get("Location"); loc != "/p/"+session {
+ t.Errorf("pressing Present again went to %q, want the same talk /p/%s", loc, session)
+ }
+ if rec := command(t, a, session, "next", token, "", nil); rec.Code != http.StatusNoContent {
+ t.Errorf("the phone's token after Present again: status %d, want 204", rec.Code)
+ }
+}
+
+// TestARevokedTokenDrivesNothing: once the phone's token is replaced, the
+// old one moves nothing and reads nothing.
+func TestARevokedTokenDrivesNothing(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, old := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+ press(t, a, session, old, op(t, "next"), nil)
+ pairThroughRow(t, a, session)
+
+ _, _, before := rowPosition(t, a, session)
+ if rec := pressRequest(t, a, session, old, op(t, "next"), nil); rec.Code != http.StatusNotFound {
+ t.Errorf("a press with a replaced token: status %d, want 404", rec.Code)
+ }
+ if rec := command(t, a, session, "next", old, "", nil); rec.Code != http.StatusNotFound {
+ t.Errorf("a form command with a replaced token: status %d, want 404", rec.Code)
+ }
+ mustGet(t, a, "/p/"+session+"/remote?t="+old, http.StatusNotFound, nil)
+ if slide, step, seq := rowPosition(t, a, session); slide != "steps" || step != 1 || seq != before {
+ t.Errorf("a replaced token moved the talk to %s step %d seq %d", slide, step, seq)
+ }
+}
+
+// TestTheSignedInPresenterMayDriveWithoutAToken: the presenter's own
+// session is enough to drive their own talk (S19).
+func TestTheSignedInPresenterMayDriveWithoutAToken(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, _ := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ got := press(t, a, session, "", op(t, "next"), cookies)
+ if got.Slide != "steps" || got.Step != 1 {
+ t.Errorf("the presenter's press answered %+v, want steps step 1", got)
+ }
+ // And a form with no JSON asked for keeps the old answers.
+ rec := post(t, a, "/p/"+session+"/command", url.Values{"op": {"next"}}, cookies...)
+ if rec.Code != http.StatusSeeOther && rec.Code != http.StatusNoContent {
+ t.Errorf("the presenter's form press: status %d, want 303 or 204\n%s", rec.Code, rec.Body)
+ }
+ if _, step, _ := rowPosition(t, a, session); step != 2 {
+ t.Errorf("after the presenter's two presses the talk is at step %d, want 2", step)
+ }
+}
+
+// TestSomeoneElseSignedInMayNotDrive: being signed in is not being the
+// presenter.
+func TestSomeoneElseSignedInMayNotDrive(t *testing.T) {
+ a := newSharedApp(t)
+ mine := signedIn(t, a, allowedAddress)
+ theirs := signedIn(t, a, otherAddress)
+ session, _ := startPresenting(t, a, stepsDeck(t, a, mine), mine)
+
+ if rec := pressRequest(t, a, session, "", op(t, "next"), theirs); rec.Code != http.StatusNotFound {
+ t.Errorf("somebody else's press: status %d, want 404", rec.Code)
+ }
+ if rec := pressRequest(t, a, session, "", op(t, "next"), nil); rec.Code != http.StatusNotFound {
+ t.Errorf("a press from nobody: status %d, want 404", rec.Code)
+ }
+ if _, step, _ := rowPosition(t, a, session); step != 0 {
+ t.Errorf("a refused press moved the talk to step %d", step)
+ }
+}
+
+// TestACrossSitePressIsRefused: the presenter's cookie makes a press
+// from their browser enough, so another site must not be able to make
+// that browser press. The app-wide origin check refuses it.
+func TestACrossSitePressIsRefused(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, _ := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ form := op(t, "next")
+ req := httptest.NewRequest(http.MethodPost, "/p/"+session+"/command", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Origin", "https://elsewhere.example")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("a cross-site press with the presenter's cookie: status %d, want 403", rec.Code)
+ }
+ if _, step, _ := rowPosition(t, a, session); step != 0 {
+ t.Errorf("a cross-site press moved the talk to step %d", step)
+ }
+}
+
+// TestCommandsOnAnEmptyTalk: a deck with no slides, or with every slide
+// parked, has nowhere to go, and every press still answers without an
+// error.
+func TestCommandsOnAnEmptyTalk(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+
+ parked := stepsDeck(t, a, cookies)
+ token := mintAgent(t, a, cookies, "park-everything")
+ sqid := strings.TrimPrefix(parked, "/d/")
+ var ops []string
+ for _, id := range []string{"steps", "plain", "extra", "last"} {
+ ops = append(ops, `{"op":"set_slide","id":`+quote(id)+`,"talk":"parked"}`)
+ }
+ apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK)
+
+ for name, path := range map[string]string{
+ "empty": strings.TrimSuffix(emptyDeck(t, a, cookies), "/edit"),
+ "parked": parked,
+ } {
+ t.Run(name, func(t *testing.T) {
+ session, token := startPresenting(t, a, path, cookies)
+ for _, name := range []string{"next", "prev", "first", "last", "mode", "blackout", "timer-reset", "resume", "goto"} {
+ form := op(t, name)
+ if name == "goto" {
+ form.Set("slide", "parked")
+ }
+ if name == "resume" {
+ form.Set("at_slide", "steps")
+ }
+ got := press(t, a, session, token, form, nil)
+ if got.Slide != "" || got.Step != 0 {
+ t.Errorf("%s on an empty talk answered %+v, want nowhere", name, got)
+ }
+ }
+ mustGet(t, a, "/p/"+session, http.StatusOK, nil)
+ })
+ }
+}
+
+// TestASessionFromBeforeTheDeployKeepsItsIndex: a talk begun before
+// positions existed carries on by its index for its remaining hours,
+// and the new presses are not ones it knows.
+func TestASessionFromBeforeTheDeployKeepsItsIndex(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ path := sampleDeck(t, a, cookies)
+ session, token := startPresenting(t, a, path, cookies)
+ // What migration 0009 leaves on a row that was already there: the
+ // new columns, all NULL.
+ if err := a.db.G.Exec(`UPDATE presentations
+ SET positional = NULL, slide_id = NULL, step = NULL, mode = NULL, seq = NULL, timer_at = NULL, slide = 2
+ WHERE sqid = ?`, session).Error; err != nil {
+ t.Fatalf("make the session a pre-deploy one: %v", err)
+ }
+
+ if rec := command(t, a, session, "next", token, "", nil); rec.Code != http.StatusNoContent {
+ t.Fatalf("next on a pre-deploy session: status %d, want 204\n%s", rec.Code, rec.Body)
+ }
+ surface := mustGet(t, a, "/p/"+session, http.StatusOK, nil).Body.String()
+ if !strings.Contains(surface, "4 / 8") {
+ t.Errorf("next from index 2 does not show slide 4:\n%s", surface)
+ }
+ var untouched int64
+ if err := a.db.G.Raw(`SELECT COUNT(*) FROM presentations WHERE sqid = ?
+ AND positional IS NULL AND slide_id IS NULL AND seq IS NULL AND timer_at IS NULL`, session).Scan(&untouched).Error; err != nil {
+ t.Fatalf("read the session: %v", err)
+ }
+ if untouched != 1 {
+ t.Error("a pre-deploy session gained a position, a sequence or a timer")
+ }
+ for _, name := range []string{"first", "last", "mode", "timer-reset", "resume"} {
+ if rec := command(t, a, session, name, token, "", nil); rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("%s on a pre-deploy session: status %d, want 422", name, rec.Code)
+ }
+ }
+ // The presenter's cookie is not a capability there either: it is
+ // today's path, and today the token is the whole permission.
+ if rec := pressRequest(t, a, session, "", op(t, "next"), cookies); rec.Code != http.StatusNotFound {
+ t.Errorf("a tokenless press on a pre-deploy session: status %d, want 404", rec.Code)
+ }
+}
+
+// TestTheFirstPressStartsTheTimer: the timer starts at the first move,
+// not when the session opens, and timer-reset clears it until the next.
+func TestTheFirstPressStartsTheTimer(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+
+ timerSet := func() bool {
+ t.Helper()
+ var n int64
+ if err := a.db.G.Raw("SELECT COUNT(*) FROM presentations WHERE sqid = ? AND timer_at IS NOT NULL", session).Scan(&n).Error; err != nil {
+ t.Fatalf("read the timer: %v", err)
+ }
+ return n == 1
+ }
+ timerAt := func() string {
+ t.Helper()
+ var at string
+ if err := a.db.G.Raw("SELECT timer_at FROM presentations WHERE sqid = ?", session).Row().Scan(&at); err != nil {
+ t.Fatalf("read the timer: %v", err)
+ }
+ return at
+ }
+
+ if timerSet() {
+ t.Fatal("the timer runs before anybody pressed anything")
+ }
+ press(t, a, session, token, op(t, "next"), nil)
+ if !timerSet() {
+ t.Fatal("the first press did not start the timer")
+ }
+ started := timerAt()
+ time.Sleep(5 * time.Millisecond)
+ press(t, a, session, token, op(t, "next"), nil)
+ if again := timerAt(); again != started {
+ t.Errorf("a later press restarted the timer: %s then %s", started, again)
+ }
+ press(t, a, session, token, op(t, "timer-reset"), nil)
+ if timerSet() {
+ t.Error("timer-reset left the timer running")
+ }
+ press(t, a, session, token, op(t, "prev"), nil)
+ if !timerSet() {
+ t.Error("the first press after a reset did not start the timer")
+ }
+}
diff --git a/internal/slidestest/present_test.go b/internal/slidestest/present_test.go
index c261f6a..26b053c 100644
--- a/internal/slidestest/present_test.go
+++ b/internal/slidestest/present_test.go
@@ -3,6 +3,10 @@ package slidestest
import (
"bufio"
"context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
"net/http"
"net/http/httptest"
"net/url"
@@ -13,12 +17,10 @@ import (
)
// presentLocation is what POST /d/{sqid}/present redirects to: the
-// presenter view for the new session, carrying the remote's capability
-// once. Both halves are captured because every later request in these
-// tests is one or the other — the session sqid is the address, and the
-// token is the permission.
+// session's own slide (S12). It carries no capability: the presenter
+// drives by being signed in, and a phone is paired separately.
var presentLocation = regexp.MustCompile(
- `^/p/([23456789abcdefghjkmnpqrstuvwxyz]{10})/notes\?t=([A-Za-z0-9_-]{43})$`)
+ `^/p/([23456789abcdefghjkmnpqrstuvwxyz]{10})$`)
// pairingCode finds the six-character code on the presenter view. The
// alphabet is the unambiguous one (no O, no 0, no I, no 1), because a
@@ -42,7 +44,7 @@ func codeOn(t *testing.T, page string) string {
}
// startPresenting presses Present on a deck and returns the session's
-// sqid and the remote token it was shown once.
+// sqid and a freshly paired remote token (pairThroughRow).
func startPresenting(t *testing.T, a *testApp, deckPath string, cookies []*http.Cookie) (string, string) {
t.Helper()
rec := post(t, a, deckPath+"/present", nil, cookies...)
@@ -52,9 +54,32 @@ func startPresenting(t *testing.T, a *testApp, deckPath string, cookies []*http.
loc := rec.Header().Get("Location")
m := presentLocation.FindStringSubmatch(loc)
if m == nil {
- t.Fatalf("POST %s/present: Location = %q, want /p/{session}/notes?t={token}", deckPath, loc)
+ t.Fatalf("POST %s/present: Location = %q, want /p/{session}", deckPath, loc)
}
- return m[1], m[2]
+ return m[1], pairThroughRow(t, a, m[1])
+}
+
+// pairThroughRow pairs a phone with a session the interim way: it mints
+// a remote token and writes the token's hash straight onto the row, as
+// Present used to, and returns the token. Replacing the session's token
+// is also how a test revokes the old one.
+//
+// It is the suite's one way to get a remote token until
+// POST /p/{session}/pair exists (Task 13), which replaces this body.
+func pairThroughRow(t *testing.T, a *testApp, session string) string {
+ t.Helper()
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ t.Fatalf("mint a remote token: %v", err)
+ }
+ token := base64.RawURLEncoding.EncodeToString(raw)
+ sum := sha256.Sum256([]byte(token))
+ res := a.db.G.Exec("UPDATE presentations SET remote_token_hash = ? WHERE sqid = ?",
+ hex.EncodeToString(sum[:]), session)
+ if res.Error != nil || res.RowsAffected != 1 {
+ t.Fatalf("pair a phone with %s: %v (%d rows)", session, res.Error, res.RowsAffected)
+ }
+ return token
}
// command posts one remote command as the phone does: a form, with the
@@ -316,10 +341,11 @@ func TestWrongRemoteTokenIs404(t *testing.T) {
}
mustGet(t, a, "/p/"+session+"/remote?t="+wrong, http.StatusNotFound, nil)
mustGet(t, a, "/p/"+session+"/remote", http.StatusNotFound, nil)
- // Signed in as the presenter is not the same as holding the remote:
- // the capability is what moves the deck.
+ // With nobody signed in, the token is the whole permission (the
+ // presenter's own session may drive too: TestTheSignedInPresenter-
+ // MayDriveWithoutAToken), so asking twice changes nothing.
if rec := command(t, a, session, "next", wrong, "", nil); rec.Code != http.StatusNotFound {
- t.Errorf("a command with the wrong token from the presenter: status %d, want 404", rec.Code)
+ t.Errorf("a second command with the wrong token: status %d, want 404", rec.Code)
}
// And nothing moved.