Skip to main content

rustango_cms/
embed.rs

1//! Embed provider discovery + responsive render.
2//!
3//! Naively emitting a pasted URL as
4//! `<iframe src="{the raw url}">` is broken for the URLs
5//! people actually paste: a YouTube *watch* URL or a Vimeo page URL
6//! won't load in an `<iframe>` (you need the provider's *embed* URL),
7//! and an arbitrary URL in an iframe is both broken and a clickjacking
8//! surface.
9//!
10//! This module recognises the common video providers from a public
11//! URL, rewrites it to the embeddable `src`, and the block template
12//! wraps it in a CSS `aspect-ratio` box so the player stays
13//! responsive. Detection is a **pure, synchronous URL transformation**
14//! (no network) so it runs inside the synchronous block-render path
15//! ([`crate::block::BlockRenderCtx`] carries no pool). Providers are
16//! an explicit **whitelist**; an unrecognised URL renders as a safe
17//! link-out rather than an arbitrary iframe.
18//!
19//! oEmbed *metadata* (title / thumbnail fetched from the provider's
20//! oEmbed endpoint) needs outbound HTTP + a cache and is out of scope
21//! here — the render path is synchronous, so that belongs in a
22//! save-time or prefetch-time resolver, tracked separately.
23//!
24//! Adding a provider is a match arm + an id extractor + a test.
25
26/// A recognised embed provider. The whitelist — anything not here
27/// falls back to a link-out.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Provider {
30    YouTube,
31    Vimeo,
32}
33
34impl Provider {
35    /// Human label — also used as the iframe `title` for a11y.
36    #[must_use]
37    pub fn name(self) -> &'static str {
38        match self {
39            Self::YouTube => "YouTube",
40            Self::Vimeo => "Vimeo",
41        }
42    }
43
44    /// CSS `aspect-ratio` value for the responsive wrapper. Both
45    /// current providers default to widescreen; split this out per
46    /// provider if one ever needs a different intrinsic ratio.
47    #[must_use]
48    pub fn aspect_ratio(self) -> &'static str {
49        "16 / 9"
50    }
51}
52
53/// Recognising a public URL: the provider, the embeddable iframe
54/// `src`, and the responsive aspect ratio.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct EmbedTarget {
57    pub provider: Provider,
58    pub src: String,
59    pub aspect_ratio: &'static str,
60}
61
62/// Recognise `url` and return its embeddable target, or `None` for an
63/// unrecognised provider (the caller links out rather than iframing an
64/// arbitrary URL).
65#[must_use]
66pub fn resolve(url: &str) -> Option<EmbedTarget> {
67    let trimmed = url.trim();
68    if let Some(id) = youtube_id(trimmed) {
69        return Some(EmbedTarget {
70            provider: Provider::YouTube,
71            src: format!("https://www.youtube.com/embed/{id}"),
72            aspect_ratio: Provider::YouTube.aspect_ratio(),
73        });
74    }
75    if let Some(id) = vimeo_id(trimmed) {
76        return Some(EmbedTarget {
77            provider: Provider::Vimeo,
78            src: format!("https://player.vimeo.com/video/{id}"),
79            aspect_ratio: Provider::Vimeo.aspect_ratio(),
80        });
81    }
82    None
83}
84
85/// Split a URL into `(lowercased host, rest)` where `rest` begins at
86/// the path/query/fragment. Scheme-relative + bare inputs are handled;
87/// inputs with no host return `None`.
88fn split_host(url: &str) -> Option<(String, &str)> {
89    let after = url.split_once("://").map_or(url, |(_, r)| r);
90    let (host, rest) = match after.find(['/', '?', '#']) {
91        Some(i) => (&after[..i], &after[i..]),
92        None => (after, ""),
93    };
94    // Strip an optional `user@` and `:port` so host matching is clean.
95    let host = host.rsplit('@').next().unwrap_or(host);
96    let host = host.split(':').next().unwrap_or(host);
97    if host.is_empty() {
98        return None;
99    }
100    Some((host.to_ascii_lowercase(), rest))
101}
102
103/// Exact host or any subdomain of `domain`.
104fn host_matches(host: &str, domain: &str) -> bool {
105    host == domain || host.ends_with(&format!(".{domain}"))
106}
107
108/// Extract a YouTube video id from watch / `youtu.be` / embed / shorts
109/// / live URLs.
110fn youtube_id(url: &str) -> Option<String> {
111    let (host, rest) = split_host(url)?;
112    if host_matches(&host, "youtu.be") {
113        return first_segment(rest).filter(|s| is_id(s));
114    }
115    if host_matches(&host, "youtube.com") || host_matches(&host, "youtube-nocookie.com") {
116        if let Some(v) = query_param(rest, "v") {
117            return Some(v).filter(|s| is_id(s));
118        }
119        let path = rest.split(['?', '#']).next().unwrap_or("");
120        let mut segs = path.split('/').filter(|s| !s.is_empty());
121        if let Some(prefix) = segs.next() {
122            if matches!(prefix, "embed" | "shorts" | "v" | "live") {
123                return segs.next().map(str::to_owned).filter(|s| is_id(s));
124            }
125        }
126    }
127    None
128}
129
130/// Extract a Vimeo numeric video id from a page or player URL.
131fn vimeo_id(url: &str) -> Option<String> {
132    let (host, rest) = split_host(url)?;
133    if !host_matches(&host, "vimeo.com") {
134        return None;
135    }
136    let path = rest.split(['?', '#']).next().unwrap_or("");
137    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
138    let candidate = match segs.as_slice() {
139        // player.vimeo.com/video/<id>
140        ["video", id, ..] => *id,
141        // vimeo.com/<id>
142        [id, ..] => *id,
143        _ => return None,
144    };
145    if !candidate.is_empty() && candidate.chars().all(|c| c.is_ascii_digit()) {
146        Some(candidate.to_owned())
147    } else {
148        None
149    }
150}
151
152/// First non-empty path segment (query/fragment stripped).
153fn first_segment(rest: &str) -> Option<String> {
154    let path = rest.split(['?', '#']).next().unwrap_or("");
155    path.split('/').find(|s| !s.is_empty()).map(str::to_owned)
156}
157
158/// Value of query parameter `key`, if present.
159fn query_param(rest: &str, key: &str) -> Option<String> {
160    let q = rest.split_once('?')?.1;
161    let q = q.split('#').next().unwrap_or(q);
162    q.split('&')
163        .filter_map(|p| p.split_once('='))
164        .find(|(k, _)| *k == key)
165        .map(|(_, v)| v.to_owned())
166}
167
168/// YouTube ids are 11 chars of `[A-Za-z0-9_-]`. Validated loosely
169/// (non-empty, url-safe charset) so a future id-format change doesn't
170/// silently drop valid embeds, while still rejecting path noise.
171fn is_id(s: &str) -> bool {
172    !s.is_empty()
173        && s.chars()
174            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[test]
182    fn youtube_watch_url() {
183        let t = resolve("https://www.youtube.com/watch?v=dQw4w9WgXcQ").unwrap();
184        assert_eq!(t.provider, Provider::YouTube);
185        assert_eq!(t.src, "https://www.youtube.com/embed/dQw4w9WgXcQ");
186        assert_eq!(t.aspect_ratio, "16 / 9");
187    }
188
189    #[test]
190    fn youtube_watch_with_extra_params() {
191        let t = resolve("https://youtube.com/watch?v=dQw4w9WgXcQ&t=42s&feature=share").unwrap();
192        assert_eq!(t.src, "https://www.youtube.com/embed/dQw4w9WgXcQ");
193    }
194
195    #[test]
196    fn youtube_short_link_and_shorts_and_embed() {
197        assert_eq!(
198            resolve("https://youtu.be/dQw4w9WgXcQ?t=10").unwrap().src,
199            "https://www.youtube.com/embed/dQw4w9WgXcQ"
200        );
201        assert_eq!(
202            resolve("https://www.youtube.com/shorts/abc123XYZ_-")
203                .unwrap()
204                .src,
205            "https://www.youtube.com/embed/abc123XYZ_-"
206        );
207        // Already an embed URL → normalised to the same canonical form.
208        assert_eq!(
209            resolve("https://www.youtube.com/embed/dQw4w9WgXcQ")
210                .unwrap()
211                .src,
212            "https://www.youtube.com/embed/dQw4w9WgXcQ"
213        );
214    }
215
216    #[test]
217    fn youtube_nocookie_and_subdomain() {
218        assert_eq!(
219            resolve("https://m.youtube.com/watch?v=dQw4w9WgXcQ")
220                .unwrap()
221                .src,
222            "https://www.youtube.com/embed/dQw4w9WgXcQ"
223        );
224        assert_eq!(
225            resolve("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ")
226                .unwrap()
227                .src,
228            "https://www.youtube.com/embed/dQw4w9WgXcQ"
229        );
230    }
231
232    #[test]
233    fn vimeo_page_and_player_urls() {
234        let t = resolve("https://vimeo.com/123456789").unwrap();
235        assert_eq!(t.provider, Provider::Vimeo);
236        assert_eq!(t.src, "https://player.vimeo.com/video/123456789");
237        assert_eq!(
238            resolve("https://player.vimeo.com/video/123456789?h=abc")
239                .unwrap()
240                .src,
241            "https://player.vimeo.com/video/123456789"
242        );
243    }
244
245    #[test]
246    fn vimeo_rejects_non_numeric_path() {
247        // /channels/staffpicks etc. aren't a video id.
248        assert!(resolve("https://vimeo.com/channels/staffpicks").is_none());
249    }
250
251    #[test]
252    fn unknown_provider_is_none() {
253        assert!(resolve("https://example.com/video/abc").is_none());
254        assert!(resolve("https://twitter.com/jack/status/20").is_none());
255        assert!(resolve("not a url").is_none());
256        assert!(resolve("").is_none());
257    }
258
259    #[test]
260    fn watch_without_v_param_is_none() {
261        assert!(resolve("https://www.youtube.com/watch?feature=share").is_none());
262    }
263
264    #[test]
265    fn scheme_relative_and_no_scheme() {
266        // Scheme is optional — people paste bare hosts too.
267        assert_eq!(
268            resolve("youtube.com/watch?v=dQw4w9WgXcQ").unwrap().src,
269            "https://www.youtube.com/embed/dQw4w9WgXcQ"
270        );
271    }
272}