Zoo

staging

← back to the zoo

13. Apps can save files for you

An app can save a file into your storage, under its own folder, without ever holding storage's keys.

rc.app_headers("storage", true) proves to storage which app calls and for whom; storage saves only under Apps / <app>. One file: POST /app/save answers {saved: {id, ...}, path}. Many: app/begin gives presigned PUTs (200 a call), the bytes go straight to B2, app/commit checks them all at once, app/urls hands out downloads.

This is the code serving the zoo right now: the bytes this very program was built from (each file is embedded when the zoo is compiled), at commit 55c71513c5 (staging). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.

e13_postcards.odin sha256 5560e8d98e02 · raw

1package main
2
3// Exhibit 13. The zoo holds no storage keys. It saves files into a person's storage by showing
4// storage an assertion from account that says "zoo, for this person" (rc.app_headers("storage",
5// true)). Storage decides the folder (Apps / Zoo); the app cannot choose another.
6//
7// One file: postcard() below is the whole path, the one to copy into an app. Many files (an importer,
8// a photo library): storage's bulk calls app/begin, app/commit, app/urls and app/list (bulk.odin;
9// storage's README, "In bulk"), which the self-check uses for 50 postcards at once.
10
11import "core:encoding/json"
12import "core:fmt"
13import "core:strings"
14import "core:time"
15import "ratcloud:rc"
16
17// A postcard, 1 bit per pixel: the background is the person's own colour, the words white.
18postcard_png :: proc(uid: i64, line := "") -> []u8 {
19	id := int(uid)
20	im := image_new(160, 104, {{u8(40 + (id * 37) % 120), u8(90 + (id * 61) % 100), u8(120 + (id * 17) % 100)}, {255, 255, 250}})
21	frame_rect(&im, 5, 5, 154, 98, 1)
22	text(&im, 14, 16, "Greetings from", 1)
23	text(&im, 14, 38, "the zoo", 1, 2)
24	text(&im, 14, 74, line if line != "" else cat(ymd_hm(now()), " UTC"), 1)
25	return png_encode(&im)
26}
27
28Card :: struct {
29	file:    struct {
30		id:   i64 `json:"id"`,
31		path: string `json:"path"`,
32	} `json:"file"`,
33	bytes:   int `json:"bytes"`,
34	matched: bool `json:"matched"`,
35	image:   string `json:"image,omitempty"`,
36}
37
38// One file: storage's /app/save, then /app/fetch by the id it answered. The save answers JSON:
39//
40//     {"saved": {"id": 42, "name": "postcard.png", "kind": "file", "size": 812, "type": "image/png",
41//                "updated": 1760000000, "app": "zoo", ...},
42//      "path": "Apps/Zoo/postcards/postcard.png"}
43//
44// so the new file's id is answer.saved.id (keep it to fetch or trash the file later). The fetch
45// answers the file's bytes themselves, not JSON. Saving at a path already taken replaces it.
46postcard :: proc(me: ^rc.User) -> (Card, string) {
47	png := postcard_png(me.id)
48	a := call_app("storage", "/app/save?path=postcards%2Fpostcard.png", true, "POST", string(png), "image/png", 30_000)
49	ans := parse(a.body)
50	id, has := jint(ans, "saved", "id")
51	if a.status != 200 || !has do return {}, fmt.tprintf("storage would not save it (%d): %s%s", a.status, jstr(ans, "error"), a.err)
52	back := call_app("storage", fmt.tprintf("/app/fetch?id=%d", id), true, timeout_ms = 30_000)
53	if back.status != 200 do return {}, fmt.tprintf("saved as file %d, but fetching it back answered %d", id, back.status)
54	c := Card{bytes = len(png), matched = back.body == string(png), image = cat("data:image/png;base64,", b64(transmute([]u8)back.body))}
55	c.file.id, c.file.path = id, jstr(ans, "path")
56	return c, ""
57}
58
59Cards :: struct {
60	count:    int `json:"count"`,
61	matched:  int `json:"matched"`,
62	listed:   int `json:"listed"`,
63	path:     string `json:"path"`,
64	ids:      [2]i64 `json:"ids"`,
65	ms:       i64 `json:"ms"`,
66	steps_ms: map[string]i64 `json:"steps_ms"`,
67	one:      ^Card `json:"one,omitempty"`,
68}
69
70// The check's batch: 50 postcards in one begin, one commit and one urls call, then listed.
71postcards_50 :: proc(me: ^rc.User) -> (Cards, string) {
72	t0 := time.tick_now()
73	lap := time.tick_now()
74	steps := make(map[string]i64)
75	mark :: proc(steps: ^map[string]i64, k: string, lap: ^time.Tick) {
76		steps[k] = i64(time.duration_milliseconds(time.tick_since(lap^)))
77		lap^ = time.tick_now()
78	}
79	paths := make([]string, 50)
80	cards := make([][]u8, 50)
81	for i in 0 ..< 50 {
82		paths[i] = fmt.tprintf("postcards/check/%02d.png", i + 1)
83		cards[i] = postcard_png(me.id, fmt.tprintf("no. %02d of 50", i + 1))
84	}
85	mark(&steps, "draw", &lap)
86	fb := strings.builder_make()
87	for p, i in paths do fmt.sbprintf(&fb, `%s{{"path":%s,"size":%d,"type":"image/png"}}`, "," if i > 0 else "", jq(p), len(cards[i]))
88	s, r := storage_call("begin", fmt.tprintf(`{{"files":[%s]}}`, strings.to_string(fb)))
89	beg := jarr(r, "files")
90	urls := 0
91	for f in beg do if jstr(f, "url") != "" do urls += 1
92	if s != 200 || urls != 50 do return {}, fmt.tprintf("storage would not begin them (%d): %s", s, to_json(jget(r, "error")) if jhas(r, "error") else to_json(beg[0] if len(beg) > 0 else r))
93	mark(&steps, "begin", &lap)
94	puts := make([]Put, 50)
95	for f, i in beg do puts[i] = {jstr(f, "url"), jstr(f, "type"), cards[i]}
96	codes := put_many(puts)
97	mark(&steps, "put", &lap)
98	for c in codes do if c != 200 do return {}, fmt.tprintf("B2 refused some PUTs: %v", codes)
99	ib := strings.builder_make()
100	for f, i in beg do fmt.sbprintf(&ib, "%s%d", "," if i > 0 else "", jint(f, "id"))
101	s, r = storage_call("commit", fmt.tprintf(`{{"ids":[%s]}}`, strings.to_string(ib)))
102	files := make([dynamic]json.Value)
103	for f in jarr(r, "files") do if jhas(f, "file") do append(&files, jget(f, "file"))
104	if s != 200 || len(files) != 50 do return {}, fmt.tprintf("storage would not commit them all (%d): %s", s, to_json(r))
105	mark(&steps, "commit", &lap)
106	fids := strings.builder_make()
107	lo, hi: i64 = max(i64), 0
108	for f, i in files {
109		id := jint(f, "id")
110		lo, hi = min(lo, id), max(hi, id)
111		fmt.sbprintf(&fids, "%s%d", "," if i > 0 else "", id)
112	}
113	s, r = storage_call("urls", fmt.tprintf(`{{"ids":[%s]}}`, strings.to_string(fids)))
114	mark(&steps, "urls", &lap)
115	got := make([dynamic]string)
116	for f in jarr(r, "files") do if jstr(f, "url") != "" do append(&got, jstr(f, "url"))
117	if s != 200 || len(got) != 50 do return {}, fmt.tprintf("storage would not hand out their URLs (%d)", s)
118	back := get_many(got[:])
119	mark(&steps, "get", &lap)
120	matched := 0
121	for g, i in back do if g.status == 200 && eq_bytes(g.body, cards[i]) do matched += 1
122	listed := make(map[string]bool)
123	after: json.Value = json.Integer(0)
124	for page := 0; page < 20; page += 1 {
125		_, l := storage_call("list", fmt.tprintf(`{{"after":%s,"limit":1000}}`, to_json(after)))
126		for f in jarr(l, "files") do listed[jstr(f, "path")] = true
127		after = jget(l, "next")
128		if !jhas(l, "next") do break
129	}
130	mark(&steps, "list", &lap)
131	n := 0
132	for p in paths do if listed[cat("Apps/Zoo/", p)] || listed[p] do n += 1
133	return {count = 50, matched = matched, listed = n, path = "Apps/Zoo/postcards/check/", ids = {lo, hi}, ms = i64(time.duration_milliseconds(time.tick_since(t0))), steps_ms = steps}, ""
134}
135
136e13 :: proc() -> Exhibit {
137	return {
138		n = 13, try_ = "save a postcard", wing = "Storage",
139		title = "Apps can save files for you",
140		promise = "An app can save a file into your storage, under its own folder, without ever holding storage's keys.",
141		block = `rc.app_headers("storage", true) proves to storage which app calls and for whom; storage saves only under Apps / <app>. One file: POST /app/save answers {saved: {id, ...}, path}. Many: app/begin gives presigned PUTs (200 a call), the bytes go straight to B2, app/commit checks them all at once, app/urls hands out downloads.`,
142		src = {"e13_postcards.odin", #load("e13_postcards.odin", string)},
143		files = srcs({"bulk.odin", #load("bulk.odin", string)}, {"png.odin", #load("png.odin", string)}),
144		script = {"web/e13.js", #load("web/e13.js", string)},
145		show = proc(me: ^rc.User) -> string {
146			d, s, found := stored_data(13, Cards)
147			last := ""
148			if found && s.ok do last = fmt.tprintf(`<p class="muted small">The self-check saves 50 postcards for the robot each time: one begin, 50 PUTs straight to B2, one commit, one call for their 50 URLs, %d ms in all, %s.</p>`, d.ms, ago(s.at))
149			if me == nil do return cat(signin_line("to have the zoo save a postcard for you."), last)
150			return cat(`<p><button id="postcard" class="primary">Save a postcard</button> <span class="out" id="postcard-out"></span></p><p id="postcard-img"></p><p class="muted">It appears in <a href="`, h(rc.app_url("storage")), `/" target="_blank" rel="noopener">your storage, under Apps / Zoo</a>.</p>`, last)
151		},
152		api = proc(a: ^Api) -> bool {
153			if (a.do_ != "postcard" && a.do_ != "postcards") || !a.post do return false
154			if a.me == nil {reply_err(a, 401, "sign in first"); return true}
155			if a.do_ == "postcard" {
156				c, err := postcard(a.me)
157				if err != "" {reply_err(a, 502, err); return true}
158				reply(a, c)
159			} else {
160				c, err := postcards_50(a.me)
161				if err != "" {reply_err(a, 502, err); return true}
162				reply(a, c)
163			}
164			return true
165		},
166		// The robot has the zoo save one postcard the simple way (the button's path), then 50 in one
167		// batch, read them all back and find them in the listing.
168		check = proc() -> Check {
169			b, err := robot_at()
170			if err != "" do return fail(err)
171			r := post(b, self_url("/api/13/postcard"))
172			one: Card
173			if r.status != 200 || !json_into(r.body, &one) do return fail(fmt.tprintf("saving one postcard failed (%d): %s", r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120)))
174			if !strings.has_prefix(one.file.path, "Apps/Zoo/") do return fail(cat("one postcard was saved at ", one.file.path, ", not under Apps/Zoo"), one)
175			one.image = ""
176			if !one.matched do return fail(fmt.tprintf("one postcard, saved as file %d, came back different", one.file.id), one)
177			b.timeout_ms = 40_000 // 50 PUTs, 50 GETs and four storage calls behind one request
178			r = post(b, self_url("/api/13/postcards"))
179			b.timeout_ms = 15_000
180			j: Cards
181			if r.status != 200 || !json_into(r.body, &j) do return fail(fmt.tprintf("saving 50 postcards failed (%d): %s", r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120)))
182			j.one = &one
183			if j.matched != 50 do return fail(fmt.tprintf("only %d of 50 postcards came back unchanged", j.matched), j)
184			if j.listed != 50 do return fail(fmt.tprintf("only %d of 50 postcards are in the zoo's listing", j.listed), j)
185			return pass(fmt.tprintf("saved one postcard at %s (file %d) and fetched it back by its id unchanged; then 50 under %s (one begin, PUTs straight to B2, one commit, one call for 50 URLs), all 50 back unchanged and listed, in %d ms", one.file.path, one.file.id, j.path, j.ms), j)
186		},
187	}
188}

bulk.odin sha256 ffb0f70ced2f · raw

1package main
2
3// Storage in bulk, the way any app calls it (storage's README, "For an app: in bulk"): a JSON call to
4// storage with rc.app_headers("storage", true), and the bytes straight to B2 and back on the
5// presigned URLs it hands out. No storage key, and no byte passes through storage's own code.
6//
7//     storage_call("begin", `{"files":[{"path":"postcards/a.png","size":812,"type":"image/png"}]}`)
8//     // files[0]: {id, url, type, size, expires}; PUT the bytes to url with that Content-Type
9//     storage_call("commit", `{"ids":[...]}`)       // one B2 listing for the whole begin
10//     storage_call("urls", `{"ids":[...]}`)         // presigned GETs, five minutes each
11//     storage_call("list", `{"after":0,"limit":1000}`)   // what the zoo saved for this person
12
13import "core:encoding/json"
14import "core:fmt"
15import "ratcloud:rc"
16
17storage_call :: proc(op: string, in_json: string) -> (int, json.Value) {
18	a := call_app("storage", cat("/app/", op), true, "POST", in_json, "application/json")
19	if v := parse(a.body); v != nil do return a.status, v
20	return a.status, parse(fmt.tprintf(`{{"error":%s}}`, jq(fmt.tprintf("storage answered %d: %s %s", a.status, clip(a.body, 160), a.err))))
21}
22
23Put :: struct {
24	url, type: string,
25	body:      []u8,
26}
27
28// At most this many calls at once: the host lets one request hold 16 open calls.
29MANY :: 15
30
31// PUT many bodies to their presigned URLs, MANY at a time: their statuses, in order. B2 answers a
32// PUT now and then with 500 or 503 and asks clients to send it again (as storage does with its own
33// B2 calls); a dropped connection (0) is sent again too. Twice more at most: the URL is the same, so
34// a PUT that did arrive is simply replaced by the same bytes.
35put_many :: proc(jobs: []Put) -> []int {
36	out := make([]int, len(jobs))
37	todo := make([dynamic]int)
38	for i in 0 ..< len(jobs) do append(&todo, i)
39	for try in 0 ..< 3 {
40		if try > 0 do rc.sleep(500)
41		for start := 0; start < len(todo); start += MANY {
42			chunk := todo[start:min(start + MANY, len(todo))]
43			calls := make([]rc.Fetch_Call, len(chunk))
44			for i, k in chunk {
45				hs := make(map[string]string)
46				hs["Content-Type"] = jobs[i].type
47				calls[k] = rc.fetch_start({method = "PUT", url = jobs[i].url, headers = hs, body = jobs[i].body, timeout_ms = 30_000})
48			}
49			buf: [4096]u8
50			for &c, k in calls {
51				out[chunk[k]] = rc.fetch_status(&c)
52				for rc.fetch_read(&c, buf[:]) > 0 {}
53				rc.fetch_close(&c)
54			}
55		}
56		again := make([dynamic]int)
57		for i in todo do if out[i] == 0 || out[i] == 500 || out[i] == 503 do append(&again, i)
58		if len(again) == 0 do break
59		todo = again
60	}
61	return out
62}
63
64Got :: struct {
65	status: int,
66	body:   []u8,
67}
68
69// GET many presigned URLs, MANY at a time: status and body, in order.
70get_many :: proc(urls: []string) -> []Got {
71	out := make([]Got, len(urls))
72	for start := 0; start < len(urls); start += MANY {
73		end := min(start + MANY, len(urls))
74		calls := make([]rc.Fetch_Call, end - start)
75		for k in 0 ..< len(calls) do calls[k] = rc.fetch_start({url = urls[start + k], timeout_ms = 30_000})
76		buf := make([]u8, 16 * 1024)
77		for &c, k in calls {
78			st := rc.fetch_status(&c)
79			body := make([dynamic]u8)
80			for {
81				n := rc.fetch_read(&c, buf)
82				if n <= 0 do break
83				append(&body, ..buf[:n])
84			}
85			rc.fetch_close(&c)
86			out[start + k] = {st, body[:]}
87		}
88	}
89	return out
90}

png.odin sha256 891fadba12b9 · raw

1package main
2
3// Pictures for the zoo (the robot's face, exhibit 13's postcards): a palette image, a few shapes, a
4// 5x7 font for capitals and digits, and a PNG writer. No compression (zlib's stored blocks): a
5// postcard is 1 bit per pixel, about 2 KB, so there is nothing to gain from a deflate here.
6
7import "core:hash"
8
9Rgb :: [3]u8
10
11Image :: struct {
12	w, h:    int,
13	palette: []Rgb,
14	px:      []u8, // palette indices, row by row
15}
16
17image_new :: proc(w, h: int, palette: []Rgb) -> Image {
18	p := make([]Rgb, len(palette))
19	copy(p, palette)
20	return {w, h, p, make([]u8, w * h)}
21}
22
23set_px :: proc(im: ^Image, x, y: int, c: u8) {
24	if x >= 0 && y >= 0 && x < im.w && y < im.h do im.px[y * im.w + x] = c
25}
26
27// Filled, corners included (GD's imagefilledrectangle).
28fill_rect :: proc(im: ^Image, x0, y0, x1, y1: int, c: u8) {
29	for y in y0 ..= y1 do for x in x0 ..= x1 do set_px(im, x, y, c)
30}
31
32// A one-pixel frame.
33frame_rect :: proc(im: ^Image, x0, y0, x1, y1: int, c: u8) {
34	for x in x0 ..= x1 {set_px(im, x, y0, c); set_px(im, x, y1, c)}
35	for y in y0 ..= y1 {set_px(im, x0, y, c); set_px(im, x1, y, c)}
36}
37
38fill_ellipse :: proc(im: ^Image, cx, cy, r: int, c: u8) {
39	for y in -r ..= r do for x in -r ..= r do if x * x + y * y <= r * r do set_px(im, cx + x, cy + y, c)
40}
41
42// Capitals, digits and ". : -", 5 wide and 7 high, one byte per row (bit 4 is the left column).
43// Lower case is drawn as upper case.
44FONT_CHARS :: " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:-"
45FONT := [?][7]u8 {
46	{0, 0, 0, 0, 0, 0, 0}, // space
47	{0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11}, // A
48	{0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e}, // B
49	{0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e}, // C
50	{0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e}, // D
51	{0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f}, // E
52	{0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10}, // F
53	{0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0f}, // G
54	{0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11}, // H
55	{0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e}, // I
56	{0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c}, // J
57	{0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11}, // K
58	{0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f}, // L
59	{0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11}, // M
60	{0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11}, // N
61	{0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e}, // O
62	{0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10}, // P
63	{0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d}, // Q
64	{0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11}, // R
65	{0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e}, // S
66	{0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04}, // T
67	{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e}, // U
68	{0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04}, // V
69	{0x11, 0x11, 0x11, 0x15, 0x15, 0x15, 0x0a}, // W
70	{0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11}, // X
71	{0x11, 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04}, // Y
72	{0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f}, // Z
73	{0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e}, // 0
74	{0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e}, // 1
75	{0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f}, // 2
76	{0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e}, // 3
77	{0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02}, // 4
78	{0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e}, // 5
79	{0x06, 0x08, 0x10, 0x1e, 0x11, 0x11, 0x0e}, // 6
80	{0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08}, // 7
81	{0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e}, // 8
82	{0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c}, // 9
83	{0, 0, 0, 0, 0, 0x0c, 0x0c}, // .
84	{0, 0x0c, 0x0c, 0, 0x0c, 0x0c, 0}, // :
85	{0, 0, 0, 0x1f, 0, 0, 0}, // -
86}
87
88// Text at (x, y), each font pixel `scale` pixels square, 6 * scale per character.
89text :: proc(im: ^Image, x, y: int, s: string, c: u8, scale := 1) {
90	cx := x
91	for ch in transmute([]u8)s {
92		up := ch - 32 if ch >= 'a' && ch <= 'z' else ch
93		gi := 0
94		for f, i in transmute([]u8)string(FONT_CHARS) do if f == up do gi = i
95		for row in 0 ..< 7 {
96			bits := FONT[gi][row]
97			for col in 0 ..< 5 do if bits & (0x10 >> u8(col)) != 0 do fill_rect(im, cx + col * scale, y + row * scale, cx + col * scale + scale - 1, y + row * scale + scale - 1, c)
98		}
99		cx += 6 * scale
100	}
101}
102
103// ---- PNG ----
104
105@(private = "file")
106chunk :: proc(out: ^[dynamic]u8, kind: string, data: []u8) {
107	append(out, ..be32(u32(len(data))))
108	start := len(out)
109	append(out, ..transmute([]u8)kind)
110	append(out, ..data)
111	append(out, ..be32(hash.crc32(out[start:])))
112}
113
114png_encode :: proc(im: ^Image) -> []u8 {
115	depth := 1 if len(im.palette) <= 2 else 2 if len(im.palette) <= 4 else 4 if len(im.palette) <= 16 else 8
116	per := 8 / depth
117	row := (im.w + per - 1) / per
118	raw := make([dynamic]u8, 0, (row + 1) * im.h)
119	for y in 0 ..< im.h {
120		append(&raw, 0) // filter: none
121		line := make([]u8, row)
122		for x in 0 ..< im.w {
123			v := im.px[y * im.w + x]
124			line[x / per] |= v << u8(8 - depth * (x % per + 1))
125		}
126		append(&raw, ..line)
127	}
128	// zlib: stored blocks of at most 65535 bytes, then adler32
129	z := make([dynamic]u8)
130	append(&z, 0x78, 0x01)
131	for off := 0; true; /**/ {
132		n := min(65535, len(raw) - off)
133		last := off + n == len(raw)
134		append(&z, 1 if last else 0, u8(n), u8(n >> 8), u8(~u16(n)), u8(~u16(n) >> 8))
135		append(&z, ..raw[off:off + n])
136		off += n
137		if last do break
138	}
139	append(&z, ..be32(hash.adler32(raw[:])))
140	out := make([dynamic]u8)
141	append(&out, 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n')
142	ihdr := join(be32(u32(im.w)), be32(u32(im.h)), {u8(depth), 3, 0, 0, 0})
143	chunk(&out, "IHDR", ihdr)
144	pl := make([]u8, 3 * len(im.palette))
145	for c, i in im.palette {pl[3 * i] = c[0]; pl[3 * i + 1] = c[1]; pl[3 * i + 2] = c[2]}
146	chunk(&out, "PLTE", pl)
147	chunk(&out, "IDAT", z[:])
148	chunk(&out, "IEND", nil)
149	return out[:]
150}

web/e13.js sha256 4a953deb0dad · raw

1document.getElementById("postcard")?.addEventListener("click", async (ev) => {
2  const out = document.getElementById("postcard-out");
3  ev.target.disabled = true; out.textContent = "saving…";
4  const j = await zoo.call("/api/13/postcard", {});
5  ev.target.disabled = false;
6  if (j.error) { out.textContent = j.error; return; }
7  out.textContent = "saved to " + j.file.path + " (file " + j.file.id + ", " + j.bytes + " bytes)" + (j.matched ? ", fetched back unchanged" : ", but the copy differs");
8  document.getElementById("postcard-img").innerHTML = '<img alt="your postcard" width="160" height="104" src="' + zoo.esc(j.image) + '">';
9});