Compare commits

...

9 Commits

Author SHA1 Message Date
vlad.os cfcfa0ccee fix: serve uploads via route handler instead of public/ (standalone 404 fix)
Deploy / build-and-deploy (push) Successful in 1m49s
2026-06-15 03:34:11 +03:00
vlad.os 3f41d7699c feat: accept any audio/video upload, server converts to 6s compressed MP3
Deploy / build-and-deploy (push) Successful in 1m44s
2026-06-15 03:25:44 +03:00
vlad.os 6a4be6b939 feat: move emoji picker from ResourceBrowser into item editor form
Deploy / build-and-deploy (push) Successful in 1m48s
2026-06-15 02:58:18 +03:00
vlad.os 0c35693598 feat: shared player with 6s cap, progress bar, stop button
Deploy / build-and-deploy (push) Successful in 1m43s
2026-06-15 02:17:46 +03:00
vlad.os 2dd604192f fix: TypeScript - capture Howl ref in closure
Deploy / build-and-deploy (push) Successful in 1m52s
2026-06-15 01:36:24 +03:00
vlad.os fb19efa72f fix: howler unlock retry on playerror
Deploy / build-and-deploy (push) Has been cancelled
2026-06-15 01:35:36 +03:00
vlad.os 05c4f19109 fix: replace new Audio() with howler.js for reliable sound playback + error logging
Deploy / build-and-deploy (push) Has been cancelled
2026-06-15 01:35:08 +03:00
vlad.os 19d7a161c7 feat: convert uploaded OGG to MP3 via ffmpeg
Deploy / build-and-deploy (push) Successful in 2m4s
2026-06-15 01:25:50 +03:00
vlad.os e158467c76 Статусы капитана 2026-06-15 01:13:09 +03:00
14 changed files with 379 additions and 192 deletions
+4
View File
@@ -35,6 +35,10 @@ yarn-error.log*
/data/*.db-wal
/data/*.db-shm
# uploads (user content)
/public/uploads/
/data/uploads/
# env files (can opt-in for committing if needed)
.env*
+3 -2
View File
@@ -13,14 +13,15 @@ WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs && \
RUN apk add --no-cache ffmpeg && \
addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
RUN mkdir -p /app/data /app/public/uploads && chmod 777 /app/data /app/public/uploads
RUN mkdir -p /app/data /app/data/uploads && chmod 777 /app/data /app/data/uploads
USER nextjs
+1 -1
View File
@@ -7,7 +7,7 @@ import path from "path";
import { v4 as uuidv4 } from "uuid";
import { eq } from "drizzle-orm";
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "images");
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "images");
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
const MAX_SIZE = 5 * 1024 * 1024;
+24 -12
View File
@@ -6,8 +6,13 @@ import { writeFile, mkdir, unlink } from "fs/promises";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { eq } from "drizzle-orm";
import { convertToCompressedMp3 } from "@/lib/convert";
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds");
export const maxDuration = 120;
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "sounds");
const ALLOWED_EXTENSIONS = /\.(mp3|ogg|wav|flac|aac|m4a|wma|opus|webm|mp4|avi|mov|mkv|webm|wmv|flv)$/i;
const MAX_SIZE = 50 * 1024 * 1024; // 50 MB
export async function GET() {
const session = await getServerSession();
@@ -42,29 +47,36 @@ export async function POST(req: NextRequest) {
const results: { url: string; originalName: string; duration: number }[] = [];
for (const file of files) {
if (!file.name.toLowerCase().endsWith(".ogg")) continue;
if (file.size > 2 * 1024 * 1024) continue;
if (!ALLOWED_EXTENSIONS.test(file.name)) continue;
if (file.size > MAX_SIZE) continue;
const baseName = uuidv4();
const inputPath = path.join(UPLOAD_DIR, `${baseName}.in`);
const mp3Path = path.join(UPLOAD_DIR, `${baseName}.mp3`);
const ext = path.extname(file.name);
const filename = `${uuidv4()}${ext}`;
const filepath = path.join(UPLOAD_DIR, filename);
const bytes = await file.arrayBuffer();
await writeFile(filepath, Buffer.from(bytes));
await writeFile(inputPath, Buffer.from(bytes));
// compute duration from file size (approximate for OGG Vorbis ~64kbps)
const duration = Math.round((file.size / (64 * 128)) * 10) / 10;
let storedFilename: string;
if (convertToCompressedMp3(inputPath, mp3Path)) {
await unlink(inputPath).catch(() => {});
storedFilename = `${baseName}.mp3`;
} else {
await unlink(inputPath).catch(() => {});
continue;
}
const id = uuidv4();
db.insert(sounds).values({
id,
originalName: file.name,
storedFilename: filename,
duration: Math.min(duration, 6),
storedFilename,
duration: 6,
uploadedBy: session.id,
createdAt: new Date().toISOString(),
}).run();
results.push({ url: `/uploads/sounds/${filename}`, originalName: file.name, duration: Math.min(duration, 6) });
results.push({ url: `/uploads/sounds/${storedFilename}`, originalName: file.name, duration: 6 });
}
return NextResponse.json({ sounds: results });
+35 -22
View File
@@ -2,11 +2,16 @@ import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "@/lib/auth";
import { db } from "@/lib/db";
import { sounds } from "@/lib/db/schema";
import { writeFile, mkdir } from "fs/promises";
import { writeFile, mkdir, unlink } from "fs/promises";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { convertToCompressedMp3 } from "@/lib/convert";
const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "sounds");
export const maxDuration = 60;
const UPLOAD_DIR = path.join(process.cwd(), "data", "uploads", "sounds");
const ALLOWED_EXTENSIONS = /\.(mp3|ogg|wav|flac|aac|m4a|wma|opus|webm|mp4|avi|mov|mkv|webm|wmv|flv)$/i;
const MAX_SIZE = 50 * 1024 * 1024; // 50 MB
export async function POST(req: NextRequest) {
const session = await getServerSession();
@@ -19,35 +24,43 @@ export async function POST(req: NextRequest) {
const file = formData.get("file") as File | null;
if (!file) return NextResponse.json({ error: "No file" }, { status: 400 });
if (!file.name.toLowerCase().endsWith(".ogg")) {
return NextResponse.json({ error: "Only OGG files allowed" }, { status: 400 });
if (!ALLOWED_EXTENSIONS.test(file.name)) {
return NextResponse.json({ error: "Unsupported file format" }, { status: 400 });
}
if (file.size > 2 * 1024 * 1024) {
return NextResponse.json({ error: "File too large (max 2MB)" }, { status: 400 });
if (file.size > MAX_SIZE) {
return NextResponse.json({ error: "File too large (max 50MB)" }, { status: 400 });
}
await mkdir(UPLOAD_DIR, { recursive: true });
const ext = path.extname(file.name);
const filename = `${uuidv4()}${ext}`;
const filepath = path.join(UPLOAD_DIR, filename);
const baseName = uuidv4();
const inputPath = path.join(UPLOAD_DIR, `${baseName}.in`);
const mp3Path = path.join(UPLOAD_DIR, `${baseName}.mp3`);
const bytes = await file.arrayBuffer();
await writeFile(filepath, Buffer.from(bytes));
await writeFile(inputPath, Buffer.from(bytes));
// approximate duration
const duration = Math.round((file.size / (64 * 128)) * 10) / 10;
let storedFilename: string;
if (convertToCompressedMp3(inputPath, mp3Path)) {
await unlink(inputPath).catch(() => {});
storedFilename = `${baseName}.mp3`;
const id = uuidv4();
db.insert(sounds).values({
id,
originalName: file.name,
storedFilename: filename,
duration: Math.min(duration, 6),
uploadedBy: session.id,
createdAt: new Date().toISOString(),
}).run();
const id = uuidv4();
db.insert(sounds).values({
id,
originalName: file.name,
storedFilename,
duration: 6,
uploadedBy: session.id,
createdAt: new Date().toISOString(),
}).run();
return NextResponse.json({ url: `/uploads/sounds/${filename}` });
return NextResponse.json({ url: `/uploads/sounds/${storedFilename}` });
}
await unlink(inputPath).catch(() => {});
return NextResponse.json({ error: "Conversion failed" }, { status: 500 });
} catch {
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
}
+49
View File
@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
const UPLOADS_DIR = path.join(process.cwd(), "data", "uploads");
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
const { path: segments } = await params;
const filePath = path.join(UPLOADS_DIR, ...segments);
if (!filePath.startsWith(UPLOADS_DIR)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
try {
const content = fs.readFileSync(filePath);
const ext = path.extname(filePath).toLowerCase();
const mime = MIME_MAP[ext] ?? "application/octet-stream";
return new NextResponse(content, {
headers: {
"Content-Type": mime,
"Cache-Control": "public, max-age=31536000, immutable",
},
});
} catch {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
}
const MIME_MAP: Record<string, string> = {
".mp3": "audio/mpeg",
".ogg": "audio/ogg",
".wav": "audio/wav",
".flac": "audio/flac",
".m4a": "audio/mp4",
".webm": "audio/webm",
".mp4": "video/mp4",
".avi": "video/x-msvideo",
".mov": "video/quicktime",
".mkv": "video/x-matroska",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
};
+3 -3
View File
@@ -168,9 +168,9 @@ export function BingoCard({ campaign, initialGrid, currentUserNickname, isAdmin
captainSanity >= 25 ? "panic" : "lost";
const sanityLabel =
sanityStage === "calm" ? "Спокоен" :
sanityStage === "nervous" ? "Нервничает" :
sanityStage === "panic" ? "Паника!" : "Кукуха уехала!";
sanityStage === "calm" ? "Держится ещё" :
sanityStage === "nervous" ? "Кукуха свистит" :
sanityStage === "panic" ? "Паника!" : "Кукуха уехала пиздаааа!";
const sanityIcon =
sanityStage === "calm" ? "😐" :
+69 -65
View File
@@ -5,9 +5,11 @@ import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { SOUND_CATEGORIES, EMOJIS } from "@/lib/bingo-data";
import { SOUND_CATEGORIES } from "@/lib/bingo-data";
import { Badge } from "./ui/badge";
import { ResourceBrowser, DragData } from "./ResourceBrowser";
import { playSoundOnce } from "@/lib/sounds";
import { SoundPlayerBar } from "./SoundPlayerBar";
type Item = {
id: string;
@@ -25,43 +27,52 @@ type Campaign = {
gridSize: number;
};
function EmojiPicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const EMOJI_LIST = [
"😀", "😂", "🤣", "😍", "🥰", "😘", "😊", "😎", "🤩", "🥳", "🤯", "😱",
"😈", "🤡", "💀", "👻", "👽", "🤖", "🎃", "😺", "🙈", "🙉", "🙊", "💩",
"🔥", "🌊", "💥", "💫", "⭐", "🌟", "✨", "⚡", "☄️", "💧", "🧊", "🌋",
"🎉", "🎊", "🎈", "🎁", "🏆", "🥇", "💎", "🔮", "🪄", "🧨", "🔫", "⚔️",
"🛡️", "🚀", "🛸", "🚁", "⚓", "🌀", "🌈", "🌪️", "☢️", "☣️", "⚕️", "🧬",
"💉", "💊", "🩸", "🧪", "🔬", "🔭", "📡", "🎯", "🎲", "♟️", "🧩", "🎭",
"🎵", "🎶", "🎺", "📯", "🔔", "🎤", "🎧", "📢", "📣", "🔊", "🔇", "💤",
"💣", "🔪", "🪦", "⚰️", "🪤", "🧲", "🗝️", "🔑", "🔓", "🔒", "🛠️", "⛓️",
"🧹", "🪠", "🔧", "⚙️", "📦", "📀", "💿", "📹", "📸", "📷", "🖼️", "🎨",
"🍺", "🍻", "🍷", "🥃", "🍸", "🍹", "🧉", "🍕", "🍔", "🌭", "🍿", "🧀",
"🥜", "🌶️", "🍄", "🥚", "🧅", "🥕", "🥦", "🫁", "🧠", "👀", "👁️", "🫀",
"💋", "🫂", "🤝", "👍", "👎", "👊", "✊", "🤛", "🤜", "👆", "👇", "🖕",
"💪", "🦵", "🦶", "👂", "👃", "🧑‍🚀", "🧑‍🔧", "🧑‍⚕️", "🧑‍✈️", "🧑‍🏫", "🧑‍🎤", "🧑‍🍳",
"🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁", "🐮",
"🦈", "🐙", "🦑", "🐋", "🐬", "🦭", "🐊", "🦎", "🐍", "🐢", "🦖", "🦕",
"🦟", "🦗", "🐛", "🪱", "🦋", "🐌", "🐞", "🐜", "🦂", "🕷️", "🦀", "🪸",
];
useEffect(() => {
function handleClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
function EmojiPickerGrid({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const [search, setSearch] = useState("");
const filtered = search ? EMOJI_LIST.filter(e => e.includes(search)) : EMOJI_LIST;
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setOpen(!open)}
className="w-10 h-10 flex items-center justify-center text-xl rounded border border-slate-700/50 bg-slate-800/50 hover:bg-slate-700/50 cursor-pointer"
>
{value || "?"}
</button>
{open && (
<div className="absolute top-full left-0 mt-1 z-50 bg-slate-900 border border-slate-700/50 rounded-lg p-2 shadow-xl w-[280px]">
<div className="grid grid-cols-8 gap-1">
{EMOJIS.map(e => (
<button
key={e}
type="button"
onClick={() => { onChange(e); setOpen(false); }}
className={`w-8 h-8 flex items-center justify-center text-base rounded hover:bg-slate-700 cursor-pointer ${e === value ? "bg-cyan-700/50 ring-1 ring-cyan-400" : ""}`}
>
{e}
</button>
))}
</div>
</div>
)}
<div className="space-y-2">
<input
type="text"
placeholder="Search emoji..."
value={search}
onChange={e => setSearch(e.target.value)}
className="w-full bg-slate-800/60 border border-slate-700/30 rounded px-2 py-1 text-[10px] font-mono text-slate-200 placeholder:text-slate-600 outline-none focus:border-cyan-500/50"
/>
<div className="flex flex-wrap gap-1 max-h-36 overflow-y-auto">
{filtered.map(e => (
<button
key={e}
type="button"
onClick={() => onChange(e)}
className={`w-7 h-7 flex items-center justify-center text-sm rounded hover:bg-slate-700/60 cursor-pointer active:scale-90 transition-transform ${
e === value ? "bg-cyan-700/50 ring-1 ring-cyan-400" : ""
}`}
>
{e}
</button>
))}
</div>
</div>
);
}
@@ -93,15 +104,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
useEffect(() => { fetchItems(); }, [campaign.id]);
// Listen for emoji-select from ResourceBrowser EmojisTab
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent).detail;
if (detail?.emoji) setEditEmoji(detail.emoji);
};
window.addEventListener("emoji-select", handler);
return () => window.removeEventListener("emoji-select", handler);
}, []);
const updateItem = async (item: Item) => {
await fetch(`/api/campaigns/${campaign.id}/items`, {
@@ -200,10 +203,6 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
setUploading(false);
};
const playSoundOnce = (url: string) => {
try { const a = new Audio(url); a.preload = "auto"; a.volume = 0.4; a.play().catch(() => {}); } catch {}
};
// ─── Drag & Drop handlers ───────────────────────────────────────
const handleDragOver = useCallback((e: React.DragEvent, idx: number) => {
@@ -225,7 +224,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
if (!item) return;
if (data.type === "sound") {
playSoundOnce(data.url);
playSoundOnce(data.url, data.originalName);
await updateItem({ ...item, soundCategory: "custom", soundUrl: data.url });
} else if (data.type === "image") {
await updateItem({ ...item, imageUrl: data.url });
@@ -261,20 +260,22 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
</button>
</div>
</div>
<div className="flex-1 min-w-[150px]">
<label className="text-[9px] font-mono text-slate-600 uppercase">Text</label>
<Input
placeholder="Reactor explodes"
value={editText}
onChange={e => setEditText(e.target.value)}
className="font-mono text-sm"
/>
</div>
<div>
<label className="text-[9px] font-mono text-slate-600 uppercase">Emoji click to select</label>
<EmojiPickerGrid value={editEmoji} onChange={setEditEmoji} />
</div>
<div className="flex flex-wrap gap-2 items-end">
<div className="flex-1 min-w-[150px]">
<label className="text-[9px] font-mono text-slate-600 uppercase">Text</label>
<Input
placeholder="Reactor explodes"
value={editText}
onChange={e => setEditText(e.target.value)}
className="font-mono text-sm"
/>
</div>
<div>
<label className="text-[9px] font-mono text-slate-600 uppercase">Emoji</label>
<EmojiPicker value={editEmoji} onChange={setEditEmoji} />
</div>
<div className="w-32">
<label className="text-[9px] font-mono text-slate-600 uppercase">Sound</label>
<Select
@@ -304,7 +305,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
<input
ref={fileInputRef}
type="file"
accept=".ogg"
accept="audio/*,video/*"
className="hidden"
onChange={e => { const f = e.target.files?.[0]; if (f) uploadSound(f); }}
/>
@@ -320,7 +321,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
{editSoundUrl && (
<div className="flex items-center gap-1 text-[10px] font-mono text-cyan-400">
<span> sound loaded</span>
<button type="button" onClick={() => playSoundOnce(editSoundUrl)} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-slate-600/50 text-xs cursor-pointer"></button>
<button type="button" onClick={() => playSoundOnce(editSoundUrl!, "Preview")} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-slate-600/50 text-xs cursor-pointer"></button>
<button type="button" onClick={() => setEditSoundUrl(null)} className="px-1.5 py-0.5 rounded bg-slate-700/50 hover:bg-red-800/50 text-xs cursor-pointer"></button>
</div>
)}
@@ -377,7 +378,7 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
{item.soundUrl && (
<button
type="button"
onClick={e => { e.stopPropagation(); playSoundOnce(item.soundUrl!); }}
onClick={e => { e.stopPropagation(); playSoundOnce(item.soundUrl!, item.text); }}
className="text-[10px] text-cyan-500/60 hover:text-cyan-300 cursor-pointer relative z-10"
>
🔊
@@ -399,6 +400,9 @@ export function ItemEditor({ campaign }: { campaign: Campaign }) {
{/* Resource Browser dock */}
<ResourceBrowser visible={showBrowser} onClose={() => setShowBrowser(false)} />
{/* Sound playback bar */}
<SoundPlayerBar />
{/* All Items list */}
<div className="space-y-1">
<h4 className="text-[10px] font-mono text-slate-600 uppercase">All Items</h4>
+6 -79
View File
@@ -2,7 +2,7 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { useDropzone } from "react-dropzone";
import { Howl } from "howler";
import { playSoundOnce } from "@/lib/sounds";
// ─── Types ──────────────────────────────────────────────────────────
@@ -33,71 +33,7 @@ export type DragData =
| { type: "image"; url: string; originalName: string }
| { type: "emoji"; emoji: string };
// ─── Howl helper ────────────────────────────────────────────────────
const howlCache = new Map<string, Howl>();
function playPreview(url: string) {
let h = howlCache.get(url);
if (!h) {
h = new Howl({ src: [url], format: ["mp3", "ogg"], volume: 0.4, preload: true });
howlCache.set(url, h);
}
h.play();
}
// ─── Emoji Picker (inline, searchable) ──────────────────────────────
const EMOJI_LIST = [
"😀", "😂", "🤣", "😍", "🥰", "😘", "😊", "😎", "🤩", "🥳", "🤯", "😱",
"😈", "🤡", "💀", "👻", "👽", "🤖", "🎃", "😺", "🙈", "🙉", "🙊", "💩",
"🔥", "🌊", "💥", "💫", "⭐", "🌟", "✨", "⚡", "☄️", "💧", "🧊", "🌋",
"🎉", "🎊", "🎈", "🎁", "🏆", "🥇", "💎", "🔮", "🪄", "🧨", "🔫", "⚔️",
"🛡️", "🚀", "🛸", "🚁", "⚓", "🌀", "🌈", "🌪️", "☢️", "☣️", "⚕️", "🧬",
"💉", "💊", "🩸", "🧪", "🔬", "🔭", "📡", "🎯", "🎲", "♟️", "🧩", "🎭",
"🎵", "🎶", "🎺", "📯", "🔔", "🎤", "🎧", "📢", "📣", "🔊", "🔇", "💤",
"💣", "🔪", "🪦", "⚰️", "🪤", "🧲", "🗝️", "🔑", "🔓", "🔒", "🛠️", "⛓️",
"🧹", "🪠", "🔧", "⚙️", "📦", "📀", "💿", "📹", "📸", "📷", "🖼️", "🎨",
"🍺", "🍻", "🍷", "🥃", "🍸", "🍹", "🧉", "🍕", "🍔", "🌭", "🍿", "🧀",
"🥜", "🌶️", "🍄", "🥚", "🧅", "🥕", "🥦", "🫁", "🧠", "👀", "👁️", "🫀",
"💋", "🫂", "🤝", "👍", "👎", "👊", "✊", "🤛", "🤜", "👆", "👇", "🖕",
"💪", "🦵", "🦶", "👂", "👃", "🧑‍🚀", "🧑‍🔧", "🧑‍⚕️", "🧑‍✈️", "🧑‍🏫", "🧑‍🎤", "🧑‍🍳",
"🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🐯", "🦁", "🐮",
"🦈", "🐙", "🦑", "🐋", "🐬", "🦭", "🐊", "🦎", "🐍", "🐢", "🦖", "🦕",
"🦟", "🦗", "🐛", "🪱", "🦋", "🐌", "🐞", "🐜", "🦂", "🕷️", "🦀", "🪸",
];
function EmojiPickerGrid({ onSelect }: { onSelect: (emoji: string) => void }) {
const [search, setSearch] = useState("");
const filtered = search ? EMOJI_LIST.filter(e => e.includes(search)) : EMOJI_LIST;
return (
<div className="space-y-2">
<input
type="text"
placeholder="Search emoji..."
value={search}
onChange={e => setSearch(e.target.value)}
className="w-full bg-slate-800/60 border border-slate-700/30 rounded px-2 py-1.5 text-xs font-mono text-slate-200 placeholder:text-slate-600 outline-none focus:border-cyan-500/50"
/>
<div className="grid grid-cols-10 gap-1 max-h-48 overflow-y-auto">
{filtered.map(e => (
<button
key={e}
draggable
onDragStart={ev => {
ev.dataTransfer.setData("application/json", JSON.stringify({ type: "emoji", emoji: e } satisfies DragData));
}}
onClick={() => onSelect(e)}
className="w-8 h-8 flex items-center justify-center text-base rounded hover:bg-slate-700/60 cursor-pointer active:scale-90 transition-transform"
>
{e}
</button>
))}
</div>
</div>
);
}
// ─── Sounds Tab ─────────────────────────────────────────────────────
@@ -143,7 +79,7 @@ function SoundsTab() {
} catch {}
setUploading(false);
},
accept: { "audio/ogg": [".ogg"] },
accept: { "audio/*": [".mp3", ".ogg", ".wav", ".flac", ".aac", ".m4a", ".wma", ".opus", ".webm"], "video/*": [".mp4", ".avi", ".mov", ".mkv", ".webm", ".wmv", ".flv"] },
multiple: true,
});
@@ -197,7 +133,7 @@ function SoundsTab() {
<div {...getRootProps()} className="border-2 border-dashed border-slate-700/40 rounded-lg p-3 text-center cursor-pointer hover:border-cyan-600/40 transition-colors">
<input {...getInputProps()} />
<p className="text-[10px] font-mono text-slate-500">Drop OGG files here or click to upload</p>
<p className="text-[10px] font-mono text-slate-500">Drop audio/video files here or click to upload</p>
</div>
{/* Library */}
@@ -211,7 +147,7 @@ function SoundsTab() {
label={s.originalName}
duration={s.duration}
url={s.url}
onPlay={() => playPreview(s.url)}
onPlay={() => playSoundOnce(s.url, s.originalName)}
onDelete={() => deleteSound(filename)}
/>
);
@@ -244,7 +180,7 @@ function SoundsTab() {
key={r.id}
name={r.name}
duration={r.duration}
onPreview={() => r.previewUrl && playPreview(r.previewUrl)}
onPreview={() => r.previewUrl && playSoundOnce(r.previewUrl, r.name)}
onImport={() => importSound(r)}
/>
))}
@@ -389,7 +325,7 @@ function FreesoundRow({ name, duration, onPreview, onImport }: {
// ─── Main ResourceBrowser ───────────────────────────────────────────
type Tab = "sounds" | "images" | "emojis";
type Tab = "sounds" | "images";
export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClose: () => void }) {
const [tab, setTab] = useState<Tab>("sounds");
@@ -403,7 +339,6 @@ export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClos
{([
{ key: "sounds" as const, label: "🔊 Sounds" },
{ key: "images" as const, label: "🖼️ Images" },
{ key: "emojis" as const, label: "😀 Emojis" },
]).map(t => (
<button
key={t.key}
@@ -427,17 +362,9 @@ export function ResourceBrowser({ visible, onClose }: { visible: boolean; onClos
<div className="max-h-72 overflow-y-auto">
{tab === "sounds" && <SoundsTab />}
{tab === "images" && <ImagesTab />}
{tab === "emojis" && <EmojisTab />}
</div>
</div>
);
}
function EmojisTab() {
const handleSelect = (emoji: string) => {
// Dispatch a custom event so ItemEditor can pick it up
window.dispatchEvent(new CustomEvent("emoji-select", { detail: { emoji } }));
};
return <div className="p-3"><EmojiPickerGrid onSelect={handleSelect} /></div>;
}
+42
View File
@@ -0,0 +1,42 @@
"use client";
import { useState, useEffect } from "react";
import { subscribe, getPlaybackState, stopCurrent, PlaybackState } from "@/lib/player";
export function SoundPlayerBar() {
const [s, setS] = useState<PlaybackState>(getPlaybackState());
useEffect(() => {
const unsub = subscribe(setS);
return unsub;
}, []);
if (!s.isPlaying) return null;
const pct = Math.min((s.elapsed / s.duration) * 100, 100);
return (
<div className="border-t border-slate-700/30 bg-slate-950/95 px-3 py-2">
<div className="flex items-center gap-2 text-[10px] font-mono max-w-2xl mx-auto">
<span className="text-cyan-400 shrink-0">🔊</span>
<span className="text-slate-300 truncate max-w-[200px]">{s.name}</span>
<div className="flex-1 h-1.5 bg-slate-800 rounded-full overflow-hidden min-w-[80px]">
<div
className="h-full bg-cyan-500 transition-all duration-100 rounded-full"
style={{ width: `${pct}%` }}
/>
</div>
<span className="text-slate-500 shrink-0 w-16 text-right tabular-nums">
{s.elapsed.toFixed(1)}s / {s.duration.toFixed(0)}s
</span>
<button
type="button"
onClick={stopCurrent}
className="px-2 py-0.5 rounded bg-slate-800 hover:bg-red-800/60 text-slate-400 hover:text-red-300 cursor-pointer shrink-0"
>
</button>
</div>
</div>
);
}
+1 -1
View File
@@ -7,7 +7,7 @@ services:
- "80:3000"
volumes:
- ./data:/app/data
- ./uploads:/app/public/uploads
- ./uploads:/app/data/uploads
environment:
- NODE_ENV=production
- FREESOUND_API_KEY=${FREESOUND_API_KEY}
+18
View File
@@ -0,0 +1,18 @@
import { execSync } from "child_process";
/**
* Convert any audio/video file to a 6-second compressed MP3 via ffmpeg.
* Returns true on success, false on failure.
* The output file is always mp3Path (overwritten if exists).
*/
export function convertToCompressedMp3(inputPath: string, mp3Path: string): boolean {
try {
execSync(
`ffmpeg -i "${inputPath}" -t 6 -vn -codec:a libmp3lame -b:a 64k -y "${mp3Path}" 2>/dev/null`,
{ timeout: 30000 }
);
return true;
} catch {
return false;
}
}
+102
View File
@@ -0,0 +1,102 @@
import { Howl } from "howler";
export type PlaybackState = {
isPlaying: boolean;
url: string | null;
name: string | null;
elapsed: number;
duration: number;
};
type Listener = (s: PlaybackState) => void;
const MAX_SECONDS = 6;
const FADE_MS = 500;
let state: PlaybackState = {
isPlaying: false,
url: null,
name: null,
elapsed: 0,
duration: MAX_SECONDS,
};
const listeners = new Set<Listener>();
let howlInstance: Howl | null = null;
let soundId: number | null = null;
let stopTimer: ReturnType<typeof setTimeout> | null = null;
let progressTimer: ReturnType<typeof setInterval> | null = null;
function emit() {
listeners.forEach(fn => fn(state));
}
function resetTimers() {
if (stopTimer) clearTimeout(stopTimer);
if (progressTimer) clearInterval(progressTimer);
stopTimer = null;
progressTimer = null;
}
function stopSound() {
if (howlInstance && soundId !== null) {
howlInstance.stop(soundId);
}
howlInstance = null;
soundId = null;
}
export function getPlaybackState(): PlaybackState {
return state;
}
export function subscribe(fn: Listener): () => void {
listeners.add(fn);
return () => listeners.delete(fn);
}
export function playUrl(url: string, name?: string) {
stopCurrent();
const displayName = name || url.split("/").pop() || url;
howlInstance = new Howl({
src: [url],
format: url.endsWith(".mp3") ? ["mp3"] : url.endsWith(".ogg") ? ["ogg"] : ["mp3", "ogg"],
volume: 0.4,
});
soundId = howlInstance.play();
state = { isPlaying: true, url, name: displayName, elapsed: 0, duration: MAX_SECONDS };
emit();
// Progress tick
progressTimer = setInterval(() => {
if (howlInstance && soundId !== null) {
const seek = howlInstance.seek(soundId) as number;
state = { ...state, elapsed: seek };
emit();
}
}, 100);
// Cap at MAX_SECONDS with fadeout
const fadeStart = (MAX_SECONDS - FADE_MS / 1000) * 1000;
stopTimer = setTimeout(() => {
if (howlInstance && soundId !== null) {
try { howlInstance.fade(0.4, 0, FADE_MS, soundId); } catch {}
setTimeout(() => stopCurrent(), FADE_MS);
}
}, fadeStart);
// Natural end
howlInstance.on("end", () => stopCurrent());
}
export function stopCurrent() {
stopSound();
resetTimers();
state = { isPlaying: false, url: null, name: null, elapsed: 0, duration: MAX_SECONDS };
emit();
}
+22 -7
View File
@@ -1,3 +1,5 @@
import { playUrl, stopCurrent } from "@/lib/player";
let audioCtx: AudioContext | null = null;
function getCtx(): AudioContext {
@@ -107,15 +109,28 @@ export function playChaosRiser() {
});
}
export function playSoundUrl(url: string) {
try {
const audio = new Audio(url);
audio.preload = "auto";
audio.volume = 0.4;
audio.play().catch(() => {});
} catch {}
// ─── URL playback via shared player ──────────────────────────────
/**
* Play a sound file URL (MP3/OGG). Goes through the shared player,
* which caps at 6s with fadeout and shows playback UI.
*/
export function playSoundUrl(url: string, name?: string) {
playUrl(url, name);
}
/**
* One-shot play with a display name. Same underlying player.
*/
export function playSoundOnce(url: string, name?: string) {
playUrl(url, name);
}
/**
* Stop current playback immediately.
*/
export { stopCurrent, getPlaybackState, subscribe } from "@/lib/player";
export function playSound(category: string, soundUrl?: string | null) {
if (soundUrl) {
playSoundUrl(soundUrl);