1use std::process::Stdio;
74use std::time::Duration;
75
76use reqwest::Url;
77
78use crate::helpers::unix_now;
79
80const FIND_TIMEOUT: Duration = Duration::from_secs(40);
83
84const AVAILABLE_WAIT_MAX: Duration = Duration::from_secs(15);
87
88const AVAILABLE_AT: &str = "available_at=%(available_at)s";
92
93const SOUND: &str = "sound=%(acodec)s";
96
97const LISTED_IN: &str = "listed_in=%(manifest_url)s";
100
101const FORMAT: &str = "b[height<=720]/b/bv[protocol^=m3u8]";
106
107const ID_CHARS: usize = 11;
109
110const SHORT_SIZE: (u32, u32) = (1080, 1920);
113
114#[derive(Debug, Clone, PartialEq, Eq, Hash)]
118pub struct VideoId(String);
119
120impl VideoId {
121 fn parse(id: &str) -> Option<Self> {
123 let shaped = id.len() == ID_CHARS && id.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
124 (shaped && id != "videoseries").then(|| Self(id.to_string()))
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct Video {
133 pub id: VideoId,
134 pub size: Option<(u32, u32)>,
137}
138
139impl Video {
140 pub fn page(&self) -> String {
143 format!("https://www.youtube.com/watch?v={}", self.id.0)
144 }
145
146 pub fn posters(&self) -> Vec<String> {
151 ["maxresdefault", "mqdefault"].map(|picture| format!("https://i.ytimg.com/vi/{}/{picture}.jpg", self.id.0)).into()
152 }
153
154 pub fn about(&self) -> String {
157 format!("https://www.youtube.com/oembed?format=json&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D{}", self.id.0)
160 }
161}
162
163pub fn video(url: &Url) -> Option<Video> {
168 if url.scheme() != "https" {
169 return None;
170 }
171 let host = url.host_str()?;
172 let host = ["www.", "m.", "music."].iter().find_map(|prefix| host.strip_prefix(prefix)).unwrap_or(host);
173 let mut path = url.path_segments()?;
174 let (first, second) = (path.next().unwrap_or_default(), path.next());
175 let (id, short) = match (host, first, second) {
176 ("youtu.be", id, None) => (id.to_string(), false),
177 ("youtube.com", "watch", None) => (url.query_pairs().find(|(name, _)| name == "v")?.1.into_owned(), false),
178 ("youtube.com", "shorts", Some(id)) => (id.to_string(), true),
179 ("youtube.com", "live" | "embed" | "v", Some(id)) | ("youtube-nocookie.com", "embed", Some(id)) => {
180 (id.to_string(), false)
181 }
182 _ => return None,
183 };
184 Some(Video { id: VideoId::parse(&id)?, size: short.then_some(SHORT_SIZE) })
185}
186
187pub fn video_at(url: &str) -> Option<Video> {
190 video(&Url::parse(url).ok()?)
191}
192
193pub fn title(answer: &[u8]) -> Option<String> {
196 let answer: serde_json::Value = serde_json::from_slice(answer).ok()?;
197 answer.get("title")?.as_str().map(str::to_string)
198}
199
200#[derive(Debug, Clone, PartialEq, Eq)]
202pub enum FindError {
203 NotInstalled,
205 TimedOut,
207 NoRuntime,
212 Failed(String),
214}
215
216fn said_wrong(errors: &str) -> FindError {
222 let lines = || errors.lines().map(str::trim).filter(|line| !line.is_empty());
223 let unprepared = |line: &str| line.starts_with("WARNING:") && (line.contains("JavaScript runtime") || line.contains("[jsc]"));
224 if lines().any(unprepared) {
225 return FindError::NoRuntime;
226 }
227 let marked = lines().rev().find_map(|line| line.strip_prefix("ERROR:"));
228 FindError::Failed(marked.or_else(|| lines().next_back()).unwrap_or("it said nothing").trim().to_string())
229}
230
231fn found(output: &str) -> Option<String> {
238 let lines = || output.lines().map(str::trim);
239 let https = |line: &&str| Url::parse(line).is_ok_and(|url| url.scheme() == "https");
240 if lines().any(|line| line == "sound=none") {
241 return lines().find_map(|line| line.strip_prefix("listed_in=")).filter(https).map(str::to_string);
242 }
243 lines().find(https).map(str::to_string)
244}
245
246fn wait_until_available(output: &str, now: u64) -> Duration {
251 let named = output.lines().find_map(|line| line.trim().strip_prefix("available_at=")?.parse::<u64>().ok());
252 Duration::from_secs(named.map_or(0, |at| at.saturating_sub(now))).min(AVAILABLE_WAIT_MAX)
253}
254
255pub async fn find_stream(video: Video) -> Result<String, FindError> {
259 let mut ytdlp = tokio::process::Command::new("yt-dlp");
260 ytdlp
261 .args(["--no-playlist", "--format", FORMAT])
262 .args(["--print", AVAILABLE_AT, "--print", SOUND, "--print", LISTED_IN, "--print", "urls", "--"])
263 .arg(video.page())
264 .stdin(Stdio::null())
265 .stdout(Stdio::piped())
266 .stderr(Stdio::piped())
267 .kill_on_drop(true);
269 let answer = match tokio::time::timeout(FIND_TIMEOUT, ytdlp.output()).await {
270 Err(_) => return Err(FindError::TimedOut),
271 Ok(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => return Err(FindError::NotInstalled),
272 Ok(Err(e)) => return Err(FindError::Failed(e.to_string())),
273 Ok(Ok(answer)) => answer,
274 };
275 if !answer.status.success() {
276 let errors = String::from_utf8_lossy(&answer.stderr);
277 tracing::debug!("yt-dlp failed, saying: {errors}");
278 return Err(said_wrong(&errors));
279 }
280 let output = String::from_utf8_lossy(&answer.stdout);
281 let stream = found(&output).ok_or_else(|| FindError::Failed("it named no stream".to_string()))?;
282 tokio::time::sleep(wait_until_available(&output, unix_now())).await;
283 Ok(stream)
284}
285
286#[cfg(test)]
287mod tests {
288 use super::{AVAILABLE_WAIT_MAX, FindError, Video, VideoId, found, said_wrong, title, video_at, wait_until_available};
289 use std::time::Duration;
290
291 fn id_at(url: &str) -> Option<String> {
292 video_at(url).map(|video| video.id.0)
293 }
294
295 #[test]
296 fn a_youtube_video_is_known_by_its_id_however_its_link_is_written() {
297 for link in [
298 "https://www.youtube.com/watch?v=aqz-KE-bpKQ",
299 "https://youtube.com/watch?v=aqz-KE-bpKQ&t=42s",
300 "https://m.youtube.com/watch?feature=share&v=aqz-KE-bpKQ",
301 "https://music.youtube.com/watch?v=aqz-KE-bpKQ&list=PL123",
302 "https://youtu.be/aqz-KE-bpKQ",
303 "https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt",
304 "https://www.youtube.com/shorts/aqz-KE-bpKQ",
305 "https://www.youtube.com/live/aqz-KE-bpKQ?feature=shared",
306 "https://www.youtube.com/embed/aqz-KE-bpKQ",
307 "https://www.youtube-nocookie.com/embed/aqz-KE-bpKQ",
308 "https://www.youtube.com/v/aqz-KE-bpKQ",
309 ] {
310 assert_eq!(id_at(link).as_deref(), Some("aqz-KE-bpKQ"), "{link}");
311 }
312
313 assert_eq!(video_at("https://www.youtube.com/shorts/aqz-KE-bpKQ").unwrap().size, Some((1080, 1920)));
315 assert_eq!(video_at("https://youtu.be/aqz-KE-bpKQ").unwrap().size, None);
316 }
317
318 #[test]
319 fn what_is_not_a_video_is_not_one() {
320 for link in [
321 "https://www.youtube.com/",
322 "https://www.youtube.com/@BlenderOfficial",
323 "https://www.youtube.com/playlist?list=PL6B3937A5D230E335",
324 "https://www.youtube.com/results?search_query=bunny",
325 "https://www.youtube.com/watch",
326 "https://www.youtube.com/watch?list=PL6B3937A5D230E335",
327 "https://www.youtube.com/embed/videoseries?list=PL6B3937A5D230E335",
328 "https://www.youtube.com/channel/UCSMOQeBJ2RAnuFungnQOxLg",
329 "https://youtu.be/",
330 "https://youtu.be/aqz-KE-bpKQ/more",
331 "https://example.com/watch?v=aqz-KE-bpKQ",
333 "https://youtube.com.example.com/watch?v=aqz-KE-bpKQ",
334 "https://notyoutu.be/aqz-KE-bpKQ",
335 "http://www.youtube.com/watch?v=aqz-KE-bpKQ",
337 "not an address",
338 ] {
339 assert_eq!(id_at(link), None, "{link}");
340 }
341 }
342
343 #[test]
344 fn only_what_is_shaped_like_an_id_is_one() {
345 assert!(VideoId::parse("aqz-KE-bpKQ").is_some());
346 assert!(VideoId::parse("_-_-_-_-_-_").is_some());
347 for not in [
348 "",
349 "short",
350 "twelve-chars",
351 "aqz-KE-bpK",
352 "aqz KE bpKQ",
353 "aqz-KE-bpK;",
354 "--exec=boom",
355 "aqz-KE-bpK\n",
356 "ééééééééééé",
357 ] {
358 assert!(VideoId::parse(not).is_none(), "{not:?}");
359 }
360 let shared = video_at("https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt&t=1%20--exec%20boom").unwrap();
362 assert_eq!(shared.page(), "https://www.youtube.com/watch?v=aqz-KE-bpKQ");
363 assert_eq!(
364 shared.about(),
365 "https://www.youtube.com/oembed?format=json&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Daqz-KE-bpKQ"
366 );
367 }
368
369 #[test]
370 fn a_video_has_two_pictures_to_stand_for_it_the_better_first() {
371 let video = Video { id: VideoId::parse("aqz-KE-bpKQ").unwrap(), size: None };
372 assert_eq!(
373 video.posters(),
374 ["https://i.ytimg.com/vi/aqz-KE-bpKQ/maxresdefault.jpg", "https://i.ytimg.com/vi/aqz-KE-bpKQ/mqdefault.jpg"]
375 );
376 }
377
378 #[test]
379 fn youtube_says_what_a_video_is_called() {
380 let answer = br#"{"title":"Big Buck Bunny 60fps 4K","author_name":"Blender","type":"video","thumbnail_url":"https://i.ytimg.com/vi/aqz-KE-bpKQ/hqdefault.jpg"}"#;
381 assert_eq!(title(answer).as_deref(), Some("Big Buck Bunny 60fps 4K"));
382 assert_eq!(title(b"Bad Request"), None);
383 assert_eq!(title(br#"{"title":7}"#), None);
384 assert_eq!(title(b"{}"), None);
385 }
386
387 #[test]
388 fn a_stream_is_waited_for_until_youtube_says_it_is_good() {
389 let wrote = |available: &str| format!("available_at={available}\nhttps://rr2.googlevideo.com/videoplayback?expire=1\n");
390 let now = 1_795_041_533;
391 assert_eq!(wait_until_available(&wrote("1795041538"), now), Duration::from_secs(5));
392 assert_eq!(wait_until_available(&wrote("1795041533"), now), Duration::ZERO);
394 assert_eq!(wait_until_available(&wrote("1795041000"), now), Duration::ZERO);
395 assert_eq!(wait_until_available(&wrote("NA"), now), Duration::ZERO);
396 assert_eq!(wait_until_available("https://rr2.googlevideo.com/videoplayback\n", now), Duration::ZERO);
397 assert_eq!(wait_until_available(&wrote("1795045133"), now), AVAILABLE_WAIT_MAX);
399 assert_eq!(found(&wrote("1795041538")).as_deref(), Some("https://rr2.googlevideo.com/videoplayback?expire=1"));
401 }
402
403 #[test]
404 fn what_yt_dlp_writes_is_read_for_a_stream_or_for_what_went_wrong() {
405 let stream = "https://rr2---sn-nx57ynsk.googlevideo.com/videoplayback?expire=1795058366&id=o-ACD";
406 assert_eq!(found(&format!("{stream}\n")).as_deref(), Some(stream));
407 assert_eq!(found(&format!("Big Buck Bunny\n {stream} \nhttps://second.example.com/\n")).as_deref(), Some(stream));
409 assert_eq!(found(""), None);
410 assert_eq!(found("NA\nhttp://plain.example.com/video\n"), None, "only https is played");
411
412 let pictures = "https://manifest.googlevideo.com/api/manifest/hls_playlist/itag/311/playlist/index.m3u8";
415 let playlist = "https://manifest.googlevideo.com/api/manifest/hls_variant/id/TNHAtXvAbEo.1/file/index.m3u8";
416 let live = |sound: &str, listed_in: &str| format!("available_at=NA\nsound={sound}\nlisted_in={listed_in}\n{pictures}\n");
417 assert_eq!(found(&live("none", playlist)).as_deref(), Some(playlist));
418 assert_eq!(found(&live("mp4a.40.2", playlist)).as_deref(), Some(pictures));
420 assert_eq!(found(&live("NA", "NA")).as_deref(), Some(pictures));
421 assert_eq!(found(&live("none", "NA")), None);
423 assert_eq!(found(&live("none", "http://plain.example.com/index.m3u8")), None);
424
425 let failed = |why: &str| FindError::Failed(why.to_string());
426 let errors = "WARNING: Unknown codec iamf.001.001.Opus\n\
427 ERROR: [youtube] aqz-KE-bpKQ: Sign in to confirm you're not a bot.\n";
428 assert_eq!(said_wrong(errors), failed("[youtube] aqz-KE-bpKQ: Sign in to confirm you're not a bot."));
429 assert_eq!(said_wrong("Traceback (most recent call last):\n somewhere\nKeyError: 'n'\n"), failed("KeyError: 'n'"));
430 assert_eq!(said_wrong("\n"), failed("it said nothing"));
431
432 let none = "WARNING: [youtube] No supported JavaScript runtime could be found. Only deno is enabled by default\n\
436 ERROR: [youtube] aqz-KE-bpKQ: Requested format is not available. Use --list-formats\n";
437 assert_eq!(said_wrong(none), FindError::NoRuntime);
438 let unused = "WARNING: [youtube] [jsc] Remote component challenge solver script (node) was skipped.\n\
439 WARNING: [youtube] aqz-KE-bpKQ: n challenge solving failed: Some formats may be missing.\n\
440 ERROR: [youtube] aqz-KE-bpKQ: Requested format is not available.\n";
441 assert_eq!(said_wrong(unused), FindError::NoRuntime);
442 }
443}