forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

media.rs777 lines, 29.3 KiBHistoryRawDownload
1//! Media in the note: attached files, pasted and dropped files, and microphone recordings.
2//! A file is POSTed raw to `/media?name=` and comes back as `/media/<hash>.<ext>`. That URL
3//! becomes an image inline; its extension picks img, audio or video when it is rendered.
4//! A recording is a take on the server, streamed over a socket part by part. Its URL
5//! (`/media/rec/<id>`) is placed at the cursor of the press once the first chunk is stored. A
6//! continuation adds a part to a take and places nothing.
7
8use std::cell::{Cell, RefCell};
9use std::collections::VecDeque;
10use std::rc::{Rc, Weak};
11
12use loro::cursor::Cursor;
13use wasm_bindgen::closure::Closure;
14use wasm_bindgen::{JsCast, JsValue};
15use wasm_bindgen_futures::{JsFuture, spawn_local};
16use web_sys::{
17 BeforeUnloadEvent, BinaryType, Blob, BlobEvent, BlobPropertyBag, Element, Event, EventTarget, File, FileList, HtmlButtonElement, HtmlElement,
18 HtmlInputElement, MediaRecorder, MediaRecorderOptions, MediaStream, MediaStreamConstraints, MediaStreamTrack, MessageEvent, MouseEvent,
19 RequestInit, Response, WebSocket,
20};
21
22use super::{Ctx, Ed, h};
23use crate::core::commands;
24use crate::core::pos::{self, Pos, Selection};
25use crate::editor::Editor;
26use crate::strings::Strings;
27use note_model::marks::Marks;
28use note_model::render::embed_of;
29use note_model::write::Inline;
30
31/// The toolbar's status line, where a failed upload says so.
32pub const STATUS_ID: &str = "editor-media-status";
33
34/// How long a notice stays in the status line (ms).
35const NOTICE_MS: i32 = 4000;
36
37/// The recorder's format. The server joins only WebM with Opus.
38const MIME: &str = "audio/webm;codecs=opus";
39
40/// A socket that goes this long without an answer, while a chunk waits for its ack or before
41/// it is ready, is dead (ms).
42const STALL_MS: f64 = 5000.0;
43
44/// The wait before a lost socket is reconnected (ms).
45const RETRY_MS: i32 = 1000;
46
47/// The microphone recording in progress, and everything wired to it. Dropped in a later task
48/// after the stop, with every handler cleared first.
49struct Recording {
50 recorder: MediaRecorder,
51 stream: MediaStream,
52 take: Rc<Take>,
53 tick: Option<i32>,
54 _on_data: Closure<dyn FnMut(BlobEvent)>,
55 _on_stop: Closure<dyn FnMut()>,
56 _ticker: Closure<dyn FnMut()>,
57}
58
59/// One part of a take on its way to the server: the chunks the server does not have yet, and
60/// every chunk for the local fallback. Shared by the recording and its socket task, so it
61/// outlives the recording itself.
62struct Take {
63 /// The take's id: asked for by the first connection of a new take, then known for good.
64 session: RefCell<Option<String>>,
65 /// The part this take's socket is attached to, from the server's `ready`.
66 part: Cell<Option<u32>>,
67 /// A new take: its URL is placed in the note once its first chunk is stored.
68 fresh: bool,
69 /// Set once the URL is placed.
70 placed: Cell<bool>,
71 /// Where the URL goes: the cursor as it was when the button was pressed.
72 at: Option<Cursor>,
73 /// The alt text of the embed.
74 name: String,
75 mime: String,
76 chunks: js_sys::Array,
77 /// Chunks the server does not have yet, the first one at byte `sent`.
78 queue: RefCell<VecDeque<Blob>>,
79 /// Bytes of this part the server has stored: the offset of the first queued chunk.
80 sent: Cell<u64>,
81 /// Set on stop: no more chunks come.
82 ended: Cell<bool>,
83 /// Set when the server rejected the take: nothing more is sent.
84 failed: Cell<bool>,
85 /// The beforeunload guard, kept until the take is concluded.
86 unload: Closure<dyn FnMut(Event)>,
87}
88
89/// What a recording starts: a new take placed at a cursor, or a new part of an earlier take.
90enum Start {
91 New(Option<Cursor>),
92 Continue(String),
93}
94
95struct Inner {
96 /// Weak, so a closed editor is not kept alive by an upload or a recording.
97 ed: Weak<RefCell<Editor>>,
98 note_id: String,
99 rec: Rc<RefCell<Option<Recording>>>,
100 /// Set while the microphone is being opened, so a second click does not start another.
101 starting: Cell<bool>,
102 /// Set on `note:detach`: the editor is leaving, so a finished recording is kept for later.
103 detached: Cell<bool>,
104 /// The record button and its m:ss readout, bound by the toolbar.
105 ui: RefCell<Option<(HtmlButtonElement, HtmlElement)>>,
106 input: HtmlInputElement,
107}
108
109/// Handle to the media buttons' behaviour. Clones share the same state.
110#[derive(Clone)]
111pub struct Media(Rc<Inner>);
112
113impl Media {
114 /// Opens the file picker; the picked files are uploaded and inserted.
115 pub fn attach(&self) {
116 self.0.input.click();
117 }
118
119 /// Starts a recording, or stops the one running.
120 pub fn toggle_record(&self) {
121 let inner = self.0.clone();
122 let recording = inner.rec.borrow().is_some();
123 if recording {
124 stop_current(&inner);
125 } else if !inner.starting.replace(true) {
126 let at = press_cursor(&inner);
127 spawn_local(start(inner, Start::New(at)));
128 }
129 }
130
131 pub fn recording(&self) -> bool {
132 self.0.rec.borrow().is_some()
133 }
134
135 /// Gives the toolbar's record button and its readout to the recording.
136 pub fn bind_record(&self, btn: HtmlButtonElement, time: HtmlElement) {
137 *self.0.ui.borrow_mut() = Some((btn, time));
138 }
139}
140
141/// Adds the file input and the detach and continue handlers. Call before the toolbar,
142/// which binds the record button to the returned handle.
143pub fn install(ed: &Ed, cx: &Ctx) -> Media {
144 let document = &cx.document;
145 let input: HtmlInputElement = h(document, "input", &[("type", "file"), ("multiple", ""), ("hidden", "")], None).unchecked_into();
146 let _ = cx.mount.append_child(&input);
147 let inner = Rc::new(Inner {
148 ed: Rc::downgrade(ed),
149 note_id: cx.note_id.clone(),
150 rec: Rc::default(),
151 starting: Cell::new(false),
152 detached: Cell::new(false),
153 ui: RefCell::new(None),
154 input: input.clone(),
155 });
156
157 // Picked files are uploaded; the input is reset so the same file can be picked again.
158 {
159 let (host, picker) = (Rc::downgrade(ed), input.clone());
160 let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
161 let files = files_of(picker.files());
162 picker.set_value("");
163 if let Some(host) = host.upgrade()
164 && !files.is_empty()
165 {
166 insert_files(&host, files);
167 }
168 });
169 let _ = input.add_event_listener_with_callback_and_add_event_listener_options("change", cb.as_ref().unchecked_ref(), &cx.opts);
170 cb.forget();
171 }
172
173 // Leaving the note: a recording in progress is stopped, and its take is finished by the socket task.
174 {
175 let weak = Rc::downgrade(&inner);
176 let cb = Closure::<dyn FnMut(Event)>::new(move |_: Event| {
177 let Some(inner) = weak.upgrade() else { return };
178 inner.detached.set(true);
179 stop_current(&inner);
180 });
181 if let Some(win) = web_sys::window() {
182 let _ = win.add_event_listener_with_callback_and_add_event_listener_options("note:detach", cb.as_ref().unchecked_ref(), &cx.opts);
183 }
184 cb.forget();
185 }
186
187 // The continue button of a take: a press keeps the caret where it is, and a click continues the take.
188 {
189 let root = ed.borrow().view.root.clone();
190 let target: &EventTarget = root.as_ref();
191 let press = Closure::<dyn FnMut(MouseEvent)>::new(|ev: MouseEvent| {
192 if continue_target(&ev).is_some() {
193 ev.prevent_default();
194 }
195 });
196 let _ = target.add_event_listener_with_callback_and_add_event_listener_options("mousedown", press.as_ref().unchecked_ref(), &cx.opts);
197 press.forget();
198 let weak = Rc::downgrade(&inner);
199 let click = Closure::<dyn FnMut(MouseEvent)>::new(move |ev: MouseEvent| {
200 if let (Some(session), Some(inner)) = (continue_target(&ev), weak.upgrade()) {
201 continue_take(inner, session);
202 }
203 });
204 let _ = target.add_event_listener_with_callback_and_add_event_listener_options("click", click.as_ref().unchecked_ref(), &cx.opts);
205 click.forget();
206 }
207
208 Media(inner)
209}
210
211/// The files of a file list (picker or clipboard), in order.
212pub fn files_of(list: Option<FileList>) -> Vec<File> {
213 let Some(list) = list else { return Vec::new() };
214 (0..list.length()).filter_map(|i| list.item(i)).collect()
215}
216
217/// Uploads each file in turn and inserts it at the selection once it is stored. A failed
218/// upload shows a notice and the rest still go on.
219pub fn insert_files(ed: &Ed, files: Vec<File>) {
220 let weak = Rc::downgrade(ed);
221 spawn_local(async move {
222 for file in files {
223 let name = file.name();
224 let blob: &Blob = file.as_ref();
225 match upload(blob, &name).await {
226 Ok(url) => {
227 if let Some(ed) = weak.upgrade() {
228 insert(&ed, embed(&url, &name));
229 }
230 }
231 Err(_) => notice("mediaFailed"),
232 }
233 }
234 });
235}
236
237/// POSTs one file as its raw bytes. The answer is the URL of the stored copy.
238async fn upload(blob: &Blob, name: &str) -> Result<String, JsValue> {
239 let win = web_sys::window().ok_or("no window")?;
240 let url = format!("/media?name={}", String::from(js_sys::encode_uri_component(name)));
241 let body: &JsValue = blob.as_ref();
242 let init = RequestInit::new();
243 init.set_method("POST");
244 init.set_body(body);
245 let resp: Response = JsFuture::from(win.fetch_with_str_and_init(&url, &init)).await?.dyn_into()?;
246 if !resp.ok() {
247 return Err(format!("upload {}", resp.status()).into());
248 }
249 let text = JsFuture::from(resp.text()?).await?.as_string().unwrap_or_default();
250 Ok(text.trim().to_owned())
251}
252
253/// The inline for a stored file: an embed when its extension can show, else a link to it.
254fn embed(url: &str, name: &str) -> Inline {
255 if embed_of(url).is_some() {
256 Inline::Image { src: url.to_owned(), alt: name.to_owned(), title: None }
257 } else {
258 let mut marks = Marks::default();
259 marks.link = Some((url.to_owned(), None));
260 Inline::Text(name.to_owned(), marks)
261 }
262}
263
264/// Puts an inline at the selection, the way typing does. False when the editor is busy.
265fn insert(ed: &Ed, inl: Inline) -> bool {
266 let Ok(mut e) = ed.try_borrow_mut() else { return false };
267 e.run(|cx| commands::insert_inline(cx, &[inl]))
268}
269
270/// Puts an inline at the cursor `at`, or at the end of the doc when it no longer resolves, and
271/// leaves the selection where it was (moved past the inline when it was after it). False when
272/// the editor is busy.
273fn insert_at(ed: &Ed, at: Option<&Cursor>, inl: Inline) -> bool {
274 let Ok(mut e) = ed.try_borrow_mut() else { return false };
275 e.run(|cx| {
276 let m = cx.m;
277 let p = at.and_then(|c| m.cursor_pos(c)).unwrap_or_else(|| m.total());
278 let p = pos::snap(m, p);
279 let saved = std::mem::replace(&mut cx.sel, Selection::caret(p));
280 let ok = commands::insert_inline(cx, &[inl]);
281 let shift = |q: Pos| if q >= p { q + 1 } else { q };
282 cx.sel = match saved {
283 Selection::Text { anchor, head } => Selection::Text { anchor: shift(anchor), head: shift(head) },
284 Selection::Node(q) => Selection::Node(shift(q)),
285 Selection::Gap(q) => Selection::Gap(shift(q)),
286 Selection::All => Selection::All,
287 };
288 ok
289 })
290}
291
292/// Shows a message in the status line, then clears it when it is still the one shown.
293fn notice(key: &str) {
294 let Some(win) = web_sys::window() else { return };
295 let Some(doc) = win.document() else { return };
296 let Some(el) = doc.get_element_by_id(STATUS_ID) else { return };
297 let text = Strings::load(&doc).get(key);
298 el.set_text_content(Some(&text));
299 let shown = text;
300 let clear = Closure::once_into_js(move || {
301 if el.text_content().is_some_and(|t| t == shown) {
302 el.set_text_content(None);
303 }
304 });
305 let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(clear.unchecked_ref(), NOTICE_MS);
306}
307
308// ---------------------------------------------------------------------------
309// Recording
310// ---------------------------------------------------------------------------
311
312/// The cursor at the selection's head, as a Loro cursor so the embed lands there even when the
313/// text before it changes while the take runs.
314fn press_cursor(inner: &Inner) -> Option<Cursor> {
315 let ed = inner.ed.upgrade()?;
316 let e = ed.try_borrow().ok()?;
317 let pos = e.sel.head()?;
318 e.m.cursor(pos)
319}
320
321/// Continues the take `session` with a new part, from its continue button. Refused while a
322/// recording runs.
323fn continue_take(inner: Rc<Inner>, session: String) {
324 if inner.rec.borrow().is_none() && !inner.starting.replace(true) {
325 spawn_local(start(inner, Start::Continue(session)));
326 }
327}
328
329/// The take of the continue button under a mouse event, if the event is on one.
330fn continue_target(ev: &MouseEvent) -> Option<String> {
331 let el: Element = ev.target()?.dyn_into().ok()?;
332 let button = el.closest(".note-take-continue").ok()??;
333 let span = button.closest("[data-take]").ok()??;
334 span.get_attribute("data-take")
335}
336
337/// Opens the microphone and the recorder, then starts the socket task that sends the take.
338/// A failure shows a notice and leaves nothing running.
339async fn start(inner: Rc<Inner>, how: Start) {
340 let rec = open_take(&inner, how).await;
341 inner.starting.set(false);
342 match rec {
343 Ok(rec) => {
344 let take = rec.take.clone();
345 *inner.rec.borrow_mut() = Some(rec);
346 set_ui(&inner, true);
347 spawn_local(link(inner.clone(), take));
348 // The page may have started leaving while the microphone was being opened.
349 if inner.detached.get() {
350 stop_current(&inner);
351 }
352 }
353 Err(key) => notice(key),
354 }
355}
356
357/// Opens the microphone and the recorder for `how`. A failure stops the microphone.
358async fn open_take(inner: &Rc<Inner>, how: Start) -> Result<Recording, &'static str> {
359 let stream = request_mic().await.map_err(|_| "micDenied")?;
360 if !MediaRecorder::is_type_supported(MIME) {
361 stop_tracks(&stream);
362 return Err("mediaFailed");
363 }
364 let name = format!("recording-{}.weba", stamp());
365 begin(inner, stream.clone(), how, name).map_err(|_| {
366 stop_tracks(&stream);
367 "mediaFailed"
368 })
369}
370
371async fn request_mic() -> Result<MediaStream, JsValue> {
372 let devices = web_sys::window().ok_or("no window")?.navigator().media_devices()?;
373 let constraints = MediaStreamConstraints::new();
374 constraints.set_audio(&JsValue::TRUE);
375 let promise = devices.get_user_media_with_constraints(&constraints)?;
376 JsFuture::from(promise).await?.dyn_into()
377}
378
379/// Builds the recorder with its handlers and starts it with one chunk a second. Each chunk is
380/// kept in the take and queued for the socket task.
381fn begin(inner: &Rc<Inner>, stream: MediaStream, how: Start, name: String) -> Result<Recording, JsValue> {
382 let opts = MediaRecorderOptions::new();
383 opts.set_mime_type(MIME);
384 let recorder = MediaRecorder::new_with_media_stream_and_media_recorder_options(&stream, &opts)?;
385
386 let (session, at, fresh) = match how {
387 Start::New(at) => (None, at, true),
388 Start::Continue(session) => (Some(session), None, false),
389 };
390 // A tab close while the take is open asks first; the guard goes when the take is concluded.
391 let unload = Closure::<dyn FnMut(Event)>::new(|ev: Event| {
392 ev.prevent_default();
393 if let Some(e) = ev.dyn_ref::<BeforeUnloadEvent>() {
394 e.set_return_value("");
395 }
396 });
397 let take = Rc::new(Take {
398 session: RefCell::new(session),
399 part: Cell::new(None),
400 fresh,
401 placed: Cell::new(false),
402 at,
403 name,
404 mime: recorder.mime_type(),
405 chunks: js_sys::Array::new(),
406 queue: RefCell::default(),
407 sent: Cell::new(0),
408 ended: Cell::new(false),
409 failed: Cell::new(false),
410 unload,
411 });
412 let sink = take.clone();
413 let on_data = Closure::<dyn FnMut(BlobEvent)>::new(move |ev: BlobEvent| {
414 if let Some(blob) = ev.data().filter(|b| b.size() > 0.0) {
415 let raw: &JsValue = blob.as_ref();
416 sink.chunks.push(raw);
417 sink.queue.borrow_mut().push_back(blob);
418 }
419 });
420 recorder.set_ondataavailable(Some(on_data.as_ref().unchecked_ref()));
421
422 // Strong, so the take is still finished when the page leaves. `on_stopped` moves the
423 // recording, and this closure with it, out of `inner`, which breaks the cycle.
424 let held = inner.clone();
425 let on_stop = Closure::<dyn FnMut()>::new(move || on_stopped(&held));
426 recorder.set_onstop(Some(on_stop.as_ref().unchecked_ref()));
427
428 recorder.start_with_time_slice(1000)?;
429 let win = web_sys::window().ok_or("no window")?;
430 win.add_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref())?;
431
432 let started = js_sys::Date::now();
433 let time = inner.ui.borrow().as_ref().map(|(_, t)| t.clone());
434 let ticker = Closure::<dyn FnMut()>::new(move || {
435 if let Some(t) = &time {
436 t.set_text_content(Some(&clock(js_sys::Date::now() - started)));
437 }
438 });
439 let tick = win.set_interval_with_callback_and_timeout_and_arguments_0(ticker.as_ref().unchecked_ref(), 1000)?;
440
441 Ok(Recording { recorder, stream, take, tick: Some(tick), _on_data: on_data, _on_stop: on_stop, _ticker: ticker })
442}
443
444/// Asks the recorder to stop. The rest happens in `on_stopped`, once its data is in.
445fn stop_current(inner: &Inner) {
446 let recorder = inner.rec.borrow().as_ref().map(|r| r.recorder.clone());
447 if let Some(recorder) = recorder {
448 let _ = recorder.stop();
449 }
450}
451
452/// The recorder stopped: releases the microphone and the timers, and marks the take ended so
453/// the socket task can send `end` once every chunk is acked. Runs inside the recorder's stop
454/// event, so the recording is dropped in a later task, not here.
455fn on_stopped(inner: &Rc<Inner>) {
456 let taken = inner.rec.borrow_mut().take();
457 let Some(rec) = taken else { return };
458 release(&rec);
459 rec.take.ended.set(true);
460 set_ui(inner, false);
461 spawn_local(async move { drop(rec) });
462}
463
464/// Stops the timers and the handlers of a finished recording, and its tracks. The beforeunload
465/// guard stays until the take is concluded.
466fn release(rec: &Recording) {
467 if let Some(win) = web_sys::window()
468 && let Some(id) = rec.tick
469 {
470 win.clear_interval_with_handle(id);
471 }
472 rec.recorder.set_ondataavailable(None);
473 rec.recorder.set_onstop(None);
474 stop_tracks(&rec.stream);
475}
476
477fn stop_tracks(stream: &MediaStream) {
478 for track in stream.get_tracks().iter() {
479 if let Ok(track) = track.dyn_into::<MediaStreamTrack>() {
480 track.stop();
481 }
482 }
483}
484
485/// How one socket of a take ended.
486enum Link {
487 /// The server answered `done`: the part is stored.
488 Done,
489 /// The socket closed, or went quiet.
490 Lost,
491 /// The server answered `reject`.
492 Rejected,
493}
494
495/// The socket task of a take. Connects, sends each chunk once the last one is acked, and
496/// reconnects for as long as the tab lives. A reject gives up. Once every chunk is acked after
497/// the stop, the take is concluded.
498async fn link(inner: Rc<Inner>, take: Rc<Take>) {
499 loop {
500 match connection(&inner, &take).await {
501 Link::Done => break,
502 Link::Lost => sleep(RETRY_MS).await,
503 Link::Rejected => {
504 take.failed.set(true);
505 // Nothing more is sent, so the recording is stopped and its chunks gathered.
506 stop_current(&inner);
507 while !take.ended.get() {
508 sleep(200).await;
509 }
510 break;
511 }
512 }
513 }
514 conclude(inner, take).await;
515}
516
517/// The URL of the take's next socket. A new take asks for its note until the server names it,
518/// then reconnects to its part. A continuation asks for its take until the server gives a part.
519fn url(inner: &Inner, take: &Take) -> Option<String> {
520 let session = take.session.borrow().clone();
521 let query = match (session, take.part.get()) {
522 (Some(s), Some(part)) => format!("session={}&part={part}", enc(&s)),
523 (Some(s), None) => format!("session={}", enc(&s)),
524 (None, _) => format!("note={}", enc(&inner.note_id)),
525 };
526 let loc = web_sys::window()?.location();
527 let proto = if loc.protocol().unwrap_or_default() == "https:" { "wss" } else { "ws" };
528 Some(format!("{proto}://{}/media/live?{query}", loc.host().unwrap_or_default()))
529}
530
531/// One socket of a take: it attaches to the part, then sends the queued chunks one at a time,
532/// each once the one before is acked. A stop sends `end` once the queue is empty.
533async fn connection(inner: &Inner, take: &Take) -> Link {
534 let Some(socket) = url(inner, take).and_then(|u| Socket::open(&u)) else { return Link::Lost };
535 let mut ready = false;
536 let mut waiting = false;
537 let mut end_sent = false;
538 let mut last = js_sys::Date::now();
539 loop {
540 if ready && !waiting {
541 let next = take.queue.borrow().front().cloned();
542 match next {
543 Some(blob) => {
544 if socket.ws.send_with_blob(&blob).is_err() {
545 return Link::Lost;
546 }
547 waiting = true;
548 }
549 None if take.ended.get() && !end_sent => {
550 let _ = socket.ws.send_with_str("end");
551 end_sent = true;
552 }
553 None => {}
554 }
555 }
556 let frame = socket.inbox.borrow_mut().pop_front();
557 let text = match frame {
558 Some(Frame::Text(text)) => text,
559 Some(Frame::Closed) => return Link::Lost,
560 None => {
561 if (!ready || waiting) && js_sys::Date::now() - last > STALL_MS {
562 return Link::Lost;
563 }
564 sleep(100).await;
565 continue;
566 }
567 };
568 last = js_sys::Date::now();
569 let fields: Vec<&str> = text.split(' ').collect();
570 match fields.as_slice() {
571 ["ready", session, part, bytes] => {
572 let (Ok(part), Ok(bytes)) = (part.parse::<u32>(), bytes.parse::<u64>()) else { return Link::Lost };
573 take.attach(session, part, bytes);
574 ready = true;
575 }
576 ["ack", bytes] if waiting => {
577 let Ok(bytes) = bytes.parse::<u64>() else { return Link::Lost };
578 take.acked(bytes);
579 waiting = false;
580 if take.fresh && !take.placed.get() {
581 place(inner, take);
582 }
583 }
584 ["done"] => return Link::Done,
585 ["reject"] => return Link::Rejected,
586 _ => {}
587 }
588 }
589}
590
591impl Take {
592 /// The server's `ready`: the take's id and the part, and what the part already holds. Those
593 /// bytes are not sent again.
594 fn attach(&self, session: &str, part: u32, bytes: u64) {
595 *self.session.borrow_mut() = Some(session.to_owned());
596 self.part.set(Some(part));
597 let mut queue = self.queue.borrow_mut();
598 let mut skip = bytes.saturating_sub(self.sent.get());
599 while skip > 0 {
600 let Some(front) = queue.front() else { break };
601 let size = front.size() as u64;
602 if size <= skip {
603 skip -= size;
604 queue.pop_front();
605 } else {
606 if let Ok(rest) = front.slice_with_f64_and_f64(skip as f64, size as f64) {
607 queue[0] = rest;
608 }
609 break;
610 }
611 }
612 self.sent.set(bytes);
613 }
614
615 /// A chunk is stored: it leaves the queue, and `bytes` is the new offset.
616 fn acked(&self, bytes: u64) {
617 self.queue.borrow_mut().pop_front();
618 self.sent.set(bytes);
619 }
620}
621
622/// Places a new take's URL at its cursor. False while the editor is busy or gone or leaving, or
623/// before the server has named the take.
624fn place(inner: &Inner, take: &Take) -> bool {
625 if inner.detached.get() {
626 return false;
627 }
628 let (Some(ed), Some(session)) = (inner.ed.upgrade(), take.session.borrow().clone()) else { return false };
629 let url = format!("/media/rec/{session}");
630 let done = insert_at(&ed, take.at.as_ref(), embed(&url, &take.name));
631 take.placed.set(done);
632 done
633}
634
635/// Runs once the socket task is done with the take. A rejected take is saved locally, and so is
636/// a new take whose URL could not be placed (the editor went, or the server never named the
637/// take), so its recording is not lost. Then the beforeunload guard goes.
638async fn conclude(inner: Rc<Inner>, take: Rc<Take>) {
639 if !take.failed.get() && take.fresh && !take.placed.get() {
640 // The first chunk may have come while the editor was busy.
641 for _ in 0..5 {
642 if place(&inner, &take) {
643 break;
644 }
645 sleep(200).await;
646 }
647 }
648 if take.failed.get() {
649 notice("mediaFailed");
650 }
651 if take.failed.get() || (take.fresh && !take.placed.get()) {
652 if let Some(blob) = take_blob(&take) {
653 save_locally(&blob, &take.name);
654 }
655 }
656 if let Some(win) = web_sys::window() {
657 let _ = win.remove_event_listener_with_callback("beforeunload", take.unload.as_ref().unchecked_ref());
658 }
659}
660
661/// The whole part as one blob. None when there is nothing to save.
662fn take_blob(take: &Take) -> Option<Blob> {
663 if take.chunks.length() == 0 {
664 return None;
665 }
666 let bag = BlobPropertyBag::new();
667 bag.set_type(&take.mime);
668 let parts: &JsValue = take.chunks.as_ref();
669 Blob::new_with_blob_sequence_and_options(parts, &bag).ok()
670}
671
672/// A take that could not be uploaded goes to the browser's downloads rather than being lost.
673fn save_locally(blob: &Blob, name: &str) {
674 let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return };
675 let Ok(url) = web_sys::Url::create_object_url_with_blob(blob) else { return };
676 let link: HtmlElement = h(&doc, "a", &[("href", &url), ("download", name)], None).unchecked_into();
677 link.click();
678}
679
680/// What a socket hears from the server or the browser.
681enum Frame {
682 Text(String),
683 Closed,
684}
685
686/// A WebSocket with its handlers, which push what arrives into `inbox`. Dropping it clears the
687/// handlers and closes the socket, so an abandoned socket says nothing more.
688struct Socket {
689 ws: WebSocket,
690 inbox: Rc<RefCell<VecDeque<Frame>>>,
691 _on_message: Closure<dyn FnMut(MessageEvent)>,
692 _on_close: Closure<dyn FnMut()>,
693}
694
695impl Socket {
696 fn open(url: &str) -> Option<Socket> {
697 let ws = WebSocket::new(url).ok()?;
698 ws.set_binary_type(BinaryType::Arraybuffer);
699 let inbox: Rc<RefCell<VecDeque<Frame>>> = Rc::default();
700 let sink = inbox.clone();
701 let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |ev: MessageEvent| {
702 if let Some(text) = ev.data().as_string() {
703 sink.borrow_mut().push_back(Frame::Text(text));
704 }
705 });
706 let sink = inbox.clone();
707 let on_close = Closure::<dyn FnMut()>::new(move || sink.borrow_mut().push_back(Frame::Closed));
708 ws.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
709 ws.set_onerror(Some(on_close.as_ref().unchecked_ref()));
710 ws.set_onclose(Some(on_close.as_ref().unchecked_ref()));
711 Some(Socket { ws, inbox, _on_message: on_message, _on_close: on_close })
712 }
713}
714
715impl Drop for Socket {
716 fn drop(&mut self) {
717 self.ws.set_onmessage(None);
718 self.ws.set_onerror(None);
719 self.ws.set_onclose(None);
720 let _ = self.ws.close();
721 }
722}
723
724/// Waits `ms` milliseconds.
725async fn sleep(ms: i32) {
726 let Some(win) = web_sys::window() else { return };
727 let wait = js_sys::Promise::new(&mut |resolve, _reject| {
728 let _ = win.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
729 });
730 let _ = JsFuture::from(wait).await;
731}
732
733/// Percent-encodes a query value.
734fn enc(s: &str) -> String {
735 String::from(js_sys::encode_uri_component(s))
736}
737
738/// Pressed state, label and the m:ss readout of the record button.
739fn set_ui(inner: &Inner, on: bool) {
740 let bound = inner.ui.borrow().clone();
741 let Some((btn, time)) = bound else { return };
742 let value = if on { "true" } else { "false" };
743 let _ = btn.set_attribute("aria-pressed", value);
744 let _ = btn.set_attribute("data-recording", value);
745 let label = btn.owner_document().map(|d| Strings::load(&d).get(if on { "stopRecording" } else { "recordAudio" })).unwrap_or_default();
746 let _ = btn.set_attribute("aria-label", &label);
747 if let Ok(Some(tip)) = btn.query_selector(".tip-label") {
748 tip.set_text_content(Some(&label));
749 }
750 if on {
751 let _ = time.remove_attribute("hidden");
752 time.set_text_content(Some("0:00"));
753 } else {
754 let _ = time.set_attribute("hidden", "");
755 time.set_text_content(None);
756 }
757}
758
759/// `m:ss` for a span in milliseconds.
760fn clock(ms: f64) -> String {
761 let s = (ms / 1000.0).max(0.0) as u64;
762 format!("{}:{:02}", s / 60, s % 60)
763}
764
765/// Local time as `YYYYMMDD-HHMMSS`, for recording names.
766fn stamp() -> String {
767 let d = js_sys::Date::new_0();
768 format!(
769 "{:04}{:02}{:02}-{:02}{:02}{:02}",
770 d.get_full_year(),
771 d.get_month() + 1,
772 d.get_date(),
773 d.get_hours(),
774 d.get_minutes(),
775 d.get_seconds()
776 )
777}