| 1 | package slidestest |
| 2 | |
| 3 | // Clips (scenes and clips spec §2, §4; plan call R3, Review Focus 5): a |
| 4 | // short muted video uploaded to a deck with the picture of its first |
| 5 | // frame as its poster, served in ranges so a browser can seek it, and |
| 6 | // drawn as that poster wherever no video plays: scripts off, a |
| 7 | // thumbnail, the PDF. |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "context" |
| 12 | "encoding/json" |
| 13 | "fmt" |
| 14 | "image" |
| 15 | "image/color" |
| 16 | "image/png" |
| 17 | "io" |
| 18 | "net/http" |
| 19 | "net/http/httptest" |
| 20 | "net/url" |
| 21 | "strings" |
| 22 | "sync" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/rastrillo/rastrillo/blobs" |
| 27 | |
| 28 | "amadan.net/oficina/slides/internal/slides/deck" |
| 29 | "amadan.net/oficina/slides/internal/slides/layout" |
| 30 | ) |
| 31 | |
| 32 | // fakeWebM opens as a WebM does (an EBML header whose DocType is webm), |
| 33 | // so it registers as a clip, and is nothing a browser can play after |
| 34 | // that: Review Focus 5's video that won't play. |
| 35 | func fakeWebM() []byte { |
| 36 | head := []byte{ |
| 37 | 0x1a, 0x45, 0xdf, 0xa3, 0x9f, |
| 38 | 0x42, 0x86, 0x81, 0x01, 0x42, 0xf7, 0x81, 0x01, 0x42, 0xf2, 0x81, 0x04, 0x42, 0xf3, 0x81, 0x08, |
| 39 | 0x42, 0x82, 0x84, 'w', 'e', 'b', 'm', 0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02, |
| 40 | } |
| 41 | return append(head, bytes.Repeat([]byte("not a frame of video "), 64)...) |
| 42 | } |
| 43 | |
| 44 | // colourPNG is a 2 by 2 PNG of one colour: a picture whose bytes are |
| 45 | // not onePixelPNG's. |
| 46 | func colourPNG(t *testing.T, c color.Color) []byte { |
| 47 | t.Helper() |
| 48 | img := image.NewRGBA(image.Rect(0, 0, 2, 2)) |
| 49 | for x := 0; x < 2; x++ { |
| 50 | for y := 0; y < 2; y++ { |
| 51 | img.Set(x, y, c) |
| 52 | } |
| 53 | } |
| 54 | var b bytes.Buffer |
| 55 | if err := png.Encode(&b, img); err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | return b.Bytes() |
| 59 | } |
| 60 | |
| 61 | // clipAlt is the clip's description, which its poster carries. |
| 62 | const clipAlt = "A screen recording" |
| 63 | |
| 64 | // uploadClip runs the editor's clip upload over HTTP: the poster first, |
| 65 | // a decorative picture, then the video naming it. It returns both |
| 66 | // records the server validated. |
| 67 | func uploadClip(t *testing.T, a *testApp, deckPath string, cookies []*http.Cookie, video []byte) (rec, poster map[string]any) { |
| 68 | t.Helper() |
| 69 | posterKey := stageUpload(t, a, deckPath, cookies, "clip.png", "image/png", onePixelPNG) |
| 70 | reg := postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.png","width":1,"height":1,"alt":"","decorative":true}`, posterKey), cookies) |
| 71 | if reg.Code != http.StatusOK { |
| 72 | t.Fatalf("register the poster: %d\n%s", reg.Code, reg.Body) |
| 73 | } |
| 74 | poster = jsonBody(t, reg) |
| 75 | key := stageUpload(t, a, deckPath, cookies, "clip.webm", "video/webm", video) |
| 76 | reg = postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`, |
| 77 | key, clipAlt, poster["ref"]), cookies) |
| 78 | if reg.Code != http.StatusOK { |
| 79 | t.Fatalf("register the clip: %d\n%s", reg.Code, reg.Body) |
| 80 | } |
| 81 | return jsonBody(t, reg), poster |
| 82 | } |
| 83 | |
| 84 | // clipFixture is clipDeck's deck: the clip's two records and its slides. |
| 85 | type clipFixture struct { |
| 86 | sqid string |
| 87 | video, poster map[string]any |
| 88 | } |
| 89 | |
| 90 | // clipDeck is a deck over the API showing video as a clip: |
| 91 | // |
| 92 | // - slide press1: the clip played on a press (box A), and a heading; |
| 93 | // - slide loop2: the clip in a loop; |
| 94 | // - slide once3: the clip played once; |
| 95 | // - slide after4: a heading. |
| 96 | func clipDeck(t *testing.T, a *testApp, cookies []*http.Cookie, token string, video []byte) clipFixture { |
| 97 | t.Helper() |
| 98 | f := clipFixture{sqid: apiDeck(t, a, token, "Clips")} |
| 99 | f.video, f.poster = uploadClip(t, a, "/d/"+f.sqid, cookies, video) |
| 100 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK) |
| 101 | var ops []string |
| 102 | for _, s := range view["slides"].([]any) { |
| 103 | ops = append(ops, `{"op":"remove_slide","id":`+quote(s.(map[string]any)["id"].(string))+`}`) |
| 104 | } |
| 105 | ops = append(ops, |
| 106 | fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.png","width":1,"height":1,"alt":""}`, f.poster["id"], f.poster["ref"]), |
| 107 | fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`, |
| 108 | f.video["id"], f.video["ref"], clipAlt, f.video["poster"])) |
| 109 | clip := func(slide, block, play string) []string { |
| 110 | return []string{ |
| 111 | `{"op":"add_slide","id":"` + slide + `","layout":"canvas"}`, |
| 112 | `{"op":"add_block","slide":"` + slide + `","id":"` + block + `","type":"clip","box":` + boxA + |
| 113 | `,"props":{"asset":` + quote(f.video["id"].(string)) + `,"play":"` + play + `"}}`, |
| 114 | } |
| 115 | } |
| 116 | ops = append(ops, clip("press1", "clippress", "press")...) |
| 117 | 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"}`) |
| 118 | ops = append(ops, clip("loop2", "cliploop", "loop")...) |
| 119 | ops = append(ops, clip("once3", "cliponce", "once")...) |
| 120 | ops = append(ops, `{"op":"add_slide","id":"after4","layout":"flow","template":"title"}`, |
| 121 | `{"op":"add_block","slide":"after4","id":"afterhead","type":"heading","region":"heading","props":{"level":1},"markdown":"After"}`) |
| 122 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+f.sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) |
| 123 | return f |
| 124 | } |
| 125 | |
| 126 | // TestClipUploadsAreRefused: a clip is an MP4 or a WebM of at most |
| 127 | // 50 MiB with a poster this deck already holds, a PNG or WebP. Each |
| 128 | // refusal is a code, and spends nothing: the receipt is still there for |
| 129 | // the registration that gets it right. |
| 130 | func TestClipUploadsAreRefused(t *testing.T) { |
| 131 | a := newAppWithStore(t, dirStore(t)) |
| 132 | cookies := signedIn(t, a, allowedAddress) |
| 133 | deckPath := createDeck(t, a, cookies, "Clips") |
| 134 | hash := hashOf(fakeWebM()) |
| 135 | |
| 136 | for _, c := range []struct { |
| 137 | name, body string |
| 138 | want int |
| 139 | code string |
| 140 | }{ |
| 141 | {"a QuickTime movie", `{"name":"x.mov","size":10,"type":"video/quicktime","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"}, |
| 142 | {"over 50 MiB", `{"name":"x.webm","size":52428801,"type":"video/webm","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"}, |
| 143 | {"over 20 MiB as a picture", `{"name":"x.png","size":20971521,"type":"image/png","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"}, |
| 144 | } { |
| 145 | rec := postJSON(t, a, deckPath+"/uploads", c.body, cookies) |
| 146 | if rec.Code != c.want || jsonBody(t, rec)["error"] != c.code { |
| 147 | t.Errorf("%s: %d %s, want %d %s", c.name, rec.Code, rec.Body, c.want, c.code) |
| 148 | } |
| 149 | } |
| 150 | // 50 MiB exactly is a clip. |
| 151 | if rec := postJSON(t, a, deckPath+"/uploads", `{"name":"x.mp4","size":52428800,"type":"video/mp4","hash":"`+hash+`"}`, cookies); rec.Code != http.StatusOK { |
| 152 | t.Errorf("a 50 MiB clip: %d %s", rec.Code, rec.Body) |
| 153 | } |
| 154 | |
| 155 | // The bytes that arrive are held to the limit too, whatever was said. |
| 156 | signed := jsonBody(t, postJSON(t, a, deckPath+"/uploads", `{"name":"x.webm","size":10,"type":"video/webm","hash":"`+hash+`"}`, cookies)) |
| 157 | big := append(fakeWebM(), make([]byte, 50<<20)...) |
| 158 | if put := putBytes(t, a, signed["url"].(string), "video/webm", big, cookies); put.Code != http.StatusRequestEntityTooLarge { |
| 159 | t.Errorf("a PUT of more than 50 MiB: %d, want 413", put.Code) |
| 160 | } |
| 161 | |
| 162 | posterKey := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", onePixelPNG) |
| 163 | poster := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, posterKey), cookies)) |
| 164 | svgKey := stageUpload(t, a, deckPath, cookies, "p.svg", "image/svg+xml", []byte(`<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>`)) |
| 165 | svg := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.svg","alt":"","decorative":true}`, svgKey), cookies)) |
| 166 | other := createDeck(t, a, cookies, "Another") |
| 167 | otherKey := stageUpload(t, a, other, cookies, "o.png", "image/png", colourPNG(t, color.RGBA{R: 200, A: 255})) |
| 168 | elsewhere := jsonBody(t, postJSON(t, a, other+"/assets", fmt.Sprintf(`{"ref":%q,"name":"o.png","alt":"","decorative":true}`, otherKey), cookies)) |
| 169 | |
| 170 | register := func(key, fields string) *httptest.ResponseRecorder { |
| 171 | return postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","width":320,"height":180,"alt":""%s}`, key, fields), cookies) |
| 172 | } |
| 173 | // A picture staged as a video is not a video; nor is Matroska that |
| 174 | // is not WebM. |
| 175 | pngAsVideo := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", onePixelPNG) |
| 176 | if rec := register(pngAsVideo, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" { |
| 177 | t.Errorf("a PNG staged as a WebM: %d %s, want 422 not_a_video", rec.Code, rec.Body) |
| 178 | } |
| 179 | mkv := bytes.Replace(fakeWebM(), []byte{0x42, 0x82, 0x84, 'w', 'e', 'b', 'm'}, []byte{0x42, 0x82, 0x84, 'm', 'k', 'v', 'x'}, 1) |
| 180 | mkvKey := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", mkv) |
| 181 | if rec := register(mkvKey, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" { |
| 182 | t.Errorf("a Matroska file: %d %s, want 422 not_a_video", rec.Code, rec.Body) |
| 183 | } |
| 184 | // A video needs a poster: one this deck verified, a PNG or WebP. |
| 185 | key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) |
| 186 | for name, fields := range map[string]string{ |
| 187 | "no poster": ``, |
| 188 | "an empty poster": `,"poster":""`, |
| 189 | "a poster nobody registered": `,"poster":"` + strings.Repeat("ab", 32) + `"`, |
| 190 | "another deck's poster": fmt.Sprintf(`,"poster":%q`, elsewhere["ref"]), |
| 191 | "an SVG poster": fmt.Sprintf(`,"poster":%q`, svg["ref"]), |
| 192 | "a poster with a slash": `,"poster":"a/b"`, |
| 193 | } { |
| 194 | if rec := register(key, fields); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "poster_required" { |
| 195 | t.Errorf("%s: %d %s, want 422 poster_required", name, rec.Code, rec.Body) |
| 196 | } |
| 197 | } |
| 198 | // And with one, the record names it, with its length. |
| 199 | rec := register(key, fmt.Sprintf(`,"poster":%q,"duration":1500`, poster["ref"])) |
| 200 | if rec.Code != http.StatusOK { |
| 201 | t.Fatalf("a clip with its poster: %d %s", rec.Code, rec.Body) |
| 202 | } |
| 203 | out := jsonBody(t, rec) |
| 204 | if out["ref"] != hashOf(fakeWebM()) || out["poster"] != poster["ref"] || out["duration"] != float64(1500) || out["width"] != float64(320) { |
| 205 | t.Errorf("the clip's record is %v", out) |
| 206 | } |
| 207 | // A negative or absurd length is no length. |
| 208 | key = stageUpload(t, a, deckPath, cookies, "y.webm", "video/webm", append(fakeWebM(), 'y')) |
| 209 | if out := jsonBody(t, register(key, fmt.Sprintf(`,"poster":%q,"duration":-4`, poster["ref"]))); out["duration"] != float64(0) { |
| 210 | t.Errorf("a negative length is %v, want 0", out["duration"]) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | // TestAClipIsServedInRanges: the video's bytes come back as a picture's |
| 215 | // do, under the deck's capability and its sniffed type, and in ranges, |
| 216 | // so a browser can seek. |
| 217 | func TestAClipIsServedInRanges(t *testing.T) { |
| 218 | a := newAppWithStore(t, dirStore(t)) |
| 219 | cookies := signedIn(t, a, allowedAddress) |
| 220 | token := mintAgent(t, a, cookies, "clips") |
| 221 | f := clipDeck(t, a, cookies, token, fakeWebM()) |
| 222 | at := "/d/" + f.sqid + "/assets/" + f.video["ref"].(string) |
| 223 | |
| 224 | whole := mustGet(t, a, at, http.StatusOK, cookies) |
| 225 | if ct := whole.Header().Get("Content-Type"); ct != "video/webm" { |
| 226 | t.Errorf("Content-Type %q, want video/webm", ct) |
| 227 | } |
| 228 | if ar := whole.Header().Get("Accept-Ranges"); ar != "bytes" { |
| 229 | t.Errorf("Accept-Ranges %q, want bytes", ar) |
| 230 | } |
| 231 | if !bytes.Equal(whole.Body.Bytes(), fakeWebM()) { |
| 232 | t.Errorf("the whole clip is %d bytes, want %d", whole.Body.Len(), len(fakeWebM())) |
| 233 | } |
| 234 | req := httptest.NewRequest(http.MethodGet, at, nil) |
| 235 | req.Header.Set("Range", "bytes=4-9") |
| 236 | for _, c := range cookies { |
| 237 | req.AddCookie(c) |
| 238 | } |
| 239 | part := httptest.NewRecorder() |
| 240 | a.ServeHTTP(part, req) |
| 241 | if part.Code != http.StatusPartialContent || !bytes.Equal(part.Body.Bytes(), fakeWebM()[4:10]) { |
| 242 | t.Errorf("bytes 4-9: %d %x", part.Code, part.Body.Bytes()) |
| 243 | } |
| 244 | if cr := part.Header().Get("Content-Range"); cr != fmt.Sprintf("bytes 4-9/%d", len(fakeWebM())) { |
| 245 | t.Errorf("Content-Range %q", cr) |
| 246 | } |
| 247 | // The poster is a picture like any other. |
| 248 | if ct := mustGet(t, a, "/d/"+f.sqid+"/assets/"+f.poster["ref"].(string), http.StatusOK, cookies).Header().Get("Content-Type"); ct != "image/png" { |
| 249 | t.Errorf("the poster's Content-Type is %q", ct) |
| 250 | } |
| 251 | // A share link and a presentation read it under their own capability. |
| 252 | share := "/s/" + mintShareLink(t, a, "/d/"+f.sqid, cookies) |
| 253 | mustGet(t, a, share+"/assets/"+f.video["ref"].(string), http.StatusOK, nil) |
| 254 | session, _ := startPresenting(t, a, "/d/"+f.sqid, cookies) |
| 255 | mustGet(t, a, "/p/"+session+"/assets/"+f.video["ref"].(string), http.StatusOK, nil) |
| 256 | } |
| 257 | |
| 258 | // TestAClipsPosterInPicturesAndPDF: wherever no video plays, a clip is |
| 259 | // its poster, described by the clip's text: the scriptless viewer, a |
| 260 | // thumbnail and the PDF. The pages carry the video's address for the |
| 261 | // script that plays it, a clip played on a press marks that press, and |
| 262 | // the presenting windows fetch the video with the talk. |
| 263 | func TestAClipsPosterInPicturesAndPDF(t *testing.T) { |
| 264 | a := newAppWithStore(t, dirStore(t)) |
| 265 | cookies := signedIn(t, a, allowedAddress) |
| 266 | token := mintAgent(t, a, cookies, "clips") |
| 267 | f := clipDeck(t, a, cookies, token, fakeWebM()) |
| 268 | deckPath := "/d/" + f.sqid |
| 269 | posterAt := func(base string) string { return base + "/assets/" + f.poster["ref"].(string) } |
| 270 | videoAt := func(base string) string { return base + "/assets/" + f.video["ref"].(string) } |
| 271 | |
| 272 | for _, vp := range []string{"", "&vp=phone"} { |
| 273 | section := slideSection(t, mustGet(t, a, deckPath+"?slide=1"+vp, http.StatusOK, cookies).Body.String()) |
| 274 | for _, want := range []string{ |
| 275 | `data-block="clip" data-id="clippress" data-clip="press" data-clip-src="` + videoAt(deckPath) + `"`, |
| 276 | `<img src="` + posterAt(deckPath) + `" alt="` + clipAlt + `" width="320" height="180">`, |
| 277 | } { |
| 278 | if !strings.Contains(section, want) { |
| 279 | t.Errorf("viewer%s: the slide lacks %s:\n%s", vp, want, section) |
| 280 | } |
| 281 | } |
| 282 | if strings.Contains(section, "<video") { |
| 283 | t.Errorf("viewer%s: the server drew a video; with scripts off it is the poster:\n%s", vp, section) |
| 284 | } |
| 285 | } |
| 286 | loop := slideSection(t, mustGet(t, a, deckPath+"?slide=2", http.StatusOK, cookies).Body.String()) |
| 287 | if !strings.Contains(loop, `data-clip="loop"`) { |
| 288 | t.Errorf("the looping clip is drawn as:\n%s", loop) |
| 289 | } |
| 290 | |
| 291 | // A thumbnail and the PDF are the poster. |
| 292 | thumb := mustGet(t, a, deckPath+"/slides/press1.svg", http.StatusOK, cookies).Body.String() |
| 293 | if !strings.Contains(thumb, "<image") || !strings.Contains(thumb, "data:image/png;base64,") { |
| 294 | t.Errorf("the thumbnail draws no poster:\n%s", thumb) |
| 295 | } |
| 296 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK) |
| 297 | raw, _ := json.Marshal(view) |
| 298 | var d deck.Deck |
| 299 | if err := json.Unmarshal(raw, &d); err != nil { |
| 300 | t.Fatal(err) |
| 301 | } |
| 302 | if got := d.Assets[f.video["id"].(string)]; got.Poster != f.poster["ref"] || got.Duration != 1500 { |
| 303 | t.Errorf("the deck's clip asset is %+v", got) |
| 304 | } |
| 305 | p, _, err := layout.Layout(&d, 0) |
| 306 | if err != nil { |
| 307 | t.Fatal(err) |
| 308 | } |
| 309 | var pictured []string |
| 310 | for _, op := range p.Ops { |
| 311 | if im, ok := op.(layout.Image); ok { |
| 312 | pictured = append(pictured, im.Asset+":"+im.Alt) |
| 313 | } |
| 314 | } |
| 315 | if strings.Join(pictured, "|") != f.poster["id"].(string)+":"+clipAlt { |
| 316 | t.Errorf("the PDF's press1 pictures %v, want the poster alone", pictured) |
| 317 | } |
| 318 | |
| 319 | // The presenting windows: the poster among a slide's pictures, the |
| 320 | // video among its clips, the press marked on a mark of its own so |
| 321 | // the poster is there from the slide's arrival. |
| 322 | session, remote := startPresenting(t, a, deckPath, cookies) |
| 323 | talk := mustGet(t, a, "/p/"+session+"/talk?t="+url.QueryEscape(remote), http.StatusOK, nil).Body.Bytes() |
| 324 | var payload struct { |
| 325 | Slides []struct { |
| 326 | ID string `json:"id"` |
| 327 | Presses int `json:"presses"` |
| 328 | HTML string `json:"html"` |
| 329 | Assets []string `json:"assets"` |
| 330 | Clips []string `json:"clips"` |
| 331 | } `json:"slides"` |
| 332 | } |
| 333 | if err := json.Unmarshal(talk, &payload); err != nil { |
| 334 | t.Fatal(err) |
| 335 | } |
| 336 | if len(payload.Slides) != 4 { |
| 337 | t.Fatalf("the talk has %d slides", len(payload.Slides)) |
| 338 | } |
| 339 | first := payload.Slides[0] |
| 340 | if first.Presses != 1 || strings.Join(first.Assets, " ") != posterAt("/p/"+session) || strings.Join(first.Clips, " ") != videoAt("/p/"+session) { |
| 341 | t.Errorf("the talk's press1 is %d presses, pictures %v, clips %v", first.Presses, first.Assets, first.Clips) |
| 342 | } |
| 343 | if !strings.Contains(first.HTML, `<span data-clip-press data-press="1" data-waiting></span>`) { |
| 344 | t.Errorf("the press is not marked:\n%s", first.HTML) |
| 345 | } |
| 346 | if strings.Contains(first.HTML, `data-id="clippress" data-clip="press" data-clip-src="`+videoAt("/p/"+session)+`" data-press`) { |
| 347 | t.Errorf("the clip itself waits for its press:\n%s", first.HTML) |
| 348 | } |
| 349 | if payload.Slides[1].Presses != 0 || payload.Slides[3].Clips != nil { |
| 350 | t.Errorf("the loop takes %d presses; a slide with no clip fetches %v", payload.Slides[1].Presses, payload.Slides[3].Clips) |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | // TestAStagedClipComesBackToWhoStagedIt: the editor draws a clip's |
| 355 | // poster from its bytes as this app serves them back while staged (the |
| 356 | // page's policy loads no blob: media). A staged picture does not come |
| 357 | // back, nor a clip once it is registered, nor an address nobody staged. |
| 358 | func TestAStagedClipComesBackToWhoStagedIt(t *testing.T) { |
| 359 | a := newAppWithStore(t, dirStore(t)) |
| 360 | cookies := signedIn(t, a, allowedAddress) |
| 361 | deckPath := createDeck(t, a, cookies, "Staged") |
| 362 | key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) |
| 363 | back := mustGet(t, a, deckPath+"/uploads/"+key, http.StatusOK, cookies) |
| 364 | if back.Header().Get("Content-Type") != "video/webm" || back.Header().Get("Cache-Control") != "no-store" || !bytes.Equal(back.Body.Bytes(), fakeWebM()) { |
| 365 | t.Errorf("the staged clip comes back as %v, %d bytes", back.Header(), back.Body.Len()) |
| 366 | } |
| 367 | // Signed out, it is the sign-in door. |
| 368 | mustGet(t, a, deckPath+"/uploads/"+key, http.StatusSeeOther, nil) |
| 369 | picture := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", onePixelPNG) |
| 370 | mustGet(t, a, deckPath+"/uploads/"+picture, http.StatusNotFound, cookies) |
| 371 | mustGet(t, a, deckPath+"/uploads/"+strings.Repeat("cd", 32), http.StatusNotFound, cookies) |
| 372 | other := createDeck(t, a, cookies, "Other") |
| 373 | mustGet(t, a, other+"/uploads/"+key, http.StatusNotFound, cookies) |
| 374 | |
| 375 | poster := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, picture), cookies)) |
| 376 | if rec := postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","poster":%q}`, key, poster["ref"]), cookies); rec.Code != http.StatusOK { |
| 377 | t.Fatalf("register: %d %s", rec.Code, rec.Body) |
| 378 | } |
| 379 | mustGet(t, a, deckPath+"/uploads/"+key, http.StatusNotFound, cookies) |
| 380 | } |
| 381 | |
| 382 | // unseekableStore is a store whose reader cannot seek, as the platform's |
| 383 | // bucket behind ThroughApp and a sealed store are, counting each read of |
| 384 | // one ref and the bytes it gave. |
| 385 | type unseekableStore struct { |
| 386 | blobs.Store |
| 387 | mu sync.Mutex |
| 388 | watch string |
| 389 | gets int |
| 390 | bytes int64 |
| 391 | // slow holds each read of the watched ref this long, so requests |
| 392 | // that arrive together overlap. |
| 393 | slow time.Duration |
| 394 | } |
| 395 | |
| 396 | func (s *unseekableStore) Get(ctx context.Context, hash string) (io.ReadCloser, error) { |
| 397 | s.mu.Lock() |
| 398 | slow := s.slow |
| 399 | if hash != s.watch { |
| 400 | slow = 0 |
| 401 | } |
| 402 | s.mu.Unlock() |
| 403 | time.Sleep(slow) |
| 404 | rc, err := s.Store.Get(ctx, hash) |
| 405 | if err != nil { |
| 406 | return nil, err |
| 407 | } |
| 408 | defer rc.Close() |
| 409 | raw, err := io.ReadAll(rc) |
| 410 | if err != nil { |
| 411 | return nil, err |
| 412 | } |
| 413 | s.mu.Lock() |
| 414 | defer s.mu.Unlock() |
| 415 | if hash == s.watch { |
| 416 | s.gets++ |
| 417 | s.bytes += int64(len(raw)) |
| 418 | } |
| 419 | return io.NopCloser(bytes.NewReader(raw)), nil |
| 420 | } |
| 421 | |
| 422 | func (s *unseekableStore) counts() (int, int64) { |
| 423 | s.mu.Lock() |
| 424 | defer s.mu.Unlock() |
| 425 | return s.gets, s.bytes |
| 426 | } |
| 427 | |
| 428 | // TestAClipFromAStoreThatCannotSeekIsReadOnce: a store that cannot |
| 429 | // start part way is read once per clip, into a cache on disk, and every |
| 430 | // range after that comes from the cache, reading the store no more. |
| 431 | func TestAClipFromAStoreThatCannotSeekIsReadOnce(t *testing.T) { |
| 432 | store := &unseekableStore{Store: dirStore(t)} |
| 433 | a := newAppWithStore(t, store) |
| 434 | cookies := signedIn(t, a, allowedAddress) |
| 435 | token := mintAgent(t, a, cookies, "clips") |
| 436 | video := append(fakeWebM(), bytes.Repeat([]byte{7}, 64<<10)...) |
| 437 | f := clipDeck(t, a, cookies, token, video) |
| 438 | ref := f.video["ref"].(string) |
| 439 | store.mu.Lock() |
| 440 | store.watch = ref |
| 441 | store.mu.Unlock() |
| 442 | at := "/d/" + f.sqid + "/assets/" + ref |
| 443 | ranged := func(spec string, from, to int) { |
| 444 | t.Helper() |
| 445 | req := httptest.NewRequest(http.MethodGet, at, nil) |
| 446 | req.Header.Set("Range", spec) |
| 447 | for _, c := range cookies { |
| 448 | req.AddCookie(c) |
| 449 | } |
| 450 | rec := httptest.NewRecorder() |
| 451 | a.ServeHTTP(rec, req) |
| 452 | if rec.Code != http.StatusPartialContent || !bytes.Equal(rec.Body.Bytes(), video[from:to+1]) { |
| 453 | t.Fatalf("%s: %d, %d bytes", spec, rec.Code, rec.Body.Len()) |
| 454 | } |
| 455 | } |
| 456 | ranged("bytes=10-20", 10, 20) |
| 457 | if gets, n := store.counts(); gets != 1 || n != int64(len(video)) { |
| 458 | t.Errorf("the first range read the store %d times, %d bytes; want once, %d", gets, n, len(video)) |
| 459 | } |
| 460 | ranged("bytes=30000-40000", 30000, 40000) |
| 461 | ranged(fmt.Sprintf("bytes=%d-", len(video)-5), len(video)-5, len(video)-1) |
| 462 | if gets, _ := store.counts(); gets != 1 { |
| 463 | t.Errorf("later ranges read the store again: %d reads", gets) |
| 464 | } |
| 465 | whole := mustGet(t, a, at, http.StatusOK, cookies) |
| 466 | if !bytes.Equal(whole.Body.Bytes(), video) || whole.Header().Get("Content-Type") != "video/webm" { |
| 467 | t.Errorf("the whole clip from the cache is %d bytes, %s", whole.Body.Len(), whole.Header().Get("Content-Type")) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | // TestAClipsPosterIsAtMost4MiB: a poster is a still, held to a still's |
| 472 | // 4 MiB at registration, exactly 4 MiB taken. |
| 473 | func TestAClipsPosterIsAtMost4MiB(t *testing.T) { |
| 474 | a := newAppWithStore(t, dirStore(t)) |
| 475 | cookies := signedIn(t, a, allowedAddress) |
| 476 | deckPath := createDeck(t, a, cookies, "Posters") |
| 477 | poster := func(size int) string { |
| 478 | body := append(append([]byte{}, onePixelPNG...), make([]byte, size-len(onePixelPNG))...) |
| 479 | key := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", body) |
| 480 | return jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, key), cookies))["ref"].(string) |
| 481 | } |
| 482 | big, fits := poster(4<<20+1), poster(4<<20) |
| 483 | key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) |
| 484 | register := func(p string) *httptest.ResponseRecorder { |
| 485 | return postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","poster":%q}`, key, p), cookies) |
| 486 | } |
| 487 | if rec := register(big); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "poster_too_large" || jsonBody(t, rec)["message"] == "" { |
| 488 | t.Errorf("a poster of 4 MiB and a byte: %d %s, want 422 poster_too_large", rec.Code, rec.Body) |
| 489 | } |
| 490 | if rec := register(fits); rec.Code != http.StatusOK { |
| 491 | t.Errorf("a poster of 4 MiB: %d %s", rec.Code, rec.Body) |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | // TestAClipsDescriptionIsItsPosters: the description written on a clip |
| 496 | // block is its poster's text in HTML and in the PDF, as an image's is; |
| 497 | // decorative is empty; with neither, the video's own. |
| 498 | func TestAClipsDescriptionIsItsPosters(t *testing.T) { |
| 499 | a := newAppWithStore(t, dirStore(t)) |
| 500 | cookies := signedIn(t, a, allowedAddress) |
| 501 | token := mintAgent(t, a, cookies, "clips") |
| 502 | f := clipDeck(t, a, cookies, token, fakeWebM()) |
| 503 | apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+f.sqid+"/ops", token, |
| 504 | `{"ops":[{"op":"set_block","slide":"press1","id":"clippress","props":{"alt":"Paul opens a deck"}},`+ |
| 505 | `{"op":"set_block","slide":"loop2","id":"cliploop","props":{"decorative":true}}]}`, http.StatusOK) |
| 506 | for slide, want := range map[int]string{1: "Paul opens a deck", 2: "", 3: clipAlt} { |
| 507 | section := slideSection(t, mustGet(t, a, fmt.Sprintf("/d/%s?slide=%d", f.sqid, slide), http.StatusOK, cookies).Body.String()) |
| 508 | if !strings.Contains(section, `alt="`+want+`"`) { |
| 509 | t.Errorf("slide %d's poster is not described %q:\n%s", slide, want, section) |
| 510 | } |
| 511 | } |
| 512 | view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK) |
| 513 | raw, _ := json.Marshal(view) |
| 514 | var d deck.Deck |
| 515 | if err := json.Unmarshal(raw, &d); err != nil { |
| 516 | t.Fatal(err) |
| 517 | } |
| 518 | for i, want := range []string{"Paul opens a deck", "", clipAlt} { |
| 519 | p, _, err := layout.Layout(&d, i) |
| 520 | if err != nil { |
| 521 | t.Fatal(err) |
| 522 | } |
| 523 | for _, op := range p.Ops { |
| 524 | if im, ok := op.(layout.Image); ok && im.Alt != want { |
| 525 | t.Errorf("the PDF's slide %d describes its poster %q, want %q", i+1, im.Alt, want) |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | // rangeOf asks target for one range and checks it is want[from:to+1]. |
| 532 | func rangeOf(t *testing.T, a *testApp, cookies []*http.Cookie, target string, want []byte, from, to int) error { |
| 533 | req := httptest.NewRequest(http.MethodGet, target, nil) |
| 534 | req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", from, to)) |
| 535 | for _, c := range cookies { |
| 536 | req.AddCookie(c) |
| 537 | } |
| 538 | rec := httptest.NewRecorder() |
| 539 | a.ServeHTTP(rec, req) |
| 540 | if rec.Code != http.StatusPartialContent || !bytes.Equal(rec.Body.Bytes(), want[from:to+1]) { |
| 541 | return fmt.Errorf("bytes %d-%d: %d, %d bytes", from, to, rec.Code, rec.Body.Len()) |
| 542 | } |
| 543 | return nil |
| 544 | } |
| 545 | |
| 546 | // TestAStagedClipFromAStoreThatCannotSeekIsReadOnce: the editor reads a |
| 547 | // staged clip back in ranges to draw its poster; on a store that cannot |
| 548 | // seek the first fills the cache and the next reads the store no more, |
| 549 | // both answered. |
| 550 | func TestAStagedClipFromAStoreThatCannotSeekIsReadOnce(t *testing.T) { |
| 551 | store := &unseekableStore{Store: dirStore(t)} |
| 552 | a := newAppWithStore(t, store) |
| 553 | cookies := signedIn(t, a, allowedAddress) |
| 554 | deckPath := createDeck(t, a, cookies, "Staged") |
| 555 | video := append(fakeWebM(), bytes.Repeat([]byte{9}, 32<<10)...) |
| 556 | key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", video) |
| 557 | store.mu.Lock() |
| 558 | store.watch = hashOf(video) // where blobs.Dir put the staged bytes |
| 559 | store.mu.Unlock() |
| 560 | for _, r := range [][2]int{{0, 99}, {20000, 30000}, {len(video) - 10, len(video) - 1}} { |
| 561 | if err := rangeOf(t, a, cookies, deckPath+"/uploads/"+key, video, r[0], r[1]); err != nil { |
| 562 | t.Error(err) |
| 563 | } |
| 564 | } |
| 565 | if gets, n := store.counts(); gets != 1 || n != int64(len(video)) { |
| 566 | t.Errorf("three staged ranges read the store %d times, %d bytes; want once, %d", gets, n, len(video)) |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | // TestConcurrentRangesOfAClipReadTheStoreOnce: ranges of one clip that |
| 571 | // arrive together, before any is cached, wait on one fill. |
| 572 | func TestConcurrentRangesOfAClipReadTheStoreOnce(t *testing.T) { |
| 573 | store := &unseekableStore{Store: dirStore(t)} |
| 574 | a := newAppWithStore(t, store) |
| 575 | cookies := signedIn(t, a, allowedAddress) |
| 576 | token := mintAgent(t, a, cookies, "clips") |
| 577 | video := append(fakeWebM(), bytes.Repeat([]byte{5}, 48<<10)...) |
| 578 | f := clipDeck(t, a, cookies, token, video) |
| 579 | ref := f.video["ref"].(string) |
| 580 | store.mu.Lock() |
| 581 | store.watch, store.slow = ref, 150*time.Millisecond |
| 582 | store.mu.Unlock() |
| 583 | const n = 8 |
| 584 | errs := make(chan error, n) |
| 585 | var wg sync.WaitGroup |
| 586 | for i := 0; i < n; i++ { |
| 587 | wg.Add(1) |
| 588 | go func(i int) { |
| 589 | defer wg.Done() |
| 590 | from := i * 4000 |
| 591 | errs <- rangeOf(t, a, cookies, "/d/"+f.sqid+"/assets/"+ref, video, from, from+999) |
| 592 | }(i) |
| 593 | } |
| 594 | wg.Wait() |
| 595 | close(errs) |
| 596 | for err := range errs { |
| 597 | if err != nil { |
| 598 | t.Error(err) |
| 599 | } |
| 600 | } |
| 601 | if gets, _ := store.counts(); gets != 1 { |
| 602 | t.Errorf("%d ranges at once read the store %d times, want once", n, gets) |
| 603 | } |
| 604 | } |
| 605 | |