Add music bot for self-hosted Stoat with web control panel
Plays audio into Stoat voice channels over LiveKit and exposes the same player through both chat commands and a browser panel, so the two never drift apart: everything routes through a single MusicManager. - core: per-server GuildPlayer (queue, loop, shuffle, seek, volume, idle auto-leave) driving revoice.js/@livekit/rtc-node and ffmpeg - sources: yt-dlp for YouTube/SoundCloud, direct media URLs and internet radio, optional local library with path-traversal guards - bot: 18 chat commands with aliases, plus !panel one-time login links - api: Fastify REST + WebSocket, sessions authenticated against the instance's own /auth/session/login (TOTP supported), permissions re-checked against Stoat membership and roles on every request - web: React panel with search, queue editing, seek and volume - deploy: Dockerfile, compose.override.yml and Caddyfile snippets for dropping the service into an existing /opt/stoat stack Verified with npm run typecheck, both builds, and scripts/smoke-api.mjs (9 API checks). Voice playback itself needs a live instance to test. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
d9d0e9f6bf
commit
a9b7ccdd16
@@ -0,0 +1,84 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { api } from "../api";
|
||||
|
||||
export function Login({ onSuccess }: { onSuccess: () => void }) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [totp, setTotp] = useState("");
|
||||
const [ticket, setTicket] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = ticket
|
||||
? await api.login({ mfaTicket: ticket, totpCode: totp })
|
||||
: await api.login({ email, password });
|
||||
if (result.mfaRequired && result.ticket) {
|
||||
setTicket(result.ticket);
|
||||
return;
|
||||
}
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Не удалось войти");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="login-wrap">
|
||||
<form className="card login" onSubmit={submit}>
|
||||
<h1>Stoat Music</h1>
|
||||
<p className="sub">Войдите учётной записью вашего Stoat-инстанса.</p>
|
||||
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
{ticket ? (
|
||||
<>
|
||||
<label htmlFor="totp">Код двухфакторной аутентификации</label>
|
||||
<input
|
||||
id="totp"
|
||||
value={totp}
|
||||
onChange={(event) => setTotp(event.target.value)}
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
autoFocus
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label htmlFor="email">E-mail</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
/>
|
||||
<label htmlFor="password">Пароль</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<button className="primary" type="submit" disabled={busy}>
|
||||
{busy ? "Проверяю…" : "Войти"}
|
||||
</button>
|
||||
<p className="hint">
|
||||
Пароль уходит напрямую в API вашего инстанса, бот его не сохраняет. Быстрее — команда{" "}
|
||||
<code>!panel</code> в чате: она выдаёт персональную ссылку без пароля.
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useEffect, useState, type MouseEvent } from "react";
|
||||
import { formatDuration } from "../api";
|
||||
import type { LoopMode, PlayerState, VoiceChannel } from "../types";
|
||||
|
||||
interface Props {
|
||||
state: PlayerState;
|
||||
position: number;
|
||||
canControl: boolean;
|
||||
voiceChannels: VoiceChannel[];
|
||||
yourVoiceChannel: VoiceChannel | null;
|
||||
onAction(action: string, payload?: Record<string, unknown>): void;
|
||||
onSeek(seconds: number): void;
|
||||
onJoin(channelId: string | null): void;
|
||||
}
|
||||
|
||||
const STATUS_LABEL: Record<PlayerState["status"], string> = {
|
||||
idle: "ожидание",
|
||||
connecting: "подключение",
|
||||
buffering: "буферизация",
|
||||
playing: "играет",
|
||||
paused: "пауза",
|
||||
};
|
||||
|
||||
const LOOP_LABEL: Record<LoopMode, string> = {
|
||||
off: "🔁 выкл",
|
||||
track: "🔂 трек",
|
||||
queue: "🔁 очередь",
|
||||
};
|
||||
|
||||
export function NowPlaying({
|
||||
state,
|
||||
position,
|
||||
canControl,
|
||||
voiceChannels,
|
||||
yourVoiceChannel,
|
||||
onAction,
|
||||
onSeek,
|
||||
onJoin,
|
||||
}: Props) {
|
||||
const [volume, setVolume] = useState(state.volume);
|
||||
const [channelId, setChannelId] = useState<string>(
|
||||
state.voiceChannelId ?? yourVoiceChannel?.id ?? voiceChannels[0]?.id ?? "",
|
||||
);
|
||||
|
||||
useEffect(() => setVolume(state.volume), [state.volume]);
|
||||
useEffect(() => {
|
||||
if (state.voiceChannelId) setChannelId(state.voiceChannelId);
|
||||
}, [state.voiceChannelId]);
|
||||
|
||||
const track = state.current;
|
||||
const duration = track?.duration ?? 0;
|
||||
const ratio = duration > 0 ? Math.min(1, position / duration) : 0;
|
||||
const isPlaying = state.status === "playing" || state.status === "buffering";
|
||||
|
||||
function seekFromClick(event: MouseEvent<HTMLDivElement>) {
|
||||
if (!track || duration <= 0 || !canControl) return;
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
const fraction = (event.clientX - rect.left) / rect.width;
|
||||
onSeek(Math.max(0, Math.min(duration - 1, fraction * duration)));
|
||||
}
|
||||
|
||||
const nextLoop: LoopMode = state.loop === "off" ? "track" : state.loop === "track" ? "queue" : "off";
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>
|
||||
Сейчас играет{" "}
|
||||
<span className={`status-pill ${state.status === "playing" ? "playing" : ""}`}>
|
||||
{STATUS_LABEL[state.status]}
|
||||
</span>
|
||||
</h2>
|
||||
|
||||
<div className="now">
|
||||
{track?.thumbnail ? (
|
||||
<img className="cover" src={track.thumbnail} alt="" />
|
||||
) : (
|
||||
<div className="cover placeholder">🎵</div>
|
||||
)}
|
||||
<div className="now-meta">
|
||||
<div className="now-title">
|
||||
{track ? (
|
||||
/^https?:/.test(track.url) ? (
|
||||
<a href={track.url} target="_blank" rel="noreferrer noopener">
|
||||
{track.title}
|
||||
</a>
|
||||
) : (
|
||||
track.title
|
||||
)
|
||||
) : (
|
||||
"Тишина"
|
||||
)}
|
||||
</div>
|
||||
<div className="now-sub">
|
||||
{track
|
||||
? [track.author, `запросил ${track.requestedBy.username}`].filter(Boolean).join(" · ")
|
||||
: "Очередь пуста — найдите что-нибудь слева"}
|
||||
</div>
|
||||
<div className="progress">
|
||||
<div className="bar" onClick={seekFromClick}>
|
||||
<span style={{ width: `${ratio * 100}%` }} />
|
||||
</div>
|
||||
<div className="times">
|
||||
<span>{track ? formatDuration(position) : "0:00"}</span>
|
||||
<span>{track?.isLive ? "LIVE" : formatDuration(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="controls">
|
||||
<button
|
||||
className="icon big primary"
|
||||
onClick={() => onAction("toggle")}
|
||||
disabled={!canControl || !track}
|
||||
title={isPlaying ? "Пауза" : "Играть"}
|
||||
>
|
||||
{isPlaying ? "⏸" : "▶"}
|
||||
</button>
|
||||
<button className="icon" onClick={() => onAction("skip")} disabled={!canControl} title="Следующий">
|
||||
⏭
|
||||
</button>
|
||||
<button className="icon" onClick={() => onAction("stop")} disabled={!canControl} title="Стоп">
|
||||
⏹
|
||||
</button>
|
||||
<button
|
||||
className="icon"
|
||||
onClick={() => onAction("shuffle")}
|
||||
disabled={!canControl || state.queue.length < 2}
|
||||
title="Перемешать"
|
||||
>
|
||||
🔀
|
||||
</button>
|
||||
<button
|
||||
className={state.loop === "off" ? "" : "active"}
|
||||
onClick={() => onAction("loop", { mode: nextLoop })}
|
||||
disabled={!canControl}
|
||||
title="Режим повтора"
|
||||
>
|
||||
{LOOP_LABEL[state.loop]}
|
||||
</button>
|
||||
|
||||
<div className="volume">
|
||||
<span title="Громкость">🔊</span>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={200}
|
||||
value={volume}
|
||||
disabled={!canControl}
|
||||
onChange={(event) => setVolume(Number(event.target.value))}
|
||||
onMouseUp={() => onAction("volume", { volume })}
|
||||
onTouchEnd={() => onAction("volume", { volume })}
|
||||
/>
|
||||
<span className="badge">{volume}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="voice-row">
|
||||
<select value={channelId} onChange={(event) => setChannelId(event.target.value)} disabled={!canControl}>
|
||||
{voiceChannels.length === 0 && <option value="">Нет голосовых каналов</option>}
|
||||
{voiceChannels.map((channel) => (
|
||||
<option key={channel.id} value={channel.id}>
|
||||
{channel.name}
|
||||
{yourVoiceChannel?.id === channel.id ? " (вы здесь)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button onClick={() => onJoin(channelId || null)} disabled={!canControl || !channelId}>
|
||||
{state.voiceChannelId === channelId ? "Переподключить" : "Зайти"}
|
||||
</button>
|
||||
<button onClick={() => onAction("leave")} disabled={!canControl || !state.voiceChannelId}>
|
||||
Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { formatDuration } from "../api";
|
||||
import type { Track } from "../types";
|
||||
|
||||
interface Props {
|
||||
tracks: Track[];
|
||||
canControl: boolean;
|
||||
onRemove(track: Track): void;
|
||||
onMove(track: Track, index: number): void;
|
||||
onClear(): void;
|
||||
}
|
||||
|
||||
export function QueueList({ tracks, canControl, onRemove, onMove, onClear }: Props) {
|
||||
const total = tracks.reduce((acc, track) => acc + track.duration, 0);
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>
|
||||
Очередь · {tracks.length}
|
||||
{total > 0 ? ` · ${formatDuration(total)}` : ""}
|
||||
</h2>
|
||||
|
||||
{tracks.length === 0 ? (
|
||||
<div className="empty">Очередь пуста</div>
|
||||
) : (
|
||||
<>
|
||||
<ul className="track-list">
|
||||
{tracks.map((track, index) => (
|
||||
<li className="track" key={track.id}>
|
||||
<span className="idx">{index + 1}</span>
|
||||
{track.thumbnail ? <img className="thumb" src={track.thumbnail} alt="" /> : <div className="thumb" />}
|
||||
<div className="info">
|
||||
<div className="title">{track.title}</div>
|
||||
<div className="sub">
|
||||
{[track.author, track.isLive ? "LIVE" : formatDuration(track.duration), track.requestedBy.username]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</div>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<button
|
||||
onClick={() => onMove(track, 0)}
|
||||
disabled={!canControl || index === 0}
|
||||
title="Наверх очереди"
|
||||
>
|
||||
⤒
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onMove(track, Math.max(0, index - 1))}
|
||||
disabled={!canControl || index === 0}
|
||||
title="Выше"
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onMove(track, index + 1)}
|
||||
disabled={!canControl || index === tracks.length - 1}
|
||||
title="Ниже"
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button onClick={() => onRemove(track)} disabled={!canControl} title="Убрать">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="row" style={{ marginTop: 12 }}>
|
||||
<button className="ghost" onClick={onClear} disabled={!canControl}>
|
||||
Очистить очередь
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { api, formatDuration } from "../api";
|
||||
import type { Track } from "../types";
|
||||
|
||||
const SOURCE_BADGE: Record<Track["source"], string> = {
|
||||
youtube: "YouTube",
|
||||
soundcloud: "SoundCloud",
|
||||
direct: "Ссылка",
|
||||
local: "Медиатека",
|
||||
};
|
||||
|
||||
interface Props {
|
||||
serverId: string;
|
||||
canControl: boolean;
|
||||
localLibrary: boolean;
|
||||
onError(message: string | null): void;
|
||||
}
|
||||
|
||||
export function SearchPanel({ serverId, canControl, localLibrary, onError }: Props) {
|
||||
const [query, setQuery] = useState("");
|
||||
const [results, setResults] = useState<Track[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [lastAdded, setLastAdded] = useState<string | null>(null);
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
const value = query.trim();
|
||||
if (!value) return;
|
||||
setBusy(true);
|
||||
onError(null);
|
||||
try {
|
||||
if (/^https?:\/\//i.test(value)) {
|
||||
await api.play(serverId, { query: value });
|
||||
setLastAdded(value);
|
||||
setResults([]);
|
||||
setQuery("");
|
||||
return;
|
||||
}
|
||||
const { tracks } = await api.search(serverId, value);
|
||||
setResults(tracks);
|
||||
} catch (err) {
|
||||
onError(err instanceof Error ? err.message : "Поиск не удался");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function enqueue(track: Track, mode: "append" | "next" | "now") {
|
||||
onError(null);
|
||||
try {
|
||||
await api.play(serverId, { trackIds: [track.id], mode });
|
||||
setLastAdded(track.title);
|
||||
} catch (err) {
|
||||
onError(err instanceof Error ? err.message : "Не удалось добавить трек");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>Поиск</h2>
|
||||
<form className="search-form" onSubmit={submit}>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Название трека или ссылка…"
|
||||
disabled={!canControl}
|
||||
/>
|
||||
<button className="primary" type="submit" disabled={busy || !canControl}>
|
||||
{busy ? "…" : "Найти"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{results.length === 0 ? (
|
||||
<div className="empty">
|
||||
{lastAdded ? `Добавлено: ${lastAdded}` : "Введите запрос или вставьте ссылку — плейлисты тоже поддерживаются."}
|
||||
</div>
|
||||
) : (
|
||||
<ul className="track-list">
|
||||
{results.map((track, index) => (
|
||||
<li className="track" key={track.id}>
|
||||
<span className="idx">{index + 1}</span>
|
||||
{track.thumbnail ? <img className="thumb" src={track.thumbnail} alt="" /> : <div className="thumb" />}
|
||||
<div className="info">
|
||||
<div className="title">{track.title}</div>
|
||||
<div className="sub">
|
||||
{[track.author, track.isLive ? "LIVE" : formatDuration(track.duration)].filter(Boolean).join(" · ")}
|
||||
</div>
|
||||
</div>
|
||||
<span className="badge">{SOURCE_BADGE[track.source]}</span>
|
||||
<div className="actions">
|
||||
<button onClick={() => enqueue(track, "now")} disabled={!canControl} title="Играть сейчас">
|
||||
▶
|
||||
</button>
|
||||
<button onClick={() => enqueue(track, "next")} disabled={!canControl} title="Следующим">
|
||||
⤴
|
||||
</button>
|
||||
<button onClick={() => enqueue(track, "append")} disabled={!canControl} title="В очередь">
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<p className="hint">
|
||||
Префиксы: <code>sc:</code> — искать в SoundCloud, <code>yt:</code> — в YouTube
|
||||
{localLibrary ? (
|
||||
<>
|
||||
, <code>local:</code> — в локальной медиатеке
|
||||
</>
|
||||
) : null}
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user