Files
sorsfonalak/services/forum/src/links/youtube.rs
T

176 lines
6.3 KiB
Rust
Raw Normal View History

//! YouTube links: the video's id (and where to start) from the usual forms
//! of address, its title and channel from YouTube's oEmbed answer, and its
//! thumbnail cut to 16:9 and kept in our storage.
use std::io::Cursor;
use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::{ImageFormat, ImageReader};
use serde::Deserialize;
use super::FOLDER;
use crate::AppState;
pub const PROVIDER: &str = "youtube";
/// The stored thumbnail: 480×270.
const WIDTH: u32 = 480;
const HEIGHT: u32 = 270;
fn valid_id(id: &str) -> bool {
id.len() == 11 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}
/// "90", "90s", "1m30s", "1h2m3s" as seconds.
fn seconds(raw: &str) -> Option<u32> {
if let Ok(n) = raw.parse::<u32>() {
return Some(n);
}
let (mut total, mut number) = (0u32, String::new());
for c in raw.chars() {
match c {
'0'..='9' => number.push(c),
'h' | 'm' | 's' => {
let n: u32 = number.parse().ok()?;
total += n * match c {
'h' => 3600,
'm' => 60,
_ => 1,
};
number.clear();
}
_ => return None,
}
}
number.is_empty().then_some(total).filter(|t| *t > 0)
}
/// The video id and start (seconds) of a YouTube address: watch, shorts,
/// live, embed and youtu.be links, on www., m. and music. too.
pub fn video(url: &reqwest::Url) -> Option<(String, Option<u32>)> {
let host = url.host_str()?.to_ascii_lowercase();
let host = host.strip_prefix("www.").unwrap_or(&host);
let param = |name: &str| url.query_pairs().find(|(k, _)| k == name).map(|(_, v)| v.into_owned());
let mut segments = url.path_segments()?;
let id = match host {
"youtu.be" => segments.next().map(str::to_string),
"youtube.com" | "m.youtube.com" | "music.youtube.com" => match segments.next() {
Some("watch") => param("v"),
Some("shorts" | "live" | "embed") => segments.next().map(str::to_string),
_ => None,
},
_ => None,
}?;
if !valid_id(&id) {
return None;
}
let start = param("t").or_else(|| param("start")).as_deref().and_then(seconds);
Some((id, start))
}
/// YouTube's oEmbed answer (live streams come without title and channel).
#[derive(Deserialize)]
struct OEmbed {
#[serde(default)]
title: Option<String>,
#[serde(default)]
author_name: Option<String>,
}
/// The card's title when YouTube gives none.
const NO_TITLE: &str = "YouTube-videó";
/// The video's title and channel, and its thumbnail into the storage.
pub async fn fetch(state: &AppState, id: &str) -> anyhow::Result<()> {
let links = &state.links;
let watch = format!("https://www.youtube.com/watch?v={id}");
let answer = links
.http
.get(&links.youtube_oembed)
.query(&[("url", watch.as_str()), ("format", "json")])
.send()
.await?
.error_for_status()?
.text()
.await?;
let meta: OEmbed = serde_json::from_str(&answer).map_err(|e| {
anyhow::anyhow!("oEmbed answer not understood ({e}): {}", answer.chars().take(160).collect::<String>())
})?;
// Without a thumbnail the card still shows (title and play button).
let thumbnail = match &state.storage {
Some(storage) => match store_thumbnail(state, storage, id).await {
Ok(file) => Some(file),
Err(e) => {
tracing::warn!(key = id, error = %e, "no thumbnail for a YouTube link");
None
}
},
None => None,
};
let title: String = meta.title.filter(|t| !t.trim().is_empty()).unwrap_or_else(|| NO_TITLE.into());
let title: String = title.chars().take(200).collect();
let author = meta.author_name.map(|a| a.chars().take(100).collect::<String>());
sqlx::query(
"INSERT INTO forum.link_previews (provider, key, title, author, thumbnail) VALUES ($1, $2, $3, $4, $5) \
ON CONFLICT (provider, key) DO UPDATE SET title = EXCLUDED.title, author = EXCLUDED.author, \
thumbnail = COALESCE(EXCLUDED.thumbnail, forum.link_previews.thumbnail), fetched_at = now()",
)
.bind(PROVIDER)
.bind(id)
.bind(&title)
.bind(&author)
.bind(&thumbnail)
.execute(&state.db)
.await?;
Ok(())
}
async fn store_thumbnail(state: &AppState, storage: &object_storage::Storage, id: &str) -> anyhow::Result<String> {
let bytes = state
.links
.http
.get(format!("{}/vi/{id}/hqdefault.jpg", state.links.youtube_thumbs))
.send()
.await?
.error_for_status()?
.bytes()
.await?;
let jpeg = widescreen(&bytes)?;
let file = format!("{PROVIDER}-{id}.jpg");
storage.put(&format!("{FOLDER}/{file}"), jpeg, "image/jpeg").await?;
Ok(file)
}
/// YouTube's 4:3 thumbnail (with black bands) as a 16:9 JPEG.
fn widescreen(bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
let img = ImageReader::with_format(Cursor::new(bytes), ImageFormat::Jpeg).decode()?;
let (w, h) = (img.width(), img.height());
let band_h = (w * 9 / 16).min(h);
let cropped = img.crop_imm(0, (h - band_h) / 2, w, band_h);
let small = cropped.resize_exact(WIDTH, HEIGHT, FilterType::Triangle).to_rgb8();
let mut out = Vec::new();
JpegEncoder::new_with_quality(&mut out, 82).encode_image(&small)?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_youtube_addresses() {
let id = |s: &str| video(&reqwest::Url::parse(s).unwrap());
assert_eq!(id("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
assert_eq!(
id("https://m.youtube.com/watch?feature=share&v=dQw4w9WgXcQ&t=42"),
Some(("dQw4w9WgXcQ".into(), Some(42)))
);
assert_eq!(id("https://youtu.be/dQw4w9WgXcQ?t=1h2m3s"), Some(("dQw4w9WgXcQ".into(), Some(3723))));
assert_eq!(id("https://youtube.com/shorts/dQw4w9WgXcQ"), Some(("dQw4w9WgXcQ".into(), None)));
assert_eq!(id("https://music.youtube.com/watch?v=dQw4w9WgXcQ&list=x"), Some(("dQw4w9WgXcQ".into(), None)));
assert_eq!(id("https://www.youtube.com/@csatorna"), None);
assert_eq!(id("https://www.youtube.com/watch?v=rovid"), None);
assert_eq!(id("https://notyoutube.com/watch?v=dQw4w9WgXcQ"), None);
}
}