From 867a29492f65ac76f46e32469b6e47d830cdacaf Mon Sep 17 00:00:00 2001 From: astar76 Date: Sat, 24 Oct 2026 16:49:52 -0500 Subject: [PATCH] /convert: output required, latest chat media by default, streamed input, oversize results hosted for 6h Co-Authored-By: Claude Sonnet 5.5 --- src/commands/media/convert.rs | 140 ++++++++++++++++----- src/commands/media/ffmpeg.rs | 226 +++++++++++++++++++++++++--------- src/commands/media/images.rs | 38 +++--- src/hosted.rs | 102 +++++++++++++++ src/main.rs | 2 + src/web/mod.rs | 20 +++ 6 files changed, 426 insertions(+), 102 deletions(-) create mode 100644 src/hosted.rs diff --git a/src/commands/media/convert.rs b/src/commands/media/convert.rs index 0cfab23..97b0487 100644 --- a/src/commands/media/convert.rs +++ b/src/commands/media/convert.rs @@ -2,14 +2,16 @@ //! //! `/convert file: output:gif quality:720p` — attach a file, then pick the **output**: as you type, the list shows //! only what *that* file can become (a picture or GIF → other picture formats or a clip; a video → a clip, a GIF, a -//! picture or just its sound; a sound → other sound formats). Leave `output` out for a sensible default (pictures → -//! PNG, GIFs and videos → MP4, sound → MP3). **Quality** is optional: *adaptive* (the best that fits Discord's upload +//! picture or just its sound; a sound → other sound formats). With no file, link or @user it converts the latest picture, +//! video or sound posted in the channel. Videos and sounds are read from their address while they are converted (no +//! waiting for a full download first), and a result too big for Discord is kept for a few hours on the bot's website. +//! **Quality** is optional: *adaptive* (the best that fits Discord's upload //! limit), a height like `1080p` / `720p` / `900p` for pictures and video (smaller sources are upscaled with Lanczos //! and a little sharpening), or a bitrate like `192k` for audio. //! Text version: `D!convert mp3 128k` (reply to a file, attach one, or add a link / @user). -use super::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, HEIGHTS, KBPS}; -use super::images::pick; -use super::{fetch_limited, has_ext, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, Source, HEIGHTS, KBPS}; +use super::images::pick_opt; +use super::{fetch_limited, has_ext, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::state::State; @@ -19,7 +21,10 @@ use futures::FutureExt; use std::collections::HashMap; use std::sync::Arc; -const MAX_MEDIA_BYTES: usize = 40 * 1024 * 1024; +/// Pictures are downloaded first (they are small); video and sound are read from the web while they are converted. +const MAX_PICTURE_BYTES: usize = 40 * 1024 * 1024; +/// The biggest video / sound we will work on. +const MAX_STREAM_BYTES: u64 = 1024 * 1024 * 1024; fn height_label(h: u32) -> &'static str { match h { @@ -128,6 +133,67 @@ fn take(rest: &mut String) -> Option { Some(w) } +/// The newest picture, video or sound posted in this channel (what `/convert` uses when you give it nothing). +async fn last_chat_media(ctx: &Ctx) -> Option { + let messages = ctx.state.http.channel_messages(ctx.channel_id).limit(30).await.ok()?.models().await.ok()?; + for m in messages.iter().filter(|m| Some(m.id) != ctx.command_message_id()) { + for a in &m.attachments { + if kind_from(a.content_type.as_deref(), &a.filename).is_some() { + return Some(a.url.clone()); + } + } + for e in &m.embeds { + if let Some(v) = e.video.as_ref().and_then(|v| v.url.clone()) { + return Some(v); + } + if let Some(i) = e.image.as_ref().map(|i| i.url.clone()).or_else(|| e.thumbnail.as_ref().map(|t| t.url.clone())) { + return Some(i); + } + } + } + None +} + +/// The first few KB of a file and its total size, without downloading the rest. +async fn fetch_head(state: &State, url: &str) -> Option<(Vec, Option)> { + let url = safe_url(url)?; + let mut r = state.web.get(url).header(reqwest::header::RANGE, "bytes=0-65535").send().await.ok()?; + if !r.status().is_success() { + return None; + } + let total = r + .headers() + .get(reqwest::header::CONTENT_RANGE) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.rsplit('/').next()?.parse::().ok()) + .or_else(|| r.content_length()); + let mut head = Vec::new(); + while head.len() < 65536 { + match r.chunk().await.ok()? { + Some(c) => head.extend_from_slice(&c), + None => break, + } + } + head.truncate(65536); + Some((head, total)) +} + +/// Pictures come down whole (they're small); anything else is read from its address while ffmpeg works. +async fn open_source(state: &State, url: &str) -> Result { + if safe_url(url).is_none() { + bail_user!("That doesn't look like a public link."); + } + let Some((head, total)) = fetch_head(state, url).await else { bail_user!("I couldn't reach that file.") }; + if image::guess_format(&head).is_ok() { + let Some(bytes) = fetch_limited(state, url, MAX_PICTURE_BYTES).await else { bail_user!("I couldn't download that picture ({} MB max).", MAX_PICTURE_BYTES / 1024 / 1024) }; + return Ok(Source::Bytes(bytes)); + } + if total.is_some_and(|t| t > MAX_STREAM_BYTES) { + bail_user!("That file is too big to convert ({} MB max).", MAX_STREAM_BYTES / 1024 / 1024); + } + Ok(Source::Url { url: url.trim_matches(|c| c == '<' || c == '>').to_string(), head }) +} + async fn convert_cmd(ctx: Arc) -> Result<()> { let a = &ctx.args; let mut output = a.str("output").unwrap_or("").to_string(); @@ -160,36 +226,48 @@ async fn convert_cmd(ctx: Arc) -> Result<()> { None => bail_user!("`{}` isn't a quality. Use `adaptive`, a height like `720p` (pictures and video) or a bitrate like `128k` (audio).", escape(&truncate(&quality_text, 20))), } }; - let (url, _) = pick(&ctx, &rest).await?; + if wanted.is_none() { + bail_user!("Convert to what? Pick an `output` — audio: {} · video: {} · image: {}.", format_list(MediaType::Audio), format_list(MediaType::Video), format_list(MediaType::Image)); + } + // the attached file, a link or @user — or else the newest media posted in this channel + let url = match pick_opt(&ctx, &rest).await? { + Some((u, _)) => u, + None => match last_chat_media(&ctx).await { + Some(u) => u, + None => bail_user!("Attach a file, give a link, or post a picture, video or sound in this channel first — I convert the latest one."), + }, + }; let limit = upload_limit(&ctx); ctx.defer().await?; - let Some(data) = fetch_limited(&ctx.state, &url, MAX_MEDIA_BYTES).await else { - bail_user!("I couldn't download that ({} MB max).", MAX_MEDIA_BYTES / 1024 / 1024); - }; - let Some((kind, animated)) = ffmpeg::detect(&data).await else { bail_user!("I can't read that file as a picture, video or sound.") }; - let fmt = match wanted { - Some(f) => { - if !ffmpeg::outputs_for(kind).iter().any(|o| o.name == f.name) { - bail_user!("That file is a {} — it can't become **{}**. It can become: {}.", kind.name(), f.name.to_uppercase(), format_list(kind)); - } - f - } - None => { - let name = match (kind, animated) { - (MediaType::Image, false) => "png", - (MediaType::Audio, _) => "mp3", - _ => "mp4", - }; - find_format(name, None).expect("default format exists") - } - }; + let source = open_source(&ctx.state, &url).await?; + let Some((kind, animated)) = ffmpeg::detect(&source).await else { bail_user!("I can't read that file as a picture, video or sound.") }; + let fmt = wanted.expect("checked above"); + if !ffmpeg::outputs_for(kind).iter().any(|o| o.name == fmt.name) { + bail_user!("That file is a {} — it can't become **{}**. It can become: {}.", kind.name(), fmt.name.to_uppercase(), format_list(kind)); + } + let _ = animated; let started = std::time::Instant::now(); - let Converted { bytes, ext, note } = match ffmpeg::convert_to(&data, fmt, quality, limit).await { + let Converted { bytes, ext, note, size, hosted } = match ffmpeg::convert_to(&source, fmt, quality, limit).await { Ok(c) => c, Err(e) => bail_user!("I couldn't convert that to **{}**: {}", fmt.name.to_uppercase(), escape(&truncate(&e, 200))), }; + let took = started.elapsed().as_secs_f32(); + if let Some(link) = hosted { + let summary = format!("✅ Converted to **{}** · {} · {}\n📦 That's over Discord's {} limit, so it's kept for **{} hours** — open it in your browser or download it.", fmt.name.to_uppercase(), note, mb(size), mb(limit), crate::hosted::TTL.as_secs() / 3600); + let button = twilight_model::channel::message::component::Button { + id: None, + custom_id: None, + disabled: false, + emoji: Some(twilight_model::channel::message::EmojiReactionType::Unicode { name: "⬇️".into() }), + label: Some("Open / download".into()), + style: twilight_model::channel::message::component::ButtonStyle::Link, + url: Some(link), + sku_id: None, + }; + return ctx.reply(Card::new(None).text(&summary).row(vec![button]).build()).await; + } let name = format!("converted.{ext}"); - let summary = format!("✅ Converted to **{}** · {} · {} · {:.1}s", fmt.name.to_uppercase(), note, mb(bytes.len()), started.elapsed().as_secs_f32()); + let summary = format!("✅ Converted to **{}** · {} · {} · {:.1}s", fmt.name.to_uppercase(), note, mb(size), took); let shows = matches!(ext, "png" | "jpg" | "webp" | "gif" | "mp4" | "webm" | "mov"); let card = if shows { Card::new(None).text(&summary).gallery(&[&format!("attachment://{name}")]) } else { Card::new(None).text(&summary).push(file_display(&name)) }; ctx.reply_file(card.build(), &name, bytes).await @@ -199,8 +277,8 @@ pub fn commands() -> Vec { vec![Command::new("convert", "fun", "Convert any picture, video or audio to another format — the output list adapts to your file", |c| convert_cmd(c).boxed()) .aliases(&["conv"]) .usage("[output] [quality] [link | @user] (reply to or attach a file)") - .opt(Opt::opt("file", "The picture, GIF, video or audio to convert", OptKind::Attachment).slash_only()) - .opt(Opt::opt("output", "What to make — the list shows what your file can become (default: PNG, MP4 or MP3)", OptKind::String).autocomplete().slash_only()) + .opt(Opt::req("output", "What to make — the list shows what your file can become", OptKind::String).autocomplete().slash_only()) + .opt(Opt::opt("file", "The picture, GIF, video or audio to convert (default: the latest one in this channel)", OptKind::Attachment).slash_only()) .opt(Opt::opt("quality", "Adaptive, a height (1080p, 720p…) or an audio bitrate (320k, 128k…)", OptKind::String).autocomplete().slash_only()) .opt(Opt::opt("rest", "Output, quality, then a link or @user (or attach / reply)", OptKind::String).prefix_only()) .opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only()) diff --git a/src/commands/media/ffmpeg.rs b/src/commands/media/ffmpeg.rs index 1457dfd..c6d66c6 100644 --- a/src/commands/media/ffmpeg.rs +++ b/src/commands/media/ffmpeg.rs @@ -152,15 +152,41 @@ pub fn formats_for(ty: MediaType) -> Vec<&'static Format> { FORMATS.iter().filter(|f| f.ty == ty).collect() } +/// Where the file comes from: bytes we already have, or a web address ffmpeg reads from while it works (so a long video +/// is converted as it arrives instead of being downloaded first). `head` is the first few KB, for telling pictures apart. +pub enum Source { + Bytes(Vec), + Url { url: String, head: Vec }, +} + +impl Source { + fn head(&self) -> &[u8] { + match self { + Source::Bytes(b) => &b[..b.len().min(65536)], + Source::Url { head, .. } => head, + } + } +} + +/// Reading from the web: only http(s), and reconnect when the connection drops. +const NET_ARGS: [&str; 8] = ["-protocol_whitelist", "http,https,tcp,tls,crypto", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5"]; + /// What a file really is: its kind, and whether a picture is animated (a GIF or animated WebP). -pub async fn detect(bytes: &[u8]) -> Option<(MediaType, bool)> { +pub async fn detect(source: &Source) -> Option<(MediaType, bool)> { let scratch = Scratch::new().ok()?; - let src = scratch.path("probe.bin"); - std::fs::write(&src, bytes).ok()?; - let info = inspect(&src, bytes).await; - let picture = image::guess_format(bytes).is_ok(); + let target = match source { + Source::Bytes(b) => { + let p = scratch.path("probe.bin"); + std::fs::write(&p, b).ok()?; + p.display().to_string() + } + Source::Url { url, .. } => url.clone(), + }; + let head = source.head(); + let info = inspect(&target, head, matches!(source, Source::Url { .. })).await; + let picture = image::guess_format(head).is_ok(); if info.video || picture { - let animated = picture && kind_of(bytes) == Kind::Moving; + let animated = picture && kind_of(head) == Kind::Moving; Some(if picture { (Image, animated) } else { (Video, false) }) } else if info.audio { Some((Audio, false)) @@ -234,9 +260,13 @@ pub fn parse_quality(text: &str) -> Option { } pub struct Converted { + /// the file (empty when it was too big for Discord and is hosted instead) pub bytes: Vec, pub ext: &'static str, pub note: String, + pub size: usize, + /// public link, when the result didn't fit Discord's upload limit (see hosted.rs) + pub hosted: Option, } struct Info { @@ -248,14 +278,13 @@ struct Info { still: bool, } -async fn inspect(path: &Path, bytes: &[u8]) -> Info { - let out = Command::new("ffprobe") - .args(["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "default=nw=1"]) - .arg(path) - .stdin(Stdio::null()) - .output() - .await - .ok(); +async fn inspect(target: &str, head: &[u8], online: bool) -> Info { + let mut cmd = Command::new("ffprobe"); + cmd.args(["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "default=nw=1"]); + if online { + cmd.args(["-protocol_whitelist", "http,https,tcp,tls,crypto"]); + } + let out = tokio::time::timeout(Duration::from_secs(60), cmd.arg(target).stdin(Stdio::null()).output()).await.ok().and_then(|r| r.ok()); let text = out.map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); let num = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.parse::().ok()).unwrap_or(0.0); Info { @@ -264,7 +293,7 @@ async fn inspect(path: &Path, bytes: &[u8]) -> Info { height: num("height=") as u32, video: text.contains("codec_type=video"), audio: text.contains("codec_type=audio"), - still: kind_of(bytes) == Kind::Still, + still: kind_of(head) == Kind::Still, } } @@ -474,13 +503,26 @@ fn image_attempts(fmt: &Format, q: Quality, info: &Info) -> Vec { out } -/// Convert `input` to the chosen format and quality. Tries smaller settings until it fits `limit`. -pub async fn convert_to(input: &[u8], fmt: &Format, quality: Quality, limit: usize) -> Result { +/// Convert `input` to the chosen format and quality. An explicit quality is honoured as asked; if the result is too +/// big for Discord it is hosted for a few hours instead (hosted.rs). "Adaptive" tries smaller settings until it fits +/// Discord, and hosts the best version only if nothing fits. +pub async fn convert_to(input: &Source, fmt: &Format, quality: Quality, limit: usize) -> Result { let scratch = Scratch::new().map_err(|e| e.to_string())?; - let src = scratch.path("input.bin"); - std::fs::write(&src, input).map_err(|e| e.to_string())?; + let (input_args, target, online): (Vec, String, bool) = match input { + Source::Bytes(b) => { + let src = scratch.path("input.bin"); + std::fs::write(&src, b).map_err(|e| e.to_string())?; + (vec![s("-i"), src.display().to_string()], src.display().to_string(), false) + } + Source::Url { url, .. } => { + let mut a: Vec = NET_ARGS.iter().map(|x| x.to_string()).collect(); + a.extend([s("-i"), url.clone()]); + (a, url.clone(), true) + } + }; let out = scratch.path(&format!("out.{}", fmt.ext)); - let info = inspect(&src, input).await; + let big = scratch.path(&format!("big.{}", fmt.ext)); + let info = inspect(&target, input.head(), online).await; match fmt.ty { Audio if !info.audio => return Err("that file has no sound to make audio from".into()), Video if !info.video => return Err("that file has no picture to make a video from".into()), @@ -493,20 +535,23 @@ pub async fn convert_to(input: &[u8], fmt: &Format, quality: Quality, limit: usi if matches!(quality, Quality::Height(_)) && fmt.ty == Audio { return Err("a height only applies to pictures and video — pick adaptive or a bitrate like 128k".into()); } - let attempts = match fmt.ty { + let mut attempts = match fmt.ty { Audio => audio_attempts(fmt, quality, &info, limit), - Video if fmt.name == "gif" => gif_attempts(quality, &info), Image if fmt.name == "gif" => gif_attempts(quality, &info), Video => video_attempts(fmt, quality, &info), Image => image_attempts(fmt, quality, &info), }; + if quality != Quality::Adaptive { + attempts.truncate(1); // what you asked for, not a smaller guess + } let mut last_error = String::new(); - for attempt in attempts { + let mut kept: Option<(String, usize)> = None; + for (n, attempt) in attempts.into_iter().enumerate() { let mut args: Vec = Vec::new(); - if info.still && fmt.ty == Video && fmt.name != "gif" { + if info.still && fmt.ty == Video { args.extend([s("-loop"), s("1")]); } - args.extend([s("-i"), src.display().to_string()]); + args.extend(input_args.clone()); args.extend(attempt.args); // extensions ffmpeg can't guess a container from match fmt.ext { @@ -517,21 +562,32 @@ pub async fn convert_to(input: &[u8], fmt: &Format, quality: Quality, limit: usi } args.push(out.display().to_string()); let _ = std::fs::remove_file(&out); - match run(&args, Duration::from_secs(240)).await { + match run(&args, Duration::from_secs(900)).await { Ok(()) => { let size = std::fs::metadata(&out).map(|m| m.len() as usize).unwrap_or(0); if size == 0 { last_error = "ffmpeg made an empty file".to_string(); } else if size <= limit { let bytes = std::fs::read(&out).map_err(|e| e.to_string())?; - return Ok(Converted { bytes, ext: fmt.ext, note: attempt.note }); + return Ok(Converted { size, bytes, ext: fmt.ext, note: attempt.note, hosted: None }); } else { - last_error = format!("the result is too big for Discord ({} MB) — try a lower quality", size / 1024 / 1024); + last_error = format!("the result is too big for Discord ({} MB)", size / 1024 / 1024); + if n == 0 && std::fs::rename(&out, &big).is_ok() { + kept = Some((attempt.note.clone(), size)); + } } } Err(e) => last_error = e, } } + // nothing fits Discord: host the best version for a few hours + if let Some((note, size)) = kept { + if size as u64 > crate::hosted::MAX_FILE { + return Err(format!("the result is huge ({} MB) — pick a lower quality", size / 1024 / 1024)); + } + let url = crate::hosted::store(&big, &format!("converted.{}", fmt.ext)).map_err(|e| format!("couldn't keep the file for download ({e})"))?; + return Ok(Converted { bytes: Vec::new(), ext: fmt.ext, note, size, hosted: Some(url) }); + } Err(last_error) } @@ -570,7 +626,7 @@ mod tests { async fn height_of(bytes: &[u8], scratch: &Scratch, ext: &str) -> u32 { let p = scratch.path(&format!("check.{ext}")); std::fs::write(&p, bytes).unwrap(); - inspect(&p, bytes).await.height + inspect(&p.display().to_string(), bytes, false).await.height } fn fmt(name: &str, ty: MediaType) -> &'static Format { @@ -617,11 +673,11 @@ mod tests { let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; for f in formats_for(Audio) { - let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); + let out = convert_to(&Source::Bytes(video.clone()), f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); assert!(out.bytes.len() > 200 && out.ext == f.ext, "{}", f.name); } - let low = convert_to(&video, fmt("mp3", Audio), Quality::Kbps(32), 20 << 20).await.unwrap(); - let high = convert_to(&video, fmt("mp3", Audio), Quality::Kbps(320), 20 << 20).await.unwrap(); + let low = convert_to(&Source::Bytes(video.clone()), fmt("mp3", Audio), Quality::Kbps(32), 20 << 20).await.unwrap(); + let high = convert_to(&Source::Bytes(video.clone()), fmt("mp3", Audio), Quality::Kbps(320), 20 << 20).await.unwrap(); assert!(high.bytes.len() > low.bytes.len() * 3, "{} vs {}", high.bytes.len(), low.bytes.len()); assert!(high.note.contains("320 kbps"), "{}", high.note); } @@ -634,12 +690,12 @@ mod tests { let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; for f in formats_for(Video) { - let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); + let out = convert_to(&Source::Bytes(video.clone()), f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); assert!(out.bytes.len() > 500 && out.ext == f.ext, "{}", f.name); } - let small = convert_to(&video, fmt("mp4", Video), Quality::Height(144), 20 << 20).await.unwrap(); + let small = convert_to(&Source::Bytes(video.clone()), fmt("mp4", Video), Quality::Height(144), 20 << 20).await.unwrap(); assert_eq!(height_of(&small.bytes, &scratch, "mp4").await, 144); - let up = convert_to(&video, fmt("mp4", Video), Quality::Height(720), 20 << 20).await.unwrap(); + let up = convert_to(&Source::Bytes(video.clone()), fmt("mp4", Video), Quality::Height(720), 20 << 20).await.unwrap(); assert_eq!(height_of(&up.bytes, &scratch, "mp4").await, 720, "a 240p source is upscaled to 720p"); } @@ -651,12 +707,12 @@ mod tests { let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; for f in formats_for(Image) { - let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); + let out = convert_to(&Source::Bytes(video.clone()), f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name)); assert!(out.bytes.len() > 100 && out.ext == f.ext, "{}", f.name); } - let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 20 << 20).await.unwrap(); + let png = convert_to(&Source::Bytes(video.clone()), fmt("png", Image), Quality::Adaptive, 20 << 20).await.unwrap(); assert_eq!(kind_of(&png.bytes), Kind::Still); - let big = convert_to(&png.bytes, fmt("jpg", Image), Quality::Height(900), 20 << 20).await.unwrap(); + let big = convert_to(&Source::Bytes(png.bytes.clone()), fmt("jpg", Image), Quality::Height(900), 20 << 20).await.unwrap(); assert_eq!(height_of(&big.bytes, &scratch, "jpg").await, 900); } @@ -667,18 +723,70 @@ mod tests { } let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; - let gif = convert_to(&video, fmt("gif", Image), Quality::Adaptive, 10 << 20).await.unwrap(); + let gif = convert_to(&Source::Bytes(video.clone()), fmt("gif", Image), Quality::Adaptive, 10 << 20).await.unwrap(); assert_eq!(kind_of(&gif.bytes), Kind::Moving); - let mp4 = convert_to(&gif.bytes, fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap(); + let mp4 = convert_to(&Source::Bytes(gif.bytes.clone()), fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap(); assert_eq!(&mp4.bytes[4..8], b"ftyp"); - let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); - let clip = convert_to(&png.bytes, fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap(); + let png = convert_to(&Source::Bytes(video.clone()), fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); + let clip = convert_to(&Source::Bytes(png.bytes.clone()), fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap(); let p = scratch.path("clip.mp4"); std::fs::write(&p, &clip.bytes).unwrap(); let (duration, has_video) = probe(&p).await.unwrap(); assert!(has_video && duration > 2.0 && duration < 4.5, "duration {duration}"); } + #[tokio::test] + async fn an_explicit_quality_is_not_traded_down_and_too_big_is_hosted() { + if !have_ffmpeg() { + return; + } + let scratch = Scratch::new().unwrap(); + let video = sample_video(&scratch).await; + let out = convert_to(&Source::Bytes(video.clone()), fmt("mp4", Video), Quality::Height(240), 500).await.unwrap(); + assert!(out.note.contains("240p") && !out.note.contains("adaptive") && out.hosted.is_some(), "{}", out.note); + let link = out.hosted.unwrap(); + let _ = std::fs::remove_dir_all(crate::hosted::dir().join(link.rsplit('/').nth(1).unwrap())); + } + + /// The input is read from a web address while ffmpeg works (no full download first). + #[tokio::test] + async fn a_web_address_is_converted_as_it_is_read() { + if !have_ffmpeg() || std::process::Command::new("python3").arg("--version").output().is_err() { + return; + } + let scratch = Scratch::new().unwrap(); + let name = scratch.path("served.mp4"); + run(&[s("-f"), s("lavfi"), s("-i"), s("testsrc=size=320x240:rate=15"), s("-f"), s("lavfi"), s("-i"), s("sine=frequency=440"), s("-t"), s("2"), s("-pix_fmt"), s("yuv420p"), s("-movflags"), s("+faststart"), name.display().to_string()], Duration::from_secs(60)).await.unwrap(); + let port = 38000 + (std::process::id() % 2000); + let mut server = std::process::Command::new("python3") + .args(["-m", "http.server", &port.to_string(), "--bind", "127.0.0.1", "--directory"]) + .arg(scratch.path("")) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + for _ in 0..50 { + if std::net::TcpStream::connect(("127.0.0.1", port as u16)).is_ok() { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + let url = format!("http://127.0.0.1:{port}/served.mp4"); + let head = std::fs::read(&name).unwrap()[..2048].to_vec(); + let source = Source::Url { url, head }; + let result = async { + assert_eq!(detect(&source).await, Some((Video, false))); + let sound = convert_to(&source, fmt("mp3", Audio), Quality::Kbps(96), 20 << 20).await.unwrap(); + assert!(sound.bytes.len() > 500 && sound.note.contains("96 kbps")); + let gif = convert_to(&source, fmt("gif", Image), Quality::Adaptive, 20 << 20).await.unwrap(); + assert!(gif.bytes.starts_with(b"GIF8")); + } + .await; + let _ = server.kill(); + let _ = server.wait(); + result + } + #[tokio::test] async fn files_are_recognised_by_what_they_are() { if !have_ffmpeg() { @@ -686,14 +794,14 @@ mod tests { } let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; - assert_eq!(detect(&video).await, Some((Video, false))); - let gif = convert_to(&video, fmt("gif", Image), Quality::Adaptive, 10 << 20).await.unwrap(); - assert_eq!(detect(&gif.bytes).await, Some((Image, true))); - let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); - assert_eq!(detect(&png.bytes).await, Some((Image, false))); - let sound = convert_to(&video, fmt("mp3", Audio), Quality::Adaptive, 10 << 20).await.unwrap(); - assert_eq!(detect(&sound.bytes).await, Some((Audio, false))); - assert_eq!(detect(b"not media at all").await, None); + assert_eq!(detect(&Source::Bytes(video.clone())).await, Some((Video, false))); + let gif = convert_to(&Source::Bytes(video.clone()), fmt("gif", Image), Quality::Adaptive, 10 << 20).await.unwrap(); + assert_eq!(detect(&Source::Bytes(gif.bytes.clone())).await, Some((Image, true))); + let png = convert_to(&Source::Bytes(video.clone()), fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); + assert_eq!(detect(&Source::Bytes(png.bytes.clone())).await, Some((Image, false))); + let sound = convert_to(&Source::Bytes(video.clone()), fmt("mp3", Audio), Quality::Adaptive, 10 << 20).await.unwrap(); + assert_eq!(detect(&Source::Bytes(sound.bytes.clone())).await, Some((Audio, false))); + assert_eq!(detect(&Source::Bytes(b"not media at all".to_vec())).await, None); } #[tokio::test] @@ -703,12 +811,18 @@ mod tests { } let scratch = Scratch::new().unwrap(); let video = sample_video(&scratch).await; - let err = convert_to(&video, fmt("gif", Image), Quality::Adaptive, 100).await.err().unwrap(); - assert!(err.contains("too big"), "{err}"); - assert!(convert_to(&video, fmt("mp3", Audio), Quality::Height(720), 1 << 20).await.is_err()); - assert!(convert_to(&video, fmt("mp4", Video), Quality::Kbps(128), 1 << 20).await.is_err()); - let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); - let err = convert_to(&png.bytes, fmt("mp3", Audio), Quality::Adaptive, 1 << 20).await.err().unwrap(); + // nothing fits 100 bytes, so the best version is kept for download instead of being refused + let hosted = convert_to(&Source::Bytes(video.clone()), fmt("gif", Image), Quality::Adaptive, 100).await.unwrap(); + let link = hosted.hosted.clone().expect("hosted"); + assert!(hosted.bytes.is_empty() && hosted.size > 100 && link.contains("/f/"), "{link}"); + let token = link.rsplit('/').nth(1).unwrap().to_string(); + let stored = crate::hosted::dir().join(&token).join("converted.gif"); + assert_eq!(std::fs::metadata(&stored).map(|m| m.len() as usize).ok(), Some(hosted.size)); + let _ = std::fs::remove_dir_all(crate::hosted::dir().join(token)); + assert!(convert_to(&Source::Bytes(video.clone()), fmt("mp3", Audio), Quality::Height(720), 1 << 20).await.is_err()); + assert!(convert_to(&Source::Bytes(video.clone()), fmt("mp4", Video), Quality::Kbps(128), 1 << 20).await.is_err()); + let png = convert_to(&Source::Bytes(video.clone()), fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap(); + let err = convert_to(&Source::Bytes(png.bytes.clone()), fmt("mp3", Audio), Quality::Adaptive, 1 << 20).await.err().unwrap(); assert!(err.contains("no sound"), "{err}"); } } diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index f744861..dd04eb1 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -319,62 +319,70 @@ pub fn squish_gif(bytes: &[u8]) -> Option> { // ---- finding the picture ---------------------------------------------------------------------- /// Where the media for a command comes from, and the words left over. -pub(super) async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> { +pub(super) async fn pick_opt(ctx: &Ctx, text: &str) -> Result> { let state = &ctx.state; if ctx.is_slash() { if let Some(a) = ctx.args.id("file").or_else(|| ctx.args.id("image")).and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) { - return Ok((a.url.clone(), text.to_string())); + return Ok(Some((a.url.clone(), text.to_string()))); } if let Some(u) = ctx.args.user("user") { - return Ok((avatar(state, u, 512).await, text.to_string())); + return Ok(Some((avatar(state, u, 512).await, text.to_string()))); } if let Some(url) = ctx.args.str("url") { if safe_url(url).is_none() { bail_user!("That doesn't look like a public link."); } - return Ok((url.trim_matches(|c| c == '<' || c == '>').to_string(), text.to_string())); + return Ok(Some((url.trim_matches(|c| c == '<' || c == '>').to_string(), text.to_string()))); } - return Ok((avatar(state, ctx.user_id, 512).await, text.to_string())); + return Ok(None); } if let Some(a) = ctx.attachments.first() { - return Ok((a.url.clone(), text.to_string())); + return Ok(Some((a.url.clone(), text.to_string()))); } let reply = replied(ctx).await; if let Some(m) = &reply { if let Some(a) = m.attachments.iter().find(|a| has_ext(&a.filename, &IMAGE_EXTS) || has_ext(&a.filename, &VIDEO_EXTS) || has_ext(&a.filename, &AUDIO_EXTS)) { - return Ok((a.url.clone(), text.to_string())); + return Ok(Some((a.url.clone(), text.to_string()))); } for e in &m.embeds { if let Some(v) = e.video.as_ref().and_then(|v| v.url.clone()) { - return Ok((v, text.to_string())); + return Ok(Some((v, text.to_string()))); } if let Some(i) = e.image.as_ref().map(|i| i.url.clone()).or_else(|| e.thumbnail.as_ref().map(|t| t.url.clone())) { - return Ok((i, text.to_string())); + return Ok(Some((i, text.to_string()))); } } if let Some(s) = m.sticker_items.first() { - return Ok((format!("https://media.discordapp.net/stickers/{}.png?size=512", s.id), text.to_string())); + return Ok(Some((format!("https://media.discordapp.net/stickers/{}.png?size=512", s.id), text.to_string()))); } } let words: Vec<&str> = text.split_whitespace().collect(); for (i, word) in words.iter().enumerate() { let left = || words.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, w)| *w).collect::>().join(" "); if word.starts_with("http://") || word.starts_with("https://") || word.starts_with("').to_string(), left())); + return Ok(Some((word.trim_matches(|c| c == '<' || c == '>').to_string(), left()))); } if let Some((_, id, animated)) = custom_emojis(word).into_iter().next() { - return Ok((emoji_url(id, animated, 256), left())); + return Ok(Some((emoji_url(id, animated, 256), left()))); } // only mentions and IDs here, never caption words let is_mention = word.starts_with("<@") || (word.len() >= 15 && word.chars().all(|c| c.is_ascii_digit())); if let (true, Some(g)) = (is_mention, ctx.guild_id) { if let Some(u) = find_member(&state.cache, g, word) { - return Ok((avatar(state, u, 512).await, left())); + return Ok(Some((avatar(state, u, 512).await, left()))); } } } - let who = reply.as_ref().map_or(ctx.user_id, |m| m.author.id); - Ok((avatar(state, who, 512).await, text.to_string())) + Ok(None) +} + +/// Like [`pick_opt`], but with nothing given it uses an avatar (the replied-to person's, else yours). +pub(super) async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> { + if let Some(found) = pick_opt(ctx, text).await? { + return Ok(found); + } + let who = if ctx.is_slash() { ctx.user_id } else { replied(ctx).await.map_or(ctx.user_id, |m| m.author.id) }; + Ok((avatar(&ctx.state, who, 512).await, text.to_string())) } // ---- /image, D!fx ------------------------------------------------------------------------------ diff --git a/src/hosted.rs b/src/hosted.rs new file mode 100644 index 0000000..5e69eb5 --- /dev/null +++ b/src/hosted.rs @@ -0,0 +1,102 @@ +//! Files too big for Discord, kept on the bot's own web server for a few hours so people can download them or +//! watch/listen in the browser: `data/hosted//` is served at `/f//` (the token is a random +//! 64-bit number, so a link only works for whoever was given it). Old files are deleted by [`start_cleanup`]. +use crate::paths; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +/// How long a hosted file is kept. +pub const TTL: Duration = Duration::from_secs(6 * 60 * 60); +/// Everything hosted together never takes more than this much disk; the oldest go first. +const MAX_TOTAL: u64 = 3 * 1024 * 1024 * 1024; +/// The biggest single file we will host. +pub const MAX_FILE: u64 = 1024 * 1024 * 1024; + +pub fn dir() -> PathBuf { + let d = paths::data(&["hosted"]); + let _ = std::fs::create_dir_all(&d); + d +} + +/// The address people open (the dashboard's public address). +pub fn base_url() -> String { + std::env::var("DASHBOARD_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "http://192.168.1.71:8080".into()).trim_end_matches('/').to_string() +} + +/// Copy `src` into the hosted folder as `name` and give back its public link. +pub fn store(src: &Path, name: &str) -> std::io::Result { + let name = crate::ui::file_name(name); + let token = format!("{:016x}", rand::random::()); + let folder = dir().join(&token); + std::fs::create_dir_all(&folder)?; + std::fs::copy(src, folder.join(&name))?; + prune(); + Ok(format!("{}/f/{token}/{name}", base_url())) +} + +fn folder_size(p: &Path) -> u64 { + std::fs::read_dir(p).map(|rd| rd.flatten().filter_map(|e| e.metadata().ok()).map(|m| m.len()).sum()).unwrap_or(0) +} + +/// Delete expired folders, then the oldest ones while over the disk budget. +pub fn prune() { + let Ok(rd) = std::fs::read_dir(dir()) else { return }; + let mut keep: Vec<(SystemTime, u64, PathBuf)> = Vec::new(); + for e in rd.flatten() { + let path = e.path(); + let Ok(meta) = e.metadata() else { continue }; + let made = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); + if made.elapsed().unwrap_or_default() > TTL { + let _ = std::fs::remove_dir_all(&path); + } else { + keep.push((made, folder_size(&path), path)); + } + } + keep.sort_by_key(|k| k.0); + let mut total: u64 = keep.iter().map(|k| k.1).sum(); + for (_, size, path) in keep { + if total <= MAX_TOTAL { + break; + } + let _ = std::fs::remove_dir_all(path); + total = total.saturating_sub(size); + } +} + +/// Clean up now and every ten minutes. +pub fn start_cleanup() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tokio::spawn(async { + loop { + prune(); + tokio::time::sleep(Duration::from_secs(600)).await; + } + }); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_stored_file_gets_a_link_and_old_ones_expire() { + let tmp = std::env::temp_dir().join(format!("dezio-host-{}", std::process::id())); + std::fs::create_dir_all(&tmp).unwrap(); + let src = tmp.join("a.bin"); + std::fs::write(&src, b"hello").unwrap(); + let url = store(&src, "My Video (1).mp4").unwrap(); + assert!(url.contains("/f/") && url.ends_with("My_Video__1.mp4"), "{url}"); + let token = url.rsplit('/').nth(1).unwrap(); + let stored = dir().join(token); + assert!(stored.exists()); + // age it past the time limit + let old = SystemTime::now() - TTL - Duration::from_secs(60); + let f = std::fs::File::open(&stored).unwrap(); + f.set_modified(old).unwrap(); + prune(); + assert!(!stored.exists(), "expired files are removed"); + let _ = std::fs::remove_dir_all(tmp); + } +} diff --git a/src/main.rs b/src/main.rs index 3eb4391..962034c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ mod prefs; mod paths; mod pix; mod state; +mod hosted; mod presence; mod text; mod tui; @@ -659,6 +660,7 @@ async fn main() -> Result<()> { commands::games::start_watch(state.clone()); commands::music::start_watch(state.clone()); commands::reactionroles::start_watch(state.clone()); + hosted::start_cleanup(); web::start(state.clone()); tracing::info!("ready as {} in {} guilds", r.user.name, r.guilds.len()); } diff --git a/src/web/mod.rs b/src/web/mod.rs index 9cb45c1..2eb2341 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -299,6 +299,8 @@ pub fn router(w: Shared) -> Router { .nest_service("/dashboard/static", ServeDir::new(app.join("static"))) .nest_service("/assets", ServeDir::new(site.join("assets"))) .nest_service("/images", ServeDir::new(site.join("images"))) + // files too big for Discord, kept for a few hours (see hosted.rs) + .nest_service("/f", ServeDir::new(crate::hosted::dir())) .layer(middleware::from_fn(headers_mw)) .layer(axum::extract::DefaultBodyLimit::max(64 * 1024)) .with_state(w) @@ -433,6 +435,24 @@ mod tests { assert_eq!(s, StatusCode::OK); } + #[tokio::test] + async fn hosted_files_download_and_support_seeking() { + let tmp = std::env::temp_dir().join(format!("dezio-hostweb-{}.bin", rand::random::())); + std::fs::write(&tmp, b"0123456789").unwrap(); + let url = crate::hosted::store(&tmp, "My clip.mp4").unwrap(); + let path = url.strip_prefix(&crate::hosted::base_url()).unwrap().to_string(); + let app = router(web()); + let (status, headers, body) = call(&app, HttpRequest::get(&path).body(Body::empty()).unwrap()).await; + assert_eq!((status, body.as_slice()), (StatusCode::OK, &b"0123456789"[..]), "{path}"); + assert_eq!(headers.get("content-type").and_then(|v| v.to_str().ok()), Some("video/mp4")); + let (status, _, body) = call(&app, HttpRequest::get(&path).header("range", "bytes=2-4").body(Body::empty()).unwrap()).await; + assert_eq!((status, body.as_slice()), (StatusCode::PARTIAL_CONTENT, &b"234"[..])); + let (status, _, _) = call(&app, HttpRequest::get("/f/0000000000000000/nothing.mp4").body(Body::empty()).unwrap()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let _ = std::fs::remove_dir_all(crate::hosted::dir().join(path.split('/').nth(2).unwrap())); + let _ = std::fs::remove_file(tmp); + } + #[tokio::test] async fn the_quote_preview_is_drawn_by_the_bot() { let w = web();