From 880097e4638c0046b23778be12858bff3d131b75 Mon Sep 17 00:00:00 2001 From: Mehfuz Hossain Date: Fri, 13 Nov 2026 16:22:24 -0800 Subject: [PATCH] Share links: one fixed link per project, QR codes, export dialog fixes - A project's link id is derived from its project id (SHA-256, 12 base62 characters; share::link_id in the app, linkIdFor on the server), so the Export dialog always shows the link, even before anything is uploaded. A project's earlier random-id link is replaced by it on the next share. - QR code for the link: a toggle on the link box in the app, and on the share page (small beside the actions, large on click, for a projector). - Share page: rendered page kept in the edge cache for 30 s. - Export dialog: link box text centred, step contents aligned with step names, link shown while uploading instead of the "Done closes this" note. - "Your links" list removed from the Export dialog. --- Cargo.lock | 7 + apps/studio/Cargo.toml | 1 + apps/studio/src/editor.rs | 3 + apps/studio/src/export.rs | 177 +++++++++++++--------- apps/studio/src/share.rs | 62 +++++--- apps/studio/src/theme.rs | 4 + apps/studio/src/widgets.rs | 63 +++++++- backend/README.md | 5 +- backend/supabase/functions/share/index.ts | 28 +++- functions/s/[id].js | 50 +++++- 10 files changed, 295 insertions(+), 105 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 69873b6..4a2a52b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4084,6 +4084,12 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quick-error" version = "2.0.1" @@ -5063,6 +5069,7 @@ dependencies = [ "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", "parking_lot", + "qrcode", "raw-window-handle", "rfd", "serde", diff --git a/apps/studio/Cargo.toml b/apps/studio/Cargo.toml index 20ce695..a143995 100644 --- a/apps/studio/Cargo.toml +++ b/apps/studio/Cargo.toml @@ -42,6 +42,7 @@ cpal = "0.18" muda = "0.21" image.workspace = true parking_lot.workspace = true +qrcode = { version = "0.14.1", default-features = false } [target.'cfg(target_os = "linux")'.dependencies] # winit needs a windowing backend on Linux diff --git a/apps/studio/src/editor.rs b/apps/studio/src/editor.rs index b703a2d..7893a19 100644 --- a/apps/studio/src/editor.rs +++ b/apps/studio/src/editor.rs @@ -1685,6 +1685,9 @@ impl Editor { /// progress and result of the running export in the same dialog. fn export_modal(&mut self, ctx: &egui::Context) { let mut ex = std::mem::take(&mut self.export); + if ex.project_id != self.session.pkg.project.id { + ex.project_id = self.session.pkg.project.id.clone(); + } ex.poll(ctx); if ex.open || ex.is_busy() { // opening the dialog (button or ⌘E) stops playback behind it diff --git a/apps/studio/src/export.rs b/apps/studio/src/export.rs index 2587d2e..efb1062 100644 --- a/apps/studio/src/export.rs +++ b/apps/studio/src/export.rs @@ -87,11 +87,18 @@ pub struct ExportDialog { share_with_export: bool, /// The running or finished export makes a link too: step 2 of the progress dialog. export_shared: bool, - /// "Your links": the account's links once loaded, and the list being fetched or a delete - /// running. - links_open: bool, - links: Option, String>>, - links_rx: Option, String>>>, + /// This project's link as the server has it (one per project), shown whenever the dialog + /// is open; asked again each time it opens. `project_link_for`: the project asked about. + project_link: Option, + /// Whether the server has answered for this project (so "nothing uploaded yet" is known). + project_link_known: bool, + project_link_for: Option, + /// The editor's project id (set by the editor every frame): its link is known without + /// asking the server (`share::link_url`). + pub project_id: String, + /// The QR code under the link is showing. + qr_open: bool, + project_link_rx: Option, String>>>, } /// An empty dialog: no file reads, no network. `std::mem::take` puts one in place every frame @@ -99,7 +106,7 @@ pub struct ExportDialog { /// that loads the license and talks to the backend. impl Default for ExportDialog { fn default() -> Self { - ExportDialog { open: false, license: sf_license::Status::Invalid("no key".into()), email: String::new(), activation: None, check_in: None, activation_msg: None, code_sent_to: None, code: String::new(), signing_in: false, promo: String::new(), promo_open: false, checkout: None, claim_until: None, next_claim: None, claim: None, free_left: None, free_rx: None, was_open: false, license_seen: 0, free_job: false, format: Format::Mp4, fps: 60.0, height: 1080, quality: QualityPreset::SocialMedia, codec: VideoCodec::H264, audio: true, job: None, progress: None, result: None, started: None, share_request: None, share_running: None, share_cancel: false, last_link: None, share_with_export: false, export_shared: false, links_open: false, links: None, links_rx: None } + ExportDialog { open: false, license: sf_license::Status::Invalid("no key".into()), email: String::new(), activation: None, check_in: None, activation_msg: None, code_sent_to: None, code: String::new(), signing_in: false, promo: String::new(), promo_open: false, checkout: None, claim_until: None, next_claim: None, claim: None, free_left: None, free_rx: None, was_open: false, license_seen: 0, free_job: false, format: Format::Mp4, fps: 60.0, height: 1080, quality: QualityPreset::SocialMedia, codec: VideoCodec::H264, audio: true, job: None, progress: None, result: None, started: None, share_request: None, share_running: None, share_cancel: false, last_link: None, share_with_export: false, export_shared: false, project_link: None, project_link_known: false, project_link_for: None, project_id: String::new(), qr_open: false, project_link_rx: None } } } @@ -282,15 +289,27 @@ impl ExportDialog { self.license = sf_license::load_saved().map(|k| sf_license::verify(&k)).unwrap_or_else(|| sf_license::Status::Invalid("no key".into())); } self.poll_checkout(ctx); + if self.open && !self.was_open { + // asked again (the link may have been made or deleted elsewhere); the last answer + // shows meanwhile + self.project_link_for = None; + } self.poll_free_exports(ctx); - if let Some(rx) = &self.links_rx { + if let Some(rx) = &self.project_link_rx { match rx.try_recv() { Ok(r) => { - self.links = Some(r); - self.links_rx = None; + self.project_link_rx = None; + // offline or a server error: keep what was shown + if let Ok(link) = r { + // a link made before ids were derived from the project counts as + // nothing uploaded: the next share moves the project to its own link + let own = crate::share::link_url(self.project_link_for.as_deref().unwrap_or_default()); + self.project_link = link.filter(|l| *l == own); + self.project_link_known = true; + } } Err(std::sync::mpsc::TryRecvError::Empty) => ctx.request_repaint_after(std::time::Duration::from_millis(200)), - Err(std::sync::mpsc::TryRecvError::Disconnected) => self.links_rx = None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.project_link_rx = None, } } if let Some(rx) = &self.check_in { @@ -434,7 +453,7 @@ impl ExportDialog { let p = self.progress; let frac = p.map(|p| p.frame as f32 / p.total_frames.max(1) as f32).unwrap_or(0.0); step_header(ui, 1, "Video", if exporting { StepState::Active } else { StepState::Done }, exporting.then(|| format!("{:.0}%", frac * 100.0))); - ui.indent("export-step-video", |ui| { + step_body(ui, |ui| { if exporting { progress_bar(ui, frac); ui.add_space(2.0); @@ -464,10 +483,12 @@ impl ExportDialog { } }); - // 2. its share link - if sharing { + // 2. its share link: made by this export, or the project's link from before (shown + // so it is always at hand, with its QR code) + if sharing || (crate::share::allowed() && self.uploaded() == Some(true)) { ui.add_space(10.0); let state = match (&self.share_running, &self.last_link) { + _ if !sharing => StepState::Done, _ if exporting => StepState::Waiting, (Some(_), _) => StepState::Active, (None, Some(Err(_))) => StepState::Failed, @@ -475,11 +496,19 @@ impl ExportDialog { }; let pct = self.share_running.as_ref().map(|(f, _)| format!("{:.0}%", f * 100.0)); step_header(ui, 2, "Share link", state, pct); - ui.indent("export-step-link", |ui| { - if exporting { + step_body(ui, |ui| { + if sharing && exporting { + // the link is known already: it can be copied (or scanned) while this runs + if let Some(url) = self.shown_link() { + widgets::link_field_qr(ui, &url, &mut self.qr_open); + ui.add_space(6.0); + } widgets::hint(ui, "Uploads when the video is ready."); } else { self.link_status_ui(ui); + if !sharing { + widgets::hint(ui, "Plays the last video shared from this project: export with \u{201c}Make a share link too\u{201d} to update it."); + } } }); } @@ -555,42 +584,70 @@ impl ExportDialog { crate::share::ShareSettings { fps, max_height, quality, include_audio: self.audio } } - fn load_links(&mut self, delete: Option) { + /// Ask the server for this project's link, once per open of the dialog. + fn ask_project_link(&mut self, project: &str) { + if self.project_link_for.as_deref() == Some(project) { + return; + } + if self.project_link_for.as_deref().is_some_and(|p| p != project) { + // another project's link must not show while this one's is asked for + self.project_link = None; + self.project_link_known = false; + } + self.project_link_for = Some(project.to_string()); let (tx, rx) = channel(); + let id = project.to_string(); std::thread::spawn(move || { - let r = match delete { - Some(id) => crate::share::delete(&id).and_then(|_| crate::share::list()), - None => crate::share::list(), - }; - let _ = tx.send(r); + let _ = tx.send(crate::share::project_link(&id)); }); - self.links_rx = Some(rx); + self.project_link_rx = Some(rx); } + /// The share being made (progress bar and Cancel), or the project's link in a text box /// (copy, open), or why it failed. fn link_status_ui(&mut self, ui: &mut egui::Ui) { let pal = theme::p(); + if let Some(url) = self.shown_link() { + widgets::link_field_qr(ui, &url, &mut self.qr_open); + ui.add_space(6.0); + } if let Some((frac, label)) = self.share_running.clone() { progress_bar(ui, frac); ui.add_space(2.0); ui.horizontal(|ui| { widgets::hint(ui, &label); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.link(RichText::new("Cancel").size(13.0).color(pal.text_dim)).on_hover_text("Stop making this link").clicked() { + if ui.link(RichText::new("Cancel").size(13.0).color(pal.text_dim)).on_hover_text("Stop uploading; the link keeps what it had").clicked() { self.share_cancel = true; } }); }); - widgets::hint(ui, "Done closes this; a notification says when the link is on your clipboard."); + widgets::hint(ui, if self.uploaded() == Some(true) { "The link plays the previous video until this upload finishes." } else { "Copy the link now: it plays the video once the upload finishes." }); + } else if let Some(Err(e)) = self.last_link.clone() { + ui.add(egui::Label::new(RichText::new(format!("The upload failed: {e}")).size(13.0).color(pal.danger)).wrap()); + } else if self.uploaded() == Some(false) { + widgets::hint(ui, "Nothing is uploaded yet: export with \u{201c}Make a share link too\u{201d} to put this video behind the link."); + } + } + + /// This project's link: derived from its id, so it is the same every time (the server + /// gives the project this id; `share::link_id`). + fn shown_link(&self) -> Option { + if !self.project_id.is_empty() { + return Some(crate::share::link_url(&self.project_id)); + } + self.last_link.clone().and_then(Result::ok) + } + + /// Whether a video is behind the link (None: not known yet). + fn uploaded(&self) -> Option { + if matches!(self.last_link, Some(Ok(_))) || self.project_link.is_some() { + Some(true) + } else if self.project_link_known { + Some(false) } else { - match self.last_link.clone() { - Some(Ok(url)) => widgets::link_field(ui, &url), - Some(Err(e)) => { - ui.add(egui::Label::new(RichText::new(format!("The last link failed: {e}")).size(13.0).color(pal.danger)).wrap()); - } - None => {} - } + None } } @@ -610,52 +667,15 @@ impl ExportDialog { ui.separator(); return; } - if self.share_running.is_none() && self.last_link.is_none() { - widgets::hint(ui, "With \u{201c}Make a share link too\u{201d}, Export uploads the video and copies a link anyone can watch in a browser. Each project keeps one link; exporting again updates it."); - } else { - self.link_status_ui(ui); + // the project's one link, always: exporting with the box ticked puts the video behind it + self.link_status_ui(ui); + if self.share_running.is_none() && self.uploaded() == Some(true) && !matches!(self.last_link, Some(Err(_))) { + widgets::hint(ui, "This project's link. Export with \u{201c}Make a share link too\u{201d} to update its video."); } ui.add_space(2.0); if ui.checkbox(&mut self.share_with_export, "Make a share link too").on_hover_text("Export uploads the video it writes and copies a link anyone can watch").changed() { crate::share::set_with_export(self.share_with_export); } - let label = if self.links_open { "Hide your links" } else { "Your links" }; - if ui.link(RichText::new(label).color(pal.text_dim)).clicked() { - self.links_open = !self.links_open; - if self.links_open && self.links_rx.is_none() { - self.load_links(None); - } - } - if self.links_open { - let busy = self.links_rx.is_some(); - match &self.links { - _ if busy && self.links.is_none() => widgets::hint(ui, "Loading…"), - Some(Err(e)) => { - ui.add(egui::Label::new(RichText::new(e).size(13.0).color(pal.danger)).wrap()); - } - Some(Ok(links)) if links.is_empty() => widgets::hint(ui, "No links yet."), - Some(Ok(links)) => { - let mut delete: Option = None; - for l in links.clone() { - ui.horizontal(|ui| { - let title = if l.title.is_empty() { "Untitled".to_string() } else { l.title.clone() }; - ui.label(RichText::new(title).size(13.0).color(pal.text)).on_hover_text(&l.url); - widgets::hint(ui, &format!("{} · {} view{}", l.created, l.views, if l.views == 1 { "" } else { "s" })); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add_enabled_ui(!busy, |ui| widgets::icon_button_tinted(ui, widgets::Icon::Trash, 13.0, "Delete this link and its video", pal.danger)).inner.clicked() { - delete = Some(l.id.clone()); - } - widgets::copy_button(ui, &l.url, "Copy link"); - }); - }); - } - if let Some(id) = delete { - self.load_links(Some(id)); - } - } - None => {} - } - } ui.add_space(4.0); ui.separator(); } @@ -750,6 +770,9 @@ impl ExportDialog { ui.separator(); } if self.license.is_valid() { + if crate::share::allowed() { + self.ask_project_link(&ed.session.pkg.project.id); + } self.share_ui(ui); } widgets::title(ui, "Format"); @@ -919,6 +942,16 @@ fn step_header(ui: &mut egui::Ui, n: u32, name: &str, state: StepState, right: O ui.add_space(4.0); } +/// What a step shows under its header, lined up with the step's name (past the 18 px marker) +/// and as wide as the box from there. +fn step_body(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { + let left = 18.0 + ui.spacing().item_spacing.x; + egui::Frame::NONE.inner_margin(egui::Margin { left: left as i8, right: 0, top: 0, bottom: 0 }).show(ui, |ui| { + ui.set_width(ui.available_width()); + add(ui); + }); +} + /// A full-width bar painted by hand (egui's ProgressBar shrinks to its label in these dialogs). fn progress_bar(ui: &mut egui::Ui, frac: f32) { let pal = theme::p(); diff --git a/apps/studio/src/share.rs b/apps/studio/src/share.rs index e3ae0d2..4e96040 100644 --- a/apps/studio/src/share.rs +++ b/apps/studio/src/share.rs @@ -312,11 +312,9 @@ impl Read for Counting<'_> { /// A link of this account, as `share` lists them. #[derive(Clone, Debug)] pub struct Link { - pub id: String, pub url: String, - pub title: String, - pub views: u64, - pub created: String, + /// The project (file id) the link belongs to: one link per project. + pub project: Option, } /// This account's links, newest first. @@ -330,11 +328,8 @@ pub fn list() -> Result, String> { a.iter() .filter_map(|l| { Some(Link { - id: l["id"].as_str()?.into(), url: l["url"].as_str()?.into(), - title: l["title"].as_str().unwrap_or("").into(), - views: l["views"].as_u64().unwrap_or(0), - created: l["created_at"].as_str().unwrap_or("").get(..10).unwrap_or("").into(), + project: l["project"].as_str().map(str::to_string), }) }) .collect() @@ -342,16 +337,28 @@ pub fn list() -> Result, String> { .unwrap_or_default()) } -/// Delete a link and its video for good. -pub fn delete(id: &str) -> Result<(), String> { - let mut req = sf_license::owner_auth().ok_or("Sign in to delete share links.")?; - req["action"] = "delete".into(); - req["id"] = id.into(); - match sf_license::call_backend_status("share", req) { - // already gone: what the user wanted - Ok(_) | Err((404, _)) => Ok(()), - Err((_, e)) => Err(e), - } +/// The page a link id opens. +pub const PAGE_URL: &str = "https://screenforge.studio/s/"; + +/// A project's link id, the same every time: 12 base62 characters of +/// SHA-256("screenforge-share/" + project id). The app shows a project's link before anything +/// is uploaded; the server gives a new link this id (`linkIdFor` in the share function), and +/// links made before keep theirs. Unguessable as long as the project id is (10 random base62 +/// characters, kept in the project file). +pub fn link_id(project: &str) -> String { + use sha2::Digest; + const ABC: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + let d = sha2::Sha256::digest(format!("screenforge-share/{project}")); + d[..12].iter().map(|b| ABC[*b as usize % 62] as char).collect() +} + +pub fn link_url(project: &str) -> String { + format!("{PAGE_URL}{}", link_id(project)) +} + +/// The link of the project with this id, if it has one. +pub fn project_link(project: &str) -> Result, String> { + Ok(list()?.into_iter().find(|l| l.project.as_deref() == Some(project)).map(|l| l.url)) } /// Where "Make a share link too" is remembered (`allowed_file` sits next to it). @@ -422,6 +429,24 @@ mod tests { assert!((job.fraction() - 1.0).abs() < 1e-6); } + #[test] + fn link_id_is_the_servers() { + // the same values as `linkIdFor` in backend/supabase/functions/share/index.ts + assert_eq!(link_id("iv5Pww9n2l"), "v3BwvryVLJ5B"); + assert_eq!(link_id("abc"), "LyVS9w6Jh3S9"); + assert_eq!(link_url("abc"), "https://screenforge.studio/s/LyVS9w6Jh3S9"); + } + + /// Against the live backend: the account's links, with the project each belongs to. + /// `cargo test -p studio list_shows_projects -- --ignored --nocapture` + #[test] + #[ignore] + fn list_shows_projects() { + for l in list().unwrap() { + println!("{} {:?}", l.url, l.project); + } + } + /// Against the live backend with this computer's license: one project, one link. /// `cargo test -p studio share_again_keeps_the_link -- --ignored` #[test] @@ -454,6 +479,7 @@ mod tests { req["id"] = first.clone().into(); call(req).unwrap(); assert_eq!(first, second, "same link"); + assert_eq!(first, link_id(&project), "the project's derived id"); assert_ne!(v1, v2, "new video address"); assert_eq!(served.as_deref(), Some("2000"), "the new video is served"); } diff --git a/apps/studio/src/theme.rs b/apps/studio/src/theme.rs index 5db2099..9098b30 100644 --- a/apps/studio/src/theme.rs +++ b/apps/studio/src/theme.rs @@ -50,6 +50,10 @@ pub struct Palette { pub thumb_empty: Color32, } +/// A QR code's modules and paper: black on white in every theme, so phone cameras read it. +pub const QR_INK: Color32 = Color32::BLACK; +pub const QR_PAPER: Color32 = Color32::WHITE; + pub const DARK: Palette = Palette { dark: true, // Catppuccin Mocha diff --git a/apps/studio/src/widgets.rs b/apps/studio/src/widgets.rs index 73e3856..0a17f50 100644 --- a/apps/studio/src/widgets.rs +++ b/apps/studio/src/widgets.rs @@ -345,30 +345,71 @@ pub fn text_field(ui: &mut Ui, text: &mut String, hint: &str) -> Response { field(ui, text, hint) } -/// A link in a read-only text box (selectable), with copy and open-in-browser buttons inside. -pub fn link_field(ui: &mut Ui, url: &str) { +/// A link in a read-only box with copy, QR and open buttons: `qr` toggles a large code under +/// the field, for a room to scan off a projector. +pub fn link_field_qr(ui: &mut Ui, url: &str, qr: &mut bool) { + let mut qr = Some(qr); let pal = theme::p(); egui::Frame::NONE .fill(pal.bg) .stroke(Stroke::new(1.0, pal.border)) .corner_radius(CornerRadius::same(BUTTON_RADIUS)) - .inner_margin(egui::Margin { left: 10, right: 4, top: 0, bottom: 0 }) + .inner_margin(egui::Margin { left: 10, right: 6, top: 0, bottom: 0 }) .show(ui, |ui| { - ui.horizontal(|ui| { + // text and buttons centred in one 32 px row + ui.allocate_ui_with_layout(vec2(ui.available_width(), 32.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 2.0; - let buttons = 2.0 * 25.0 + 2.0 * 2.0; + let n = if qr.is_some() { 3.0 } else { 2.0 }; + let buttons = n * 25.0 + n * 2.0; let mut text = url; ui.add_sized( vec2((ui.available_width() - buttons).max(40.0), 32.0), - egui::TextEdit::singleline(&mut text).font(egui::FontId::proportional(13.0)).text_color(pal.text).frame(egui::Frame::NONE).margin(egui::Margin::ZERO), + egui::TextEdit::singleline(&mut text).font(egui::FontId::proportional(13.0)).text_color(pal.text).frame(egui::Frame::NONE).vertical_align(egui::Align::Center).margin(egui::Margin::ZERO).min_size(vec2(0.0, 32.0)), ) .on_hover_text(url); copy_button(ui, url, "Copy link"); + if let Some(open) = qr.as_deref_mut() { + let tint = if *open { theme::p().accent } else { theme::p().text }; + if icon_button_tinted(ui, Icon::Qr, 13.0, if *open { "Hide the QR code" } else { "Show a QR code to scan" }, tint).clicked() { + *open = !*open; + } + } if icon_button(ui, Icon::OpenExternal, 13.0, "Open in the browser").clicked() { crate::os::open(url); } }); }); + if qr.is_some_and(|o| *o) { + ui.add_space(8.0); + qr_code(ui, url, 168.0); + } +} + +/// `text` as a QR code, `side` points square with its quiet zone, centred in the row: dark +/// modules on white whatever the theme, so phone cameras read it. +pub fn qr_code(ui: &mut Ui, text: &str, side: f32) { + let Ok(code) = qrcode::QrCode::with_error_correction_level(text.as_bytes(), qrcode::EcLevel::M) else { return }; + let n = code.width(); + let colors = code.to_colors(); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + let p = ui.painter(); + // the white square is part of the code (its quiet zone), not UI chrome + let (paper, ink) = (theme::QR_PAPER, theme::QR_INK); + p.rect_filled(rect, CornerRadius::same(2), paper); + let quiet = 4.0; + let m = side / (n as f32 + 2.0 * quiet); + let origin = rect.min + vec2(quiet * m, quiet * m); + for y in 0..n { + for x in 0..n { + if colors[y * n + x] == qrcode::Color::Dark { + let min = origin + vec2(x as f32 * m, y as f32 * m); + // a hair wider than a module so neighbours join without seams + p.rect_filled(Rect::from_min_size(min, vec2(m + 0.3, m + 0.3)), 0.0, ink); + } + } + } + }); } fn field(ui: &mut Ui, text: &mut String, hint: &str) -> Response { @@ -494,6 +535,8 @@ pub enum Icon { Plus, /// Arrow leaving a box (open a page in the browser). OpenExternal, + /// Three corner squares and a few modules (show a link's QR code). + Qr, /// Magnifying glass (search). Search, /// Heart outline (not a favourite yet). @@ -667,6 +710,14 @@ pub fn paint_icon(p: &egui::Painter, rect: Rect, icon: Icon, color: Color32) { } p.add(egui::Shape::closed_line(pts, s)); } + Icon::Qr => { + // the finder squares at three corners, a few modules at the fourth + for (x, y) in [(-0.85, -0.85), (0.15, -0.85), (-0.85, 0.15)] { + p.rect_stroke(rr(x, y, x + 0.7, y + 0.7), 1.0, s, egui::StrokeKind::Middle); + } + p.rect_filled(rr(0.15, 0.15, 0.45, 0.45), 0.0, color); + p.rect_filled(rr(0.55, 0.55, 0.85, 0.85), 0.0, color); + } Icon::OpenExternal => { // box open at its top-right corner line((0.05, -0.8), (-0.8, -0.8)); diff --git a/backend/README.md b/backend/README.md index 3fa2588..9c5b812 100644 --- a/backend/README.md +++ b/backend/README.md @@ -191,7 +191,10 @@ H.264 MP4 export goes up as it is; a GIF, ProRes or VP9 one is rendered again as A project has one link (`share_links.project`, the project file's id): exporting it again replaces the video behind the same URL, and the page keeps the old one until the new upload is complete (`pending_bytes`; `rev` adds `?v=` to the media URLs so the CDN serves the new file). -Export → Share link → Your links lists, copies and deletes the links. +A link's id is derived from the project id (`share::link_id` / `linkIdFor`), so the app shows +the project's link before anything is uploaded; the share page shows its QR code. A project's +link made before that (random id) is deleted on its next share, for the derived one. The app no longer lists or deletes links (`delete` stays on +the server). ``` app ──{ device, key, bytes, poster }──▶ share (create) ──▶ presigned PUT URLs (R2, 6 h) diff --git a/backend/supabase/functions/share/index.ts b/backend/supabase/functions/share/index.ts index 6e37005..a6a91e9 100644 --- a/backend/supabase/functions/share/index.ts +++ b/backend/supabase/functions/share/index.ts @@ -47,6 +47,17 @@ function newId(): string { return out; } +/** + * A project's link id, the same every time: 12 base62 characters of + * SHA-256("screenforge-share/" + project). The app shows it before anything is uploaded + * (`share::link_id`; "iv5Pww9n2l" → "v3BwvryVLJ5B", "abc" → "LyVS9w6Jh3S9"). + */ +async function linkIdFor(project: string): Promise { + const abc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + const d = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`screenforge-share/${project}`))); + return Array.from(d.slice(0, 12), (b) => abc[b % 62]).join(""); +} + /** The license email of the computer making the request, or an error reply. */ async function owner(client: SupabaseClient, device: unknown, key: unknown): Promise { if (!isDevice(device)) return fail("device required", 400); @@ -106,13 +117,20 @@ serve(async (req) => { const { data: stale } = await client.from("share_links").select("id").eq("email", email).eq("status", "uploading").lt("created_at", new Date(Date.now() - 24 * 3600 * 1000).toISOString()); for (const s of stale ?? []) await removeLink(client, s.id); const project = isProject(body.project) ? body.project : null; - const { data: existing } = project + // the project's link id is derived from the project (the link the app shows); one + // made before that, with a random id, is dropped for it: the project keeps one link + const own = project ? await linkIdFor(project) : null; + let { data: existing } = project ? await client.from("share_links").select("id").eq("email", email).eq("project", project).maybeSingle() : { data: null }; + if (existing && own && existing.id !== own) { + await removeLink(client, existing.id); + existing = null; + } const { data: used } = await client.from("share_links").select("id, bytes").eq("email", email); // a replaced video's old size no longer counts const total = (used ?? []).filter((r) => r.id !== existing?.id).reduce((n, r) => n + Number(r.bytes), 0); - if (total + bytes > MAX_ACCOUNT_BYTES) return fail(`Your share links use ${(total / 1024 ** 3).toFixed(1)} GB of ${(MAX_ACCOUNT_BYTES / 1024 ** 3).toFixed(0)} GB. Delete some old links (Export → Share link → Your links) and try again.`, 413); + if (total + bytes > MAX_ACCOUNT_BYTES) return fail(`Your share links use ${(total / 1024 ** 3).toFixed(1)} GB of ${(MAX_ACCOUNT_BYTES / 1024 ** 3).toFixed(0)} GB. Contact ScreenForge support to remove old links, then try again.`, 413); const int = (v: unknown) => (Number.isInteger(v) && (v as number) > 0 && (v as number) < 2 ** 31 ? v as number : null); const fields = { device_id: body.device, title: String(body.title ?? "").slice(0, 200), width: int(body.width), height: int(body.height), duration_ms: int(body.duration_ms), pending_bytes: bytes, updated_at: new Date().toISOString() }; let id: string; @@ -122,7 +140,9 @@ serve(async (req) => { const { error } = await client.from("share_links").update(fields).eq("id", id); if (error) throw new Error(error.message); } else { - id = newId(); + // the project's own id, unless another account holds it (a copied project file) + const { data: taken } = own ? await client.from("share_links").select("id").eq("id", own).maybeSingle() : { data: null }; + id = own && !taken ? own : newId(); const { error } = await client.from("share_links").insert({ id, email, project, bytes, has_poster: poster > 0, ...fields }); if (error) throw new Error(error.message); } @@ -147,7 +167,7 @@ serve(async (req) => { case "list": { const email = await owner(client, body.device, body.key); if (email instanceof Response) return email; - const { data, error } = await client.from("share_links").select("id, title, bytes, duration_ms, views, created_at, updated_at").eq("email", email).eq("status", "ready").order("updated_at", { ascending: false }).limit(200); + const { data, error } = await client.from("share_links").select("id, project, title, bytes, duration_ms, views, created_at, updated_at").eq("email", email).eq("status", "ready").order("updated_at", { ascending: false }).limit(200); if (error) throw new Error(error.message); return json({ links: (data ?? []).map((l) => ({ ...l, url: urlFor(l.id) })) }); } diff --git a/functions/s/[id].js b/functions/s/[id].js index 7d0e9f7..e603864 100644 --- a/functions/s/[id].js +++ b/functions/s/[id].js @@ -38,6 +38,17 @@ footer{margin-top:auto;padding-top:40px;padding-bottom:28px;color:var(--dim);fon footer a{color:var(--fg)} .gone{text-align:center;padding:18vh 0} .gone h1{font-size:26px} +.side{display:flex;gap:16px;align-items:flex-start;margin-top:18px} +.side .actions{margin-top:0} +.qr{display:block;background:#fff;border-radius:2px} +.qr svg{display:block;width:100%;height:100%} +.qr-mini{width:92px;height:92px;padding:0;border:1px solid var(--line);border-radius:2px;background:#fff;cursor:zoom-in} +.qr-mini .qr{width:100%;height:100%} +#qr-view{position:fixed;inset:0;z-index:10;display:none;flex-direction:column;align-items:center;justify-content:center;gap:18px;padding:16px;background:rgba(10,10,14,.9);cursor:zoom-out} +#qr-view.open{display:flex} +#qr-view .qr{width:min(72vmin,460px);height:min(72vmin,460px)} +#qr-view p{color:#f8f8f2;font-size:clamp(16px,2.8vmin,24px);text-align:center;overflow-wrap:anywhere} +@media (max-width:640px){.qr-mini{display:none}} `; function page({ title, head = "", body }) { @@ -52,13 +63,27 @@ ${body} } function notFound() { - const body = `

This video is not available

The link may have been deleted by its owner, or mistyped.

`; + const body = `

This video is not available

Its video may not be uploaded yet, or the link was deleted or mistyped.

`; return new Response(page({ title: "Video not available · ScreenForge", head: ``, body }), { status: 404, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=30" } }); } -export async function onRequestGet({ params }) { +// Pages Functions are not cached by Cloudflare on their own: the rendered page is kept in the +// edge cache for this long, so a visit does not wait on Supabase each time. A replaced video +// (new `rev`) shows within this time. +const PAGE_TTL = 30; + +export async function onRequestGet({ params, request, waitUntil }) { const id = String(params.id ?? ""); if (!/^[A-Za-z0-9]{12}$/.test(id)) return notFound(); + const key = new Request(new URL(`/s/${id}`, request.url).toString()); + const cached = await caches.default.match(key); + if (cached) return cached; + const res = await render(id); + if (res.status === 200) waitUntil(caches.default.put(key, res.clone())); + return res; +} + +async function render(id) { let s; try { const r = await fetch(`${SUPABASE_URL}/functions/v1/share`, { @@ -93,13 +118,30 @@ export async function onRequestGet({ params }) { const body = `

${esc(title)}

${[date, duration(s.duration_ms), views].filter(Boolean).map(esc).join("·")}

-
Download
+
Download
+
+ + `; return new Response(page({ title: `${title} · ScreenForge`, head: og, body }), { - headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=60" }, + headers: { "content-type": "text/html; charset=utf-8", "cache-control": `public, max-age=${PAGE_TTL}` }, }); }