Lighter music card for the slow upload, security patches
One GIF upload took latency to Discord from 39 ms to over 450 ms, which was the music lag. The card is smaller and about 15 fps, goes still when uploads get slow, and panels no longer hold up skips. The waveform reads at a gentler rate and recent pictures are reused. deploy/shape-upload.sh keeps voice ahead of uploads. Music links get the private-network check, music ffmpeg can only open web addresses, casino bets are checked and taken in one step, zstd-safe updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
2072e5aac8
commit
2a53e42dba
10 changed files with 164 additions and 37 deletions
4
Cargo.lock
generated
4
Cargo.lock
generated
|
|
@ -6613,9 +6613,9 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
|||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "7.3.0"
|
||||
version = "7.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"
|
||||
checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -119,3 +119,12 @@ Plan (backward compatible with the existing file):
|
|||
- `commands/action_art.rs`: pictures for moderation results, AFK, snipe, stolen emojis, VirusTotal reports and download progress. Download progress is a picture every 5 s; `Live::freeze` stops those edits before the finished file goes up, because each edit replaces the message's files. Upload limit is 20 MiB by default since Discord's change on 2026-09-03 (`upload_limit`), more with boost levels 2 and 3.
|
||||
- `/queue` stays text: it's a private, self-deleting list of clickable links. A download's finished message is the video or file itself, so it gets no card.
|
||||
- Security pass: powerful roles are refused in role menus and autoroles (`State::role_gives_power`), redirects are checked at every hop, HSTS, Game Boy page frameable only by Discord. Not done: rate limits, Forgejo on its own subdomain, narrower invite permissions, `cargo audit` (not installed).
|
||||
|
||||
## Speed and security pass (2026-11-07)
|
||||
- Measured on the Chromebook: 425 KB/s down, 114 KB/s up. Voice shares that upload, so a 664 KB GIF took latency to Discord from 39 ms to 450-785 ms. That was the music lag.
|
||||
- The music card is now 640 wide at about 15 fps and turns into a still picture if uploads take over 12 s. `deploy/shape-upload.sh` keeps the queue on the server so voice goes first; it has to be run by hand on the server.
|
||||
- The waveform reads at 10x speed, panels no longer hold up skips, recent avatars and covers are kept for 10 minutes.
|
||||
- yt-dlp takes about 7 s per song because of its JS step. The faster clients were tested: android_vr gets a 403, android and others give the 360p video stream, about 4x the bandwidth.
|
||||
- Attacked over the public address: traversal, forged sessions and bearer tokens, oversized bodies, open redirects, cross-site requests and Host tricks all failed. ffmpeg file reads through crafted playlists and concat files were refused. @everyone can't be sent through confessions, phone, AI or echo.
|
||||
- Patched: music links now get the private-network check, music ffmpeg can only open web addresses, casino bets are checked and taken in one step. zstd-safe updated.
|
||||
- Still open: rustls 0.22 (twilight-gateway), rustls-webpki 0.102, ringbuf and libcrux (songbird) need new upstream releases. All Forgejo repos are public. Redirects inside yt-dlp and ffmpeg aren't checked.
|
||||
|
|
|
|||
66
deploy/shape-upload.sh
Executable file
66
deploy/shape-upload.sh
Executable file
|
|
@ -0,0 +1,66 @@
|
|||
#!/bin/bash
|
||||
# Keeps voice smooth on the Chromebook's slow upload (about 0.9 Mbit/s).
|
||||
# Without this, one picture upload fills the router's queue and voice packets wait behind it: latency to Discord went
|
||||
# from 39 ms to 450-785 ms while a 664 KB GIF uploaded. This caps internet-bound traffic just under the line's speed so
|
||||
# the queue stays here, where fq_codel lets small flows like voice go first. Traffic to the home network isn't capped.
|
||||
#
|
||||
# shape-upload.sh turn it on
|
||||
# shape-upload.sh off turn it off
|
||||
# shape-upload.sh install turn it on now and at every boot
|
||||
#
|
||||
# It turns itself off again after 2 minutes unless `keep` is the second word, so a mistake can't lock anyone out.
|
||||
set -eu
|
||||
DEV=wlan0
|
||||
RATE=800kbit
|
||||
|
||||
off() { tc qdisc del dev "$DEV" root 2>/dev/null || true; }
|
||||
|
||||
on() {
|
||||
off
|
||||
tc qdisc add dev "$DEV" root handle 1: htb default 20
|
||||
tc class add dev "$DEV" parent 1: classid 1:1 htb rate 100mbit
|
||||
tc class add dev "$DEV" parent 1:1 classid 1:10 htb rate 90mbit ceil 100mbit
|
||||
tc class add dev "$DEV" parent 1:1 classid 1:20 htb rate "$RATE" ceil "$RATE"
|
||||
tc qdisc add dev "$DEV" parent 1:10 fq_codel
|
||||
tc qdisc add dev "$DEV" parent 1:20 fq_codel
|
||||
tc filter add dev "$DEV" parent 1: protocol ip prio 1 u32 match ip dst 192.168.0.0/16 flowid 1:10
|
||||
tc filter add dev "$DEV" parent 1: protocol ipv6 prio 2 u32 match ip6 dst fe80::/10 flowid 1:10
|
||||
}
|
||||
|
||||
case "${1:-on}" in
|
||||
off)
|
||||
off
|
||||
systemctl disable --now dezio-shape.service 2>/dev/null || true
|
||||
echo "Upload shaping is off"
|
||||
;;
|
||||
install)
|
||||
install -m 755 "$0" /usr/local/bin/dezio-shape
|
||||
cat > /etc/systemd/system/dezio-shape.service <<UNIT
|
||||
[Unit]
|
||||
Description=Keep voice smooth on the slow upload
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/usr/local/bin/dezio-shape on keep
|
||||
ExecStop=/usr/local/bin/dezio-shape off
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now dezio-shape.service
|
||||
echo "Upload shaping is on, now and at every boot"
|
||||
;;
|
||||
*)
|
||||
on
|
||||
if [ "${2:-}" = keep ]; then
|
||||
echo "Upload shaping is on"
|
||||
else
|
||||
nohup sh -c "sleep 120; tc qdisc del dev $DEV root" >/dev/null 2>&1 &
|
||||
echo "Upload shaping is on for 2 minutes as a test"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
|
@ -99,7 +99,7 @@ pub fn balance(user: u64) -> i64 {
|
|||
|
||||
pub fn add(user: u64, amount: i64) -> i64 {
|
||||
with_player(user, |p| {
|
||||
let m = (p.get("money").and_then(Value::as_i64).unwrap_or(STARTING) + amount).max(0);
|
||||
let m = p.get("money").and_then(Value::as_i64).unwrap_or(STARTING).saturating_add(amount).max(0);
|
||||
p.insert("money".into(), json!(m));
|
||||
m
|
||||
})
|
||||
|
|
@ -107,11 +107,18 @@ pub fn add(user: u64, amount: i64) -> i64 {
|
|||
|
||||
/// Take `amount` out of the wallet. False if it isn't there.
|
||||
pub fn take(user: u64, amount: i64) -> bool {
|
||||
if amount < 1 || balance(user) < amount {
|
||||
if amount < 1 {
|
||||
return false;
|
||||
}
|
||||
add(user, -amount);
|
||||
true
|
||||
// checked and taken in one step, so two games started together can't spend the same coins
|
||||
with_player(user, |p| {
|
||||
let money = p.get("money").and_then(Value::as_i64).unwrap_or(STARTING);
|
||||
if money < amount {
|
||||
return false;
|
||||
}
|
||||
p.insert("money".into(), json!(money - amount));
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
fn record(user: u64, bet: i64, payout: i64) {
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ fn is_global(ip: std::net::IpAddr) -> bool {
|
|||
}
|
||||
|
||||
/// Block requests to localhost and private networks (also after DNS lookup).
|
||||
async fn url_is_safe(url: &str) -> bool {
|
||||
pub(crate) async fn url_is_safe(url: &str) -> bool {
|
||||
let Some(parsed) = super::safe_url(url) else { return false };
|
||||
let Some(host) = parsed.host_str() else { return false };
|
||||
let host = host.trim_matches(|c| c == '[' || c == ']').to_lowercase();
|
||||
|
|
|
|||
|
|
@ -67,8 +67,23 @@ pub async fn fetch_limited(state: &State, url: &str, max: usize) -> Option<Vec<u
|
|||
|
||||
/// A picture from the web, decoded. `None` if it can't be had: every card has to work without it.
|
||||
pub async fn fetch_picture(state: &State, url: &str) -> Option<image::RgbaImage> {
|
||||
type Pictures = std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, image::RgbaImage)>>;
|
||||
static RECENT: std::sync::OnceLock<Pictures> = std::sync::OnceLock::new();
|
||||
const KEEP: std::time::Duration = std::time::Duration::from_secs(600);
|
||||
let recent = RECENT.get_or_init(Default::default);
|
||||
if let Some((at, picture)) = recent.lock().unwrap_or_else(|e| e.into_inner()).get(url) {
|
||||
if at.elapsed() < KEEP {
|
||||
return Some(picture.clone()); // avatars and covers come up again and again
|
||||
}
|
||||
}
|
||||
let bytes = fetch_limited(state, url, 4 * 1024 * 1024).await?;
|
||||
tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten()
|
||||
let picture = tokio::task::spawn_blocking(move || crate::pix::decode(&bytes)).await.ok().flatten()?;
|
||||
let mut all = recent.lock().unwrap_or_else(|e| e.into_inner());
|
||||
all.retain(|_, (at, _)| at.elapsed() < KEEP);
|
||||
if all.len() < 64 {
|
||||
all.insert(url.to_string(), (std::time::Instant::now(), picture.clone()));
|
||||
}
|
||||
Some(picture)
|
||||
}
|
||||
|
||||
/// A user's avatar picture (animated ones as GIF). Looks the user up if we haven't seen them.
|
||||
|
|
|
|||
|
|
@ -13,24 +13,25 @@ pub const STILL_NAME: &str = "player.jpg";
|
|||
/// How finely `source::peaks` measures a song.
|
||||
pub const LEVELS_PER_SECOND: usize = 5;
|
||||
|
||||
const WIDTH: u32 = 800;
|
||||
const HEIGHT: u32 = 384;
|
||||
const PAD: i32 = 28;
|
||||
const COVER: u32 = 112;
|
||||
const TEXT_X: i32 = PAD + COVER as i32 + 16;
|
||||
// Small on purpose: this picture goes up every 20 seconds on a home connection, and voice shares that upload.
|
||||
const WIDTH: u32 = 640;
|
||||
const HEIGHT: u32 = 308;
|
||||
const PAD: i32 = 22;
|
||||
const COVER: u32 = 90;
|
||||
const TEXT_X: i32 = PAD + COVER as i32 + 14;
|
||||
const COLUMN: i32 = WIDTH as i32 - PAD - TEXT_X;
|
||||
const BARS: usize = 36;
|
||||
const BAR_TOP: i32 = 156;
|
||||
const BAR_BOTTOM: i32 = 316;
|
||||
const CLOCK_Y: i32 = 332;
|
||||
const TRACK_LEFT: i32 = 104;
|
||||
const TRACK_RIGHT: i32 = WIDTH as i32 - 104;
|
||||
const BAR_TOP: i32 = 124;
|
||||
const BAR_BOTTOM: i32 = 252;
|
||||
const CLOCK_Y: i32 = 266;
|
||||
const TRACK_LEFT: i32 = 84;
|
||||
const TRACK_RIGHT: i32 = WIDTH as i32 - 84;
|
||||
/// Everything below this line changes from frame to frame.
|
||||
const MOVING_TOP: i32 = BAR_TOP - 4;
|
||||
|
||||
/// Twenty frames a second for 30 seconds. GIF delays are in hundredths of a second.
|
||||
const FRAME_DELAY: u16 = 5;
|
||||
const FRAMES: usize = 600;
|
||||
/// About fifteen frames a second for 30 seconds: smooth, and light enough for a slow upload. GIF delays are in hundredths.
|
||||
const FRAME_DELAY: u16 = 7;
|
||||
const FRAMES: usize = 430;
|
||||
/// A palette index no colour uses: in a frame it means "this pixel hasn't changed".
|
||||
const UNCHANGED: u8 = 255;
|
||||
/// How much of the palette the cover gets; the rest is kept for the interface's own colours.
|
||||
|
|
@ -82,9 +83,9 @@ fn clock(seconds: f64) -> String {
|
|||
fn backdrop(view: &View) -> RgbaImage {
|
||||
let mut img = RgbaImage::from_pixel(WIDTH, HEIGHT, rgba(SURFACE));
|
||||
cover(&mut img, view.cover.as_deref());
|
||||
line(&mut img, &view.status, (TEXT_X, 30), 17.0, false, MUTED, COLUMN);
|
||||
line(&mut img, &view.title, (TEXT_X, 50), 30.0, true, PRIMARY, COLUMN);
|
||||
line(&mut img, &view.artist, (TEXT_X, 92), 19.0, false, SECONDARY, COLUMN);
|
||||
line(&mut img, &view.status, (TEXT_X, 24), 14.0, false, MUTED, COLUMN);
|
||||
line(&mut img, &view.title, (TEXT_X, 42), 24.0, true, PRIMARY, COLUMN);
|
||||
line(&mut img, &view.artist, (TEXT_X, 76), 15.0, false, SECONDARY, COLUMN);
|
||||
img
|
||||
}
|
||||
|
||||
|
|
@ -163,12 +164,12 @@ fn progress_width(view: &View, seconds: f64) -> i32 {
|
|||
|
||||
/// The parts of the moving strip that don't move: the empty progress track and the song's length.
|
||||
fn strip_backdrop(img: &mut RgbaImage, view: &View) {
|
||||
pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 10, TRACK_RIGHT - TRACK_LEFT, 4, 2, rgba(TRACK));
|
||||
pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 8, TRACK_RIGHT - TRACK_LEFT, 4, 2, rgba(TRACK));
|
||||
if let Some(d) = view.duration.filter(|d| *d > 0.0) {
|
||||
let end = clock(d);
|
||||
let look = text::Look::new(None, false, MUTED);
|
||||
let w = text::width_of(&end, 17.0, &look).ceil() as i32;
|
||||
line(img, &end, (WIDTH as i32 - PAD - w, CLOCK_Y), 17.0, false, MUTED, w + 1);
|
||||
let w = text::width_of(&end, 14.0, &look).ceil() as i32;
|
||||
line(img, &end, (WIDTH as i32 - PAD - w, CLOCK_Y), 14.0, false, MUTED, w + 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -180,9 +181,9 @@ fn moment(img: &mut RgbaImage, view: &View, bars: &[[u8; 3]; 3], seconds: f64) {
|
|||
let height = bar_height(i, seconds as f32, level);
|
||||
pix::rounded_rect(img, x, BAR_BOTTOM - height, width, height, 3, rgba(bars[bar_band(i)]));
|
||||
}
|
||||
line(img, &clock(seconds), (PAD, CLOCK_Y), 17.0, false, SECONDARY, 72);
|
||||
line(img, &clock(seconds), (PAD, CLOCK_Y), 14.0, false, SECONDARY, 58);
|
||||
strip_backdrop(img, view);
|
||||
pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 10, progress_width(view, seconds), 4, 2, rgba(bars[2]));
|
||||
pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 8, progress_width(view, seconds), 4, 2, rgba(bars[2]));
|
||||
}
|
||||
|
||||
/// One picture, for a paused song.
|
||||
|
|
@ -286,7 +287,7 @@ pub fn moving(view: &View, lead: f64) -> Vec<u8> {
|
|||
strip_backdrop(&mut empty, view);
|
||||
let empty = image::imageops::crop_imm(&empty, 0, MOVING_TOP as u32, WIDTH, HEIGHT - MOVING_TOP as u32).to_image();
|
||||
let fixed: Vec<u8> = empty.pixels().map(|p| palette.index([p[0], p[1], p[2]])).collect();
|
||||
let (clock_x, clock_y, clock_w, clock_h) = (PAD as usize, (CLOCK_Y - MOVING_TOP) as usize, 72usize, 26usize);
|
||||
let (clock_x, clock_y, clock_w, clock_h) = (PAD as usize, (CLOCK_Y - MOVING_TOP) as usize, 58usize, 21usize);
|
||||
let (mut shown, mut digits) = (String::new(), vec![0u8; clock_w * clock_h]);
|
||||
for n in 1..FRAMES {
|
||||
let seconds = at(n);
|
||||
|
|
@ -297,12 +298,12 @@ pub fn moving(view: &View, lead: f64) -> Vec<u8> {
|
|||
let height = bar_height(i, seconds as f32, level);
|
||||
strip.fill(x, BAR_BOTTOM - height, width, height, bar_ink[bar_band(i)]);
|
||||
}
|
||||
strip.fill(TRACK_LEFT, CLOCK_Y + 10, progress_width(view, seconds), 4, bar_ink[2]);
|
||||
strip.fill(TRACK_LEFT, CLOCK_Y + 8, progress_width(view, seconds), 4, bar_ink[2]);
|
||||
// the clock only changes once a second, so its text is drawn once a second
|
||||
let time = clock(seconds);
|
||||
if time != shown {
|
||||
let mut sprite = RgbaImage::from_pixel(clock_w as u32, clock_h as u32, rgba(SURFACE));
|
||||
line(&mut sprite, &time, (0, 0), 17.0, false, SECONDARY, clock_w as i32);
|
||||
line(&mut sprite, &time, (0, 0), 14.0, false, SECONDARY, clock_w as i32);
|
||||
digits = sprite.pixels().map(|p| palette.index([p[0], p[1], p[2]])).collect();
|
||||
shown = time;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ const LOOP_MODES: [&str; 3] = ["off", "track", "queue"];
|
|||
/// How often the panel's picture is replaced while a song plays, sooner than its 30 seconds of animation run out.
|
||||
/// Each one is an upload and a message edit. The watch loop runs every 10 s, so this means every 20.
|
||||
const PANEL_TICK: Duration = Duration::from_secs(18);
|
||||
/// Seconds an upload may take before the panel stops animating to spare the connection.
|
||||
const SLOW_UPLOAD: f64 = 12.0;
|
||||
/// How long a new picture takes to reach people, until a real one has been measured.
|
||||
const FIRST_LEAD: f64 = 3.0;
|
||||
/// A playing song whose position hasn't moved for this long has lost its voice connection.
|
||||
|
|
@ -99,6 +101,8 @@ pub struct Player {
|
|||
play_lock: AsyncMutex<()>,
|
||||
/// Serialises voice connects.
|
||||
connect_lock: AsyncMutex<()>,
|
||||
/// One panel post at a time, or quick skips would leave two behind.
|
||||
panel_lock: AsyncMutex<()>,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
|
|
@ -126,6 +130,7 @@ fn player_for(guild: Guild) -> Arc<Player> {
|
|||
st: Mutex::new(PState { queue: VecDeque::new(), current: None, loop_mode: 0, volume: percent as f32 / 100.0, text_channel: None, panel: None, skip_requested: false, votes: None, alone_since: None, idle_since: None, loading: None, next_id: 1, waveform: None, plain_panel: false, drawn_at: None, lead: FIRST_LEAD, moved: None }),
|
||||
play_lock: AsyncMutex::new(()),
|
||||
connect_lock: AsyncMutex::new(()),
|
||||
panel_lock: AsyncMutex::new(()),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
|
|
@ -406,7 +411,9 @@ async fn play_next(state: &Arc<State>, p: &Arc<Player>, ended: bool) {
|
|||
st.current = Some(Current { track: track.clone(), handle, pos, id, paused: false });
|
||||
st.idle_since = None;
|
||||
}
|
||||
show_panel(state, p).await;
|
||||
// not awaited: the next skip shouldn't have to wait for a picture to upload
|
||||
let (state, panel) = (state.clone(), p.clone());
|
||||
tokio::spawn(async move { show_panel(&state, &panel).await });
|
||||
prefetch(p);
|
||||
return;
|
||||
}
|
||||
|
|
@ -649,6 +656,7 @@ async fn tint(state: &State, track: &Track, default: u32) -> u32 {
|
|||
|
||||
/// Post a fresh panel at the bottom of the chat, replacing the old one.
|
||||
async fn show_panel(state: &Arc<State>, p: &Arc<Player>) {
|
||||
let _one_at_a_time = p.panel_lock.lock().await;
|
||||
clear_panel(state, p).await;
|
||||
let (track, channel) = {
|
||||
let st = p.lock();
|
||||
|
|
@ -721,7 +729,8 @@ async fn panel_picture(p: &Player, animate: bool) -> Option<Attachment> {
|
|||
let mut who: Vec<String> = track.uploader.iter().cloned().collect();
|
||||
who.extend(track.album.iter().map(|a| track.year.map_or(a.clone(), |y| format!("{a} ({y})"))));
|
||||
who.push(track.duration.map_or("Live".to_string(), |d| fmt_time(d as f64)));
|
||||
(animate && !cur.paused, st.lead, card::View { status: status.to_string(), title: track.title.clone(), artist: who.join(" · "), position: cur.pos.seconds(), duration: track.duration.map(|d| d as f64), levels: art.peaks.clone(), cover: art.cover.clone() })
|
||||
// when the connection is struggling, a still picture is all it should have to carry
|
||||
(animate && !cur.paused && st.lead < SLOW_UPLOAD, st.lead, card::View { status: status.to_string(), title: track.title.clone(), artist: who.join(" · "), position: cur.pos.seconds(), duration: track.duration.map(|d| d as f64), levels: art.peaks.clone(), cover: art.cover.clone() })
|
||||
};
|
||||
let (moving, lead, view) = view;
|
||||
let (name, bytes) = tokio::task::spawn_blocking(move || if moving { (card::MOVING_NAME, card::moving(&view, lead)) } else { (card::STILL_NAME, card::still(&view)) }).await.ok()?;
|
||||
|
|
@ -745,7 +754,7 @@ async fn refresh_panel(state: &State, p: &Player) {
|
|||
edit = edit.keep_attachment_ids(&[]); // twilight keeps old files by default, which would stack one per redraw
|
||||
}
|
||||
let Err(e) = edit.await else {
|
||||
p.lock().lead = started.elapsed().as_secs_f64().min(15.0) + 0.5; // the half second is Discord showing it
|
||||
p.lock().lead = started.elapsed().as_secs_f64().min(20.0) + 0.5; // the half second is Discord showing it
|
||||
return;
|
||||
};
|
||||
// Only a deleted panel is forgotten: a slow upload mustn't stop the updates, and a newer panel stays.
|
||||
|
|
|
|||
|
|
@ -168,6 +168,9 @@ impl Drop for BufferedPipe {
|
|||
}
|
||||
}
|
||||
|
||||
/// What ffmpeg may open for a song: the web, never a local file a crafted page or playlist points it at.
|
||||
const WEB_ONLY: &str = "http,https,tcp,tls,crypto";
|
||||
|
||||
/// Start ffmpeg on a stream (optionally from `start` seconds in) and give back the voice input and its position.
|
||||
pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> {
|
||||
let (pipe, position) = spawn_pipe(stream, start)?;
|
||||
|
|
@ -178,6 +181,7 @@ pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> {
|
|||
pub fn spawn_pipe(stream: &Stream, start: f64) -> Result<(BufferedPipe, Position), String> {
|
||||
let mut cmd = Command::new(crate::commands::media::download::tool("ffmpeg"));
|
||||
cmd.args(["-nostdin", "-loglevel", "error", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_on_network_error", "1", "-reconnect_on_http_error", "4xx,5xx", "-reconnect_delay_max", "5"]);
|
||||
cmd.args(["-protocol_whitelist", WEB_ONLY]);
|
||||
if start > 0.0 {
|
||||
cmd.args(["-ss", &format!("{start:.2}")]);
|
||||
}
|
||||
|
|
@ -205,7 +209,8 @@ pub async fn peaks(stream: &Stream, per_second: usize) -> Option<Vec<f32>> {
|
|||
use tokio::io::AsyncReadExt;
|
||||
const RATE: usize = 2000;
|
||||
let mut cmd = tokio::process::Command::new(crate::commands::media::download::tool("ffmpeg"));
|
||||
cmd.args(["-nostdin", "-loglevel", "error"]);
|
||||
// reading at ten times playing speed leaves the slow home line to the song itself
|
||||
cmd.args(["-nostdin", "-loglevel", "error", "-protocol_whitelist", WEB_ONLY, "-readrate", "10"]);
|
||||
if !stream.headers.is_empty() {
|
||||
cmd.arg("-headers").arg(stream.headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect::<String>());
|
||||
}
|
||||
|
|
@ -260,7 +265,19 @@ mod tests {
|
|||
let path = std::env::temp_dir().join(format!("dezio-peaks-{}.wav", std::process::id()));
|
||||
let filter = "aevalsrc='if(lt(t,1),0,0.5*sin(440*2*PI*t))':d=2:s=44100";
|
||||
assert!(std::process::Command::new("ffmpeg").args(["-loglevel", "error", "-y", "-f", "lavfi", "-i", filter]).arg(&path).status().unwrap().success());
|
||||
let stream = Stream { url: path.to_string_lossy().into_owned(), headers: vec![], at: std::time::Instant::now() };
|
||||
let served = std::fs::read(&path).unwrap();
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0u8; 2048];
|
||||
let _ = socket.read(&mut request).await;
|
||||
let head = format!("HTTP/1.1 200 OK\r\nContent-Type: audio/wav\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", served.len());
|
||||
let _ = socket.write_all(head.as_bytes()).await;
|
||||
let _ = socket.write_all(&served).await;
|
||||
});
|
||||
let stream = Stream { url: format!("http://127.0.0.1:{port}/song.wav"), headers: vec![], at: std::time::Instant::now() };
|
||||
let levels = peaks(&stream, 4).await.unwrap();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(levels.len(), 8, "{levels:?}");
|
||||
|
|
|
|||
|
|
@ -221,6 +221,9 @@ async fn music_search(query: &str, requester: u64) -> Option<Track> {
|
|||
pub async fn search(query: &str, requester: u64) -> Result<Found, String> {
|
||||
let query = query.trim().trim_matches(|c| c == '<' || c == '>');
|
||||
if query.starts_with("http://") || query.starts_with("https://") {
|
||||
if !crate::commands::media::download::url_is_safe(query).await {
|
||||
return Err("That address points to a private network.".into());
|
||||
}
|
||||
let mix = youtube_mix(query);
|
||||
let info = extract(query, Mode::Link { first: mix.then_some(MIX_FIRST) }).await?;
|
||||
if info["_type"].as_str() == Some("playlist") || info.get("entries").is_some() {
|
||||
|
|
|
|||
Loading…
Reference in a new issue