16. Ping me
An app can send a notification to your phone or browser.
The push app keeps each person's devices (Web Push); an app asks it to notify someone with rc.app_headers("push", true).
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 (live). The zoo's own self-check fetches this page and compares it byte for byte with the file it runs.
e16_ping_me.odin sha256 e19c82c33ee7 · raw
1package main 2 3// Exhibit 16. Two halves, both push's: 4// 1. Allowing: the card sends the person to push's own page (`/?enable=1&back=…`), which knows the 5// zoo from the Referer. Only push can subscribe a browser, so no app can plant an endpoint for 6// anyone; and no push code runs on the zoo's origin. 7// 2. Sending: the zoo asks push to notify the person, with an assertion that names the zoo: 8// POST rc.app_url("push") + "/?api=send" {user, title, body, url} rc.app_headers("push", true) 9// push delivers only to browsers where that person allowed the zoo (`sent: 0` otherwise). 10// "In ten seconds": the zoo takes the assertion now (it lives two minutes), answers at once 11// (rc.done), and goes on: waits ten seconds, then sends. 12// Human-only: a notification arriving on a phone cannot be seen by the zoo. The check proves the send 13// path (the robot has no browser, so `sent` may be 0); a person presses "this worked for me". 14 15import "core:encoding/json" 16import "core:fmt" 17import "ratcloud:rc" 18 19ping_send :: proc(uid: i64, headers: map[string]string) -> (json.Value, string) { 20 hs := make(map[string]string) 21 for k, v in headers do hs[k] = v 22 hs["Content-Type"] = "application/json" 23 body := fmt.tprintf(`{{"user":%d,"title":"The zoo says hello","body":"Exhibit 16 worked. Tap to go back to the zoo.","url":%s}}`, uid, jq(cat(rc.app_url("zoo"), "/#e16"))) 24 res := rc.fetch({method = "POST", url = cat(rc.app_url("push"), "/?api=send"), headers = hs, body = transmute([]u8)body, timeout_ms = 20_000}) 25 r := parse(string(res.body)) 26 if res.status != 200 || !jhas(r, "sent") do return nil, fmt.tprintf("push answered %d: %s%s", res.status, clip(string(res.body), 160), res.err) 27 return r, "" 28} 29 30ping_state :: proc(uid: i64) -> json.Value { 31 v, _ := meta(fmt.tprintf("ping16.%d", uid)) 32 return parse(v) 33} 34ping_set :: proc(uid: i64, state_json: string) { 35 meta_set(fmt.tprintf("ping16.%d", uid), state_json) 36} 37 38e16 :: proc() -> Exhibit { 39 return { 40 n = 16, try_ = "get a notification", wing = "Notifications", kind = "human", 41 title = "Ping me", 42 promise = "An app can send a notification to your phone or browser.", 43 block = `The push app keeps each person's devices (Web Push); an app asks it to notify someone with rc.app_headers("push", true).`, 44 src = {"e16_ping_me.odin", #load("e16_ping_me.odin", string)}, 45 script = {"web/e16.js", #load("web/e16.js", string)}, 46 show = proc(me: ^rc.User) -> string { 47 if me == nil do return signin_line("to be notified.") 48 return cat(`<p><button id="ping16" class="primary" data-push="`, h(rc.app_url("push")), `">Notify me in ten seconds</button> <span class="out" id="ping16-out"></span></p><p class="muted">The first time, push asks you to allow the zoo on this browser. <button class="link" id="ping16-manage">Your browsers</button></p>`, 49 seen_button(16, me, "The notification arrived and opened the zoo: this worked for me")) 50 }, 51 api = proc(a: ^Api) -> bool { 52 if a.me == nil {reply_err(a, 401, "sign in first"); return true} 53 uid := a.me.id 54 switch a.do_ { 55 case "status": 56 reply_raw(a, fmt.tprintf(`{{"state":%s}}`, to_json(ping_state(uid)))) 57 return true 58 case "send": 59 if !a.post do return false 60 hs, err := rc.app_headers("push", true) 61 if err != "" {reply_err(a, 502, err); return true} 62 r, serr := ping_send(uid, hs) 63 if serr != "" {reply_err(a, 502, serr); return true} 64 reply(a, r) 65 return true 66 case "notify": 67 if !a.post do return false 68 hs, err := rc.app_headers("push", true) // taken now: it names this person and lives two minutes 69 if err != "" {reply_err(a, 502, err); return true} 70 ping_set(uid, fmt.tprintf(`{{"state":"waiting","at":%d}}`, now())) 71 reply_raw(a, `{"scheduled":true,"in":10}`) 72 rc.done(a.w) // the browser has its answer; the rest runs inside this request's own time 73 rc.sleep(10_000) 74 r, serr := ping_send(uid, hs) 75 if serr != "" { 76 ping_set(uid, fmt.tprintf(`{{"state":"error","error":%s,"at":%d}}`, jq(serr), now())) 77 } else { 78 ping_set(uid, fmt.tprintf(`{{"state":%s,"sent":%d,"signed_out":%d,"at":%d}}`, `"sent"` if jint(r, "sent") > 0 else `"nobody"`, jint(r, "sent"), jint(r, "signed_out"), now())) 79 } 80 return true 81 } 82 return false 83 }, 84 // The send path, as the robot: push must accept the assertion and answer with its counts. It 85 // has no browser, so sent is expected to be 0. 86 check = proc() -> Check { 87 b, err := robot_at() 88 if err != "" do return fail(err) 89 r := post(b, self_url("/api/16/send")) 90 if r.status != 200 || r.j == nil do return fail(fmt.tprintf("push's send failed (%d): %s", r.status, jstr(r.j, "error") if r.j != nil else clip(r.body, 120))) 91 return pass(fmt.tprintf("push accepted the zoo's send for the robot: sent %d, gone %d, signed out %d, failed %d", jint(r.j, "sent"), jint(r.j, "gone"), jint(r.j, "signed_out"), jint(r.j, "failed")), r.j) 92 }, 93 } 94}
web/e16.js sha256 bea06304856d · raw
1(() => { 2 const btn = document.getElementById("ping16"); 3 if (!btn) return; 4 const out = document.getElementById("ping16-out"); 5 const KEY = "zoo-push-allowed"; 6 const get = () => { try { return localStorage.getItem(KEY); } catch (e) { return null; } }; 7 const put = (v) => { try { v ? localStorage.setItem(KEY, "1") : localStorage.removeItem(KEY); } catch (e) {} }; 8 if (/[?&]pushed=1/.test(location.search)) { put(true); history.replaceState(null, "", "/#e16"); out.textContent = "allowed: press the button again"; } 9 const push = btn.dataset.push; 10 document.getElementById("ping16-manage").addEventListener("click", () => { location.href = push + "/"; }); 11 const go = () => { location.href = push + "/?enable=1&back=" + encodeURIComponent(location.origin + "/?pushed=1#e16"); }; 12 btn.addEventListener("click", async () => { 13 if (!get()) { out.textContent = "taking you to push to allow the zoo…"; go(); return; } 14 btn.disabled = true; out.textContent = "scheduled: ten seconds"; 15 const j = await zoo.call("/api/16/notify", {}); 16 if (j.error) { out.textContent = j.error; btn.disabled = false; return; } 17 for (let i = 0; i < 20; i++) { 18 await new Promise(r => setTimeout(r, 1500)); 19 const s = (await zoo.call("/api/16/status")).state; 20 if (!s || s.state === "waiting") continue; 21 btn.disabled = false; 22 if (s.state === "sent") out.textContent = "sent to " + s.sent + " browser(s): look for it"; 23 else if (s.state === "nobody") { put(false); out.innerHTML = 'Nothing was sent: the zoo is not allowed on any of your browsers yet. <button class="link" id="ping16-allow">Allow it</button>'; document.getElementById("ping16-allow").onclick = go; } 24 else out.textContent = s.error || "failed"; 25 return; 26 } 27 btn.disabled = false; out.textContent = "no answer yet"; 28 }); 29})();