1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Provider {
30 YouTube,
31 Vimeo,
32}
33
34impl Provider {
35 #[must_use]
37 pub fn name(self) -> &'static str {
38 match self {
39 Self::YouTube => "YouTube",
40 Self::Vimeo => "Vimeo",
41 }
42 }
43
44 #[must_use]
48 pub fn aspect_ratio(self) -> &'static str {
49 "16 / 9"
50 }
51}
52
53#[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#[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
85fn 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 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
103fn host_matches(host: &str, domain: &str) -> bool {
105 host == domain || host.ends_with(&format!(".{domain}"))
106}
107
108fn 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
130fn 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 ["video", id, ..] => *id,
141 [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
152fn 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
158fn 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
168fn 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 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 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 assert_eq!(
268 resolve("youtube.com/watch?v=dQw4w9WgXcQ").unwrap().src,
269 "https://www.youtube.com/embed/dQw4w9WgXcQ"
270 );
271 }
272}