package slidestest
// Clips (scenes and clips spec §2, §4; plan call R3, Review Focus 5): a
// short muted video uploaded to a deck with the picture of its first
// frame as its poster, served in ranges so a browser can seek it, and
// drawn as that poster wherever no video plays: scripts off, a
// thumbnail, the PDF.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"amadan.net/rastrillo/rastrillo/blobs"
"amadan.net/oficina/slides/internal/slides/deck"
"amadan.net/oficina/slides/internal/slides/layout"
)
// fakeWebM opens as a WebM does (an EBML header whose DocType is webm),
// so it registers as a clip, and is nothing a browser can play after
// that: Review Focus 5's video that won't play.
func fakeWebM() []byte {
head := []byte{
0x1a, 0x45, 0xdf, 0xa3, 0x9f,
0x42, 0x86, 0x81, 0x01, 0x42, 0xf7, 0x81, 0x01, 0x42, 0xf2, 0x81, 0x04, 0x42, 0xf3, 0x81, 0x08,
0x42, 0x82, 0x84, 'w', 'e', 'b', 'm', 0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02,
}
return append(head, bytes.Repeat([]byte("not a frame of video "), 64)...)
}
// colourPNG is a 2 by 2 PNG of one colour: a picture whose bytes are
// not onePixelPNG's.
func colourPNG(t *testing.T, c color.Color) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
for x := 0; x < 2; x++ {
for y := 0; y < 2; y++ {
img.Set(x, y, c)
}
}
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
// clipAlt is the clip's description, which its poster carries.
const clipAlt = "A screen recording"
// uploadClip runs the editor's clip upload over HTTP: the poster first,
// a decorative picture, then the video naming it. It returns both
// records the server validated.
func uploadClip(t *testing.T, a *testApp, deckPath string, cookies []*http.Cookie, video []byte) (rec, poster map[string]any) {
t.Helper()
posterKey := stageUpload(t, a, deckPath, cookies, "clip.png", "image/png", onePixelPNG)
reg := postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.png","width":1,"height":1,"alt":"","decorative":true}`, posterKey), cookies)
if reg.Code != http.StatusOK {
t.Fatalf("register the poster: %d\n%s", reg.Code, reg.Body)
}
poster = jsonBody(t, reg)
key := stageUpload(t, a, deckPath, cookies, "clip.webm", "video/webm", video)
reg = postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`,
key, clipAlt, poster["ref"]), cookies)
if reg.Code != http.StatusOK {
t.Fatalf("register the clip: %d\n%s", reg.Code, reg.Body)
}
return jsonBody(t, reg), poster
}
// clipFixture is clipDeck's deck: the clip's two records and its slides.
type clipFixture struct {
sqid string
video, poster map[string]any
}
// clipDeck is a deck over the API showing video as a clip:
//
// - slide press1: the clip played on a press (box A), and a heading;
// - slide loop2: the clip in a loop;
// - slide once3: the clip played once;
// - slide after4: a heading.
func clipDeck(t *testing.T, a *testApp, cookies []*http.Cookie, token string, video []byte) clipFixture {
t.Helper()
f := clipFixture{sqid: apiDeck(t, a, token, "Clips")}
f.video, f.poster = uploadClip(t, a, "/d/"+f.sqid, cookies, video)
view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK)
var ops []string
for _, s := range view["slides"].([]any) {
ops = append(ops, `{"op":"remove_slide","id":`+quote(s.(map[string]any)["id"].(string))+`}`)
}
ops = append(ops,
fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.png","width":1,"height":1,"alt":""}`, f.poster["id"], f.poster["ref"]),
fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`,
f.video["id"], f.video["ref"], clipAlt, f.video["poster"]))
clip := func(slide, block, play string) []string {
return []string{
`{"op":"add_slide","id":"` + slide + `","layout":"canvas"}`,
`{"op":"add_block","slide":"` + slide + `","id":"` + block + `","type":"clip","box":` + boxA +
`,"props":{"asset":` + quote(f.video["id"].(string)) + `,"play":"` + play + `"}}`,
}
}
ops = append(ops, clip("press1", "clippress", "press")...)
ops = append(ops, `{"op":"add_block","slide":"press1","id":"presshead","type":"heading","box":{"x":0.1,"y":0.75,"w":0.8,"h":0.1},"props":{"level":2},"markdown":"Pressed"}`)
ops = append(ops, clip("loop2", "cliploop", "loop")...)
ops = append(ops, clip("once3", "cliponce", "once")...)
ops = append(ops, `{"op":"add_slide","id":"after4","layout":"flow","template":"title"}`,
`{"op":"add_block","slide":"after4","id":"afterhead","type":"heading","region":"heading","props":{"level":1},"markdown":"After"}`)
apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+f.sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK)
return f
}
// TestClipUploadsAreRefused: a clip is an MP4 or a WebM of at most
// 50 MiB with a poster this deck already holds, a PNG or WebP. Each
// refusal is a code, and spends nothing: the receipt is still there for
// the registration that gets it right.
func TestClipUploadsAreRefused(t *testing.T) {
a := newAppWithStore(t, dirStore(t))
cookies := signedIn(t, a, allowedAddress)
deckPath := createDeck(t, a, cookies, "Clips")
hash := hashOf(fakeWebM())
for _, c := range []struct {
name, body string
want int
code string
}{
{"a QuickTime movie", `{"name":"x.mov","size":10,"type":"video/quicktime","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"},
{"over 50 MiB", `{"name":"x.webm","size":52428801,"type":"video/webm","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"},
{"over 20 MiB as a picture", `{"name":"x.png","size":20971521,"type":"image/png","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"},
} {
rec := postJSON(t, a, deckPath+"/uploads", c.body, cookies)
if rec.Code != c.want || jsonBody(t, rec)["error"] != c.code {
t.Errorf("%s: %d %s, want %d %s", c.name, rec.Code, rec.Body, c.want, c.code)
}
}
// 50 MiB exactly is a clip.
if rec := postJSON(t, a, deckPath+"/uploads", `{"name":"x.mp4","size":52428800,"type":"video/mp4","hash":"`+hash+`"}`, cookies); rec.Code != http.StatusOK {
t.Errorf("a 50 MiB clip: %d %s", rec.Code, rec.Body)
}
// The bytes that arrive are held to the limit too, whatever was said.
signed := jsonBody(t, postJSON(t, a, deckPath+"/uploads", `{"name":"x.webm","size":10,"type":"video/webm","hash":"`+hash+`"}`, cookies))
big := append(fakeWebM(), make([]byte, 50<<20)...)
if put := putBytes(t, a, signed["url"].(string), "video/webm", big, cookies); put.Code != http.StatusRequestEntityTooLarge {
t.Errorf("a PUT of more than 50 MiB: %d, want 413", put.Code)
}
posterKey := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", onePixelPNG)
poster := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, posterKey), cookies))
svgKey := stageUpload(t, a, deckPath, cookies, "p.svg", "image/svg+xml", []byte(``))
svg := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.svg","alt":"","decorative":true}`, svgKey), cookies))
other := createDeck(t, a, cookies, "Another")
otherKey := stageUpload(t, a, other, cookies, "o.png", "image/png", colourPNG(t, color.RGBA{R: 200, A: 255}))
elsewhere := jsonBody(t, postJSON(t, a, other+"/assets", fmt.Sprintf(`{"ref":%q,"name":"o.png","alt":"","decorative":true}`, otherKey), cookies))
register := func(key, fields string) *httptest.ResponseRecorder {
return postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","width":320,"height":180,"alt":""%s}`, key, fields), cookies)
}
// A picture staged as a video is not a video; nor is Matroska that
// is not WebM.
pngAsVideo := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", onePixelPNG)
if rec := register(pngAsVideo, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" {
t.Errorf("a PNG staged as a WebM: %d %s, want 422 not_a_video", rec.Code, rec.Body)
}
mkv := bytes.Replace(fakeWebM(), []byte{0x42, 0x82, 0x84, 'w', 'e', 'b', 'm'}, []byte{0x42, 0x82, 0x84, 'm', 'k', 'v', 'x'}, 1)
mkvKey := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", mkv)
if rec := register(mkvKey, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" {
t.Errorf("a Matroska file: %d %s, want 422 not_a_video", rec.Code, rec.Body)
}
// A video needs a poster: one this deck verified, a PNG or WebP.
key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM())
for name, fields := range map[string]string{
"no poster": ``,
"an empty poster": `,"poster":""`,
"a poster nobody registered": `,"poster":"` + strings.Repeat("ab", 32) + `"`,
"another deck's poster": fmt.Sprintf(`,"poster":%q`, elsewhere["ref"]),
"an SVG poster": fmt.Sprintf(`,"poster":%q`, svg["ref"]),
"a poster with a slash": `,"poster":"a/b"`,
} {
if rec := register(key, fields); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "poster_required" {
t.Errorf("%s: %d %s, want 422 poster_required", name, rec.Code, rec.Body)
}
}
// And with one, the record names it, with its length.
rec := register(key, fmt.Sprintf(`,"poster":%q,"duration":1500`, poster["ref"]))
if rec.Code != http.StatusOK {
t.Fatalf("a clip with its poster: %d %s", rec.Code, rec.Body)
}
out := jsonBody(t, rec)
if out["ref"] != hashOf(fakeWebM()) || out["poster"] != poster["ref"] || out["duration"] != float64(1500) || out["width"] != float64(320) {
t.Errorf("the clip's record is %v", out)
}
// A negative or absurd length is no length.
key = stageUpload(t, a, deckPath, cookies, "y.webm", "video/webm", append(fakeWebM(), 'y'))
if out := jsonBody(t, register(key, fmt.Sprintf(`,"poster":%q,"duration":-4`, poster["ref"]))); out["duration"] != float64(0) {
t.Errorf("a negative length is %v, want 0", out["duration"])
}
}
// TestAClipIsServedInRanges: the video's bytes come back as a picture's
// do, under the deck's capability and its sniffed type, and in ranges,
// so a browser can seek.
func TestAClipIsServedInRanges(t *testing.T) {
a := newAppWithStore(t, dirStore(t))
cookies := signedIn(t, a, allowedAddress)
token := mintAgent(t, a, cookies, "clips")
f := clipDeck(t, a, cookies, token, fakeWebM())
at := "/d/" + f.sqid + "/assets/" + f.video["ref"].(string)
whole := mustGet(t, a, at, http.StatusOK, cookies)
if ct := whole.Header().Get("Content-Type"); ct != "video/webm" {
t.Errorf("Content-Type %q, want video/webm", ct)
}
if ar := whole.Header().Get("Accept-Ranges"); ar != "bytes" {
t.Errorf("Accept-Ranges %q, want bytes", ar)
}
if !bytes.Equal(whole.Body.Bytes(), fakeWebM()) {
t.Errorf("the whole clip is %d bytes, want %d", whole.Body.Len(), len(fakeWebM()))
}
req := httptest.NewRequest(http.MethodGet, at, nil)
req.Header.Set("Range", "bytes=4-9")
for _, c := range cookies {
req.AddCookie(c)
}
part := httptest.NewRecorder()
a.ServeHTTP(part, req)
if part.Code != http.StatusPartialContent || !bytes.Equal(part.Body.Bytes(), fakeWebM()[4:10]) {
t.Errorf("bytes 4-9: %d %x", part.Code, part.Body.Bytes())
}
if cr := part.Header().Get("Content-Range"); cr != fmt.Sprintf("bytes 4-9/%d", len(fakeWebM())) {
t.Errorf("Content-Range %q", cr)
}
// The poster is a picture like any other.
if ct := mustGet(t, a, "/d/"+f.sqid+"/assets/"+f.poster["ref"].(string), http.StatusOK, cookies).Header().Get("Content-Type"); ct != "image/png" {
t.Errorf("the poster's Content-Type is %q", ct)
}
// A share link and a presentation read it under their own capability.
share := "/s/" + mintShareLink(t, a, "/d/"+f.sqid, cookies)
mustGet(t, a, share+"/assets/"+f.video["ref"].(string), http.StatusOK, nil)
session, _ := startPresenting(t, a, "/d/"+f.sqid, cookies)
mustGet(t, a, "/p/"+session+"/assets/"+f.video["ref"].(string), http.StatusOK, nil)
}
// TestAClipsPosterInPicturesAndPDF: wherever no video plays, a clip is
// its poster, described by the clip's text: the scriptless viewer, a
// thumbnail and the PDF. The pages carry the video's address for the
// script that plays it, a clip played on a press marks that press, and
// the presenting windows fetch the video with the talk.
func TestAClipsPosterInPicturesAndPDF(t *testing.T) {
a := newAppWithStore(t, dirStore(t))
cookies := signedIn(t, a, allowedAddress)
token := mintAgent(t, a, cookies, "clips")
f := clipDeck(t, a, cookies, token, fakeWebM())
deckPath := "/d/" + f.sqid
posterAt := func(base string) string { return base + "/assets/" + f.poster["ref"].(string) }
videoAt := func(base string) string { return base + "/assets/" + f.video["ref"].(string) }
for _, vp := range []string{"", "&vp=phone"} {
section := slideSection(t, mustGet(t, a, deckPath+"?slide=1"+vp, http.StatusOK, cookies).Body.String())
for _, want := range []string{
`data-block="clip" data-id="clippress" data-clip="press" data-clip-src="` + videoAt(deckPath) + `"`,
``,
} {
if !strings.Contains(section, want) {
t.Errorf("viewer%s: the slide lacks %s:\n%s", vp, want, section)
}
}
if strings.Contains(section, "