1 Commits
Author SHA1 Message Date
remco b6be0baecb chore(deps): update All dependencies
CI / check (pull_request) Failing after 12s
CI / release (pull_request) Skipped
CI / deploy (pull_request) Skipped
2026-08-06 14:00:34 +00:00
28 changed files with 221 additions and 574 deletions

No files matched your search

+1 -1
View File
@@ -82,7 +82,7 @@
"pino-pretty": "^13.1.3", "pino-pretty": "^13.1.3",
"postcss": "^8.5.26", "postcss": "^8.5.26",
"tailwindcss": "^4.3.3", "tailwindcss": "^4.3.3",
"tsx": "^4.23.10", "tsx": "^4.23.9",
"typescript": "^7.0.2", "typescript": "^7.0.2",
"vite": "8.2.1", "vite": "8.2.1",
"vitest": "4.1.10" "vitest": "4.1.10"
+18 -18
View File
@@ -192,17 +192,17 @@ importers:
specifier: ^4.3.3 specifier: ^4.3.3
version: 4.3.3 version: 4.3.3
tsx: tsx:
specifier: ^4.23.10 specifier: ^4.23.9
version: 4.23.10 version: 4.23.9
typescript: typescript:
specifier: ^7.0.2 specifier: ^7.0.2
version: 7.0.2 version: 7.0.2
vite: vite:
specifier: 8.2.1 specifier: 8.2.1
version: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]) version: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].9)([email protected])
vitest: vitest:
specifier: 4.1.10 specifier: 4.1.10
version: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])) version: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected]))
packages: packages:
@@ -2968,13 +2968,13 @@ packages:
[email protected]: [email protected]:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
[email protected].10: [email protected].8:
resolution: {integrity: sha512-0Vb9eKU47njkxv/6B8CRZRDsxNDT/Pz+BIU+M5jw7xL3TdzAjSxlZUxu0xFL/kLpaG3sHZ0LH2wbK1T1yo7CUQ==} resolution: {integrity: sha512-8W675THjbzfFmLOQzjDBIBna+WjqMGIxmSZ1mMc1+o9qoVsEuAgQu5j5ueLhau8inOkDu9OslVg0FmfBs1RIHw==}
engines: {node: '>=18.0.0'} engines: {node: '>=18.0.0'}
hasBin: true hasBin: true
[email protected].8: [email protected].9:
resolution: {integrity: sha512-8W675THjbzfFmLOQzjDBIBna+WjqMGIxmSZ1mMc1+o9qoVsEuAgQu5j5ueLhau8inOkDu9OslVg0FmfBs1RIHw==} resolution: {integrity: sha512-6q8uTORRGauQVjqMQnKUucLFoeXZAfw6zKvG35GLbdKWbLdeOtZ3H4mhyA5mxuUd2o2cRTskhj59nLLQseUvUw==}
engines: {node: '>=18.0.0'} engines: {node: '>=18.0.0'}
hasBin: true hasBin: true
@@ -4252,7 +4252,7 @@ snapshots:
obug: 2.1.4 obug: 2.1.4
std-env: 4.2.0 std-env: 4.2.0
tinyrainbow: 3.1.1 tinyrainbow: 3.1.1
vitest: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])) vitest: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected]))
'@vitest/[email protected]': '@vitest/[email protected]':
dependencies: dependencies:
@@ -4263,13 +4263,13 @@ snapshots:
chai: 6.2.2 chai: 6.2.2
tinyrainbow: 3.1.1 tinyrainbow: 3.1.1
'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]))': '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected]))':
dependencies: dependencies:
'@vitest/spy': 4.1.10 '@vitest/spy': 4.1.10
estree-walker: 3.0.3 estree-walker: 3.0.3
magic-string: 0.30.21 magic-string: 0.30.21
optionalDependencies: optionalDependencies:
vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]) vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].9)([email protected])
'@vitest/[email protected]': '@vitest/[email protected]':
dependencies: dependencies:
@@ -5230,13 +5230,13 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected].10: [email protected].8:
dependencies: dependencies:
esbuild: 0.25.12 esbuild: 0.25.12
optionalDependencies: optionalDependencies:
fsevents: 2.3.3 fsevents: 2.3.3
[email protected].8: [email protected].9:
dependencies: dependencies:
esbuild: 0.25.12 esbuild: 0.25.12
optionalDependencies: optionalDependencies:
@@ -5300,7 +5300,7 @@ snapshots:
[email protected]: {} [email protected]: {}
[email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]): [email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected]):
dependencies: dependencies:
lightningcss: 1.33.0 lightningcss: 1.33.0
picomatch: 4.0.5 picomatch: 4.0.5
@@ -5312,13 +5312,13 @@ snapshots:
esbuild: 0.25.12 esbuild: 0.25.12
fsevents: 2.3.3 fsevents: 2.3.3
jiti: 2.7.0 jiti: 2.7.0
tsx: 4.23.10 tsx: 4.23.9
yaml: 2.9.0 yaml: 2.9.0
[email protected](@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])): [email protected](@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected])):
dependencies: dependencies:
'@vitest/expect': 4.1.10 '@vitest/expect': 4.1.10
'@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])) '@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected])([email protected])([email protected].9)([email protected]))
'@vitest/pretty-format': 4.1.10 '@vitest/pretty-format': 4.1.10
'@vitest/runner': 4.1.10 '@vitest/runner': 4.1.10
'@vitest/snapshot': 4.1.10 '@vitest/snapshot': 4.1.10
@@ -5335,7 +5335,7 @@ snapshots:
tinyexec: 1.3.0 tinyexec: 1.3.0
tinyglobby: 0.2.17 tinyglobby: 0.2.17
tinyrainbow: 3.1.1 tinyrainbow: 3.1.1
vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]) vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].9)([email protected])
why-is-node-running: 2.3.0 why-is-node-running: 2.3.0
optionalDependencies: optionalDependencies:
'@types/node': 26.1.2 '@types/node': 26.1.2
+16 -17
View File
@@ -4,7 +4,6 @@ import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache"; import { revalidatePath } from "next/cache";
import { requirePermission } from "@/lib/admin/guard"; import { requirePermission } from "@/lib/admin/guard";
import { db, RadioBanners, RadioRanks, WebsiteSetting } from "@/lib/db"; import { db, RadioBanners, RadioRanks, WebsiteSetting } from "@/lib/db";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { siteSettings } from "@/lib/services/site-settings"; import { siteSettings } from "@/lib/services/site-settings";
@@ -51,8 +50,8 @@ export async function saveRadioSetting(formData: FormData): Promise<void> {
.values({ key, value, comment: comment || null }) .values({ key, value, comment: comment || null })
.onDuplicateKeyUpdate({ set: { value } }); .onDuplicateKeyUpdate({ set: { value } });
siteSettings.reload(); siteSettings.reload();
} catch (err) { } catch {
logger.error("Failed to save radio setting", { err, key }); // DB unavailable — fail soft so the action does not throw.
} }
revalidatePath("/admin/radio/settings"); revalidatePath("/admin/radio/settings");
} }
@@ -82,8 +81,8 @@ export async function saveRadioSettings(formData: FormData): Promise<void> {
}), }),
); );
siteSettings.reload(); siteSettings.reload();
} catch (err) { } catch {
logger.error("Failed to bulk-save radio settings", { err, keys }); // Fail soft.
} }
revalidatePath("/admin/radio/settings"); revalidatePath("/admin/radio/settings");
} }
@@ -115,8 +114,8 @@ export async function createRadioBanner(formData: FormData): Promise<void> {
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}); });
} catch (err) { } catch {
logger.error("Failed to create radio banner", { err, imagePath }); // Fail soft.
} }
revalidatePath("/admin/radio/banners"); revalidatePath("/admin/radio/banners");
} }
@@ -148,8 +147,8 @@ export async function updateRadioBanner(formData: FormData): Promise<void> {
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(eq(RadioBanners.id, id)); .where(eq(RadioBanners.id, id));
} catch (err) { } catch {
logger.error("Failed to update radio banner", { err, id: String(id) }); // Row may be gone; ignore.
} }
revalidatePath("/admin/radio/banners"); revalidatePath("/admin/radio/banners");
} }
@@ -160,8 +159,8 @@ export async function deleteRadioBanner(formData: FormData): Promise<void> {
if (id === null) return; if (id === null) return;
try { try {
await db.delete(RadioBanners).where(eq(RadioBanners.id, id)); await db.delete(RadioBanners).where(eq(RadioBanners.id, id));
} catch (err) { } catch {
logger.error("Failed to delete radio banner", { err, id: String(id) }); // Already deleted; ignore.
} }
revalidatePath("/admin/radio/banners"); revalidatePath("/admin/radio/banners");
} }
@@ -187,8 +186,8 @@ export async function createRadioRank(formData: FormData): Promise<void> {
createdAt: now, createdAt: now,
updatedAt: now, updatedAt: now,
}); });
} catch (err) { } catch {
logger.error("Failed to create radio rank", { err, name }); // Fail soft.
} }
revalidatePath("/admin/radio/ranks"); revalidatePath("/admin/radio/ranks");
} }
@@ -215,8 +214,8 @@ export async function updateRadioRank(formData: FormData): Promise<void> {
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(eq(RadioRanks.id, id)); .where(eq(RadioRanks.id, id));
} catch (err) { } catch {
logger.error("Failed to update radio rank", { err, id: String(id) }); // Row may be gone; ignore.
} }
revalidatePath("/admin/radio/ranks"); revalidatePath("/admin/radio/ranks");
} }
@@ -227,8 +226,8 @@ export async function deleteRadioRank(formData: FormData): Promise<void> {
if (id === null) return; if (id === null) return;
try { try {
await db.delete(RadioRanks).where(eq(RadioRanks.id, id)); await db.delete(RadioRanks).where(eq(RadioRanks.id, id));
} catch (err) { } catch {
logger.error("Failed to delete radio rank", { err, id: String(id) }); // Already deleted; ignore.
} }
revalidatePath("/admin/radio/ranks"); revalidatePath("/admin/radio/ranks");
} }
+3 -3
View File
@@ -77,9 +77,9 @@ export async function updateSetting(formData: FormData): Promise<void> {
); );
if (!key) return; if (!key) return;
await db await db
.insert(WebsiteSetting) .update(WebsiteSetting)
.values({ key, value }) .set({ value })
.onDuplicateKeyUpdate({ set: { value } }); .where(eq(WebsiteSetting.key, key));
await siteSettings.reload(); await siteSettings.reload();
bustGamedataCachesIfNeeded(key); bustGamedataCachesIfNeeded(key);
revalidatePath("/admin/settings"); revalidatePath("/admin/settings");
+2 -17
View File
@@ -2,8 +2,8 @@
import { Pencil } from "lucide-react"; import { Pencil } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { deleteCatalogPage, toggleCatalogPage } from "@/actions/catalog"; import { toggleCatalogPage } from "@/actions/catalog";
import { deleteBcTreePage, toggleBcPage } from "@/actions/catalog-bc"; import { toggleBcPage } from "@/actions/catalog-bc";
import { DataTable } from "@/components/admin/data-table"; import { DataTable } from "@/components/admin/data-table";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -175,20 +175,6 @@ export function CatalogTable({
}, },
]; ];
async function handleBulkAction(action: string, ids: (number | string)[]) {
if (action !== "delete" || ids.length === 0) return;
for (const id of ids) {
const numId = typeof id === "string" ? Number(id) : id;
if (Number.isInteger(numId) && numId > 0) {
run(() =>
isBc
? deleteBcTreePage({ pageId: numId, mode: "reparent" })
: deleteCatalogPage({ id: numId }),
);
}
}
}
return ( return (
<DataTable <DataTable
data={data} data={data}
@@ -205,7 +191,6 @@ export function CatalogTable({
] ]
: undefined : undefined
} }
onBulkAction={canEdit ? handleBulkAction : undefined}
/> />
); );
} }
@@ -15,7 +15,6 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@@ -371,7 +370,6 @@ interface FurniGridProps {
const PER_PAGE = 50; const PER_PAGE = 50;
function FurniGrid({ source }: FurniGridProps) { function FurniGrid({ source }: FurniGridProps) {
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
const [activeSearch, setActiveSearch] = useState(""); const [activeSearch, setActiveSearch] = useState("");
const [items, setItems] = useState<FurniItem[]>([]); const [items, setItems] = useState<FurniItem[]>([]);
@@ -556,12 +554,13 @@ function FurniGrid({ source }: FurniGridProps) {
toast.info("Nothing to clone — everything is already present"); toast.info("Nothing to clone — everything is already present");
return; return;
} }
const confirmed = await confirm({ if (
title: "Clone All Furni", !window.confirm(
description: `Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`, `Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
confirmLabel: "Clone All", )
}); ) {
if (!confirmed) return; return;
}
batchAbortRef.current?.abort(); batchAbortRef.current?.abort();
const abort = new AbortController(); const abort = new AbortController();
batchAbortRef.current = abort; batchAbortRef.current = abort;
@@ -615,7 +614,6 @@ function FurniGrid({ source }: FurniGridProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{confirmDialog}
{/* Stats bar */} {/* Stats bar */}
{stats && ( {stats && (
<div className="flex items-center gap-3 flex-wrap"> <div className="flex items-center gap-3 flex-wrap">
@@ -396,6 +396,14 @@ export function ImportFurniClient({ source }: { source: FurniImportSource }) {
} }
}, [statusFilter, activeSearch, fetchItems]); }, [statusFilter, activeSearch, fetchItems]);
function _doSearch(e?: React.FormEvent) {
e?.preventDefault();
setActiveSearch(searchTerm);
setPage(1);
fetchItems(searchTerm, 1, statusFilter);
}
void _doSearch;
function goPage(p: number) { function goPage(p: number) {
setPage(p); setPage(p);
fetchItems(activeSearch, p, statusFilter); fetchItems(activeSearch, p, statusFilter);
@@ -215,7 +215,7 @@ export function NitroEditorDialog({
return; return;
} }
toast.success("Nitro metadata saved"); toast.success("Nitro metadata salvato");
setMetadata(metadataToSave); setMetadata(metadataToSave);
setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave))); setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave)));
setOriginalFlags({ ...flags }); setOriginalFlags({ ...flags });
@@ -339,7 +339,7 @@ export function NitroEditorDialog({
{colorCount > 0 && ( {colorCount > 0 && (
<Badge variant="outline" className="text-[10px] gap-1"> <Badge variant="outline" className="text-[10px] gap-1">
<Palette className="w-2.5 h-2.5" /> <Palette className="w-2.5 h-2.5" />
{colorCount} colors {colorCount} colori
</Badge> </Badge>
)} )}
{animCount > 0 && ( {animCount > 0 && (
@@ -392,7 +392,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4"> <section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<Ruler className="w-4 h-4 text-muted-foreground" /> <Ruler className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Dimensions</h3> <h3 className="text-sm font-medium">Dimensioni</h3>
</div> </div>
<div className="grid grid-cols-3 gap-3"> <div className="grid grid-cols-3 gap-3">
<div> <div>
@@ -400,7 +400,7 @@ export function NitroEditorDialog({
htmlFor="dim-x" htmlFor="dim-x"
className="text-xs text-muted-foreground" className="text-xs text-muted-foreground"
> >
X (width) X (larghezza)
</Label> </Label>
<Input <Input
id="dim-x" id="dim-x"
@@ -432,7 +432,7 @@ export function NitroEditorDialog({
htmlFor="dim-z" htmlFor="dim-z"
className="text-xs text-muted-foreground" className="text-xs text-muted-foreground"
> >
Z (height) Z (altezza)
</Label> </Label>
<Input <Input
id="dim-z" id="dim-z"
@@ -451,7 +451,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4"> <section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<MousePointerClick className="w-4 h-4 text-muted-foreground" /> <MousePointerClick className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Interaction</h3> <h3 className="text-sm font-medium">Interazione</h3>
</div> </div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors"> <div className="flex items-center justify-between rounded-md border px-3 py-2 hover:bg-muted/50 transition-colors">
@@ -489,9 +489,9 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4"> <section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<Compass className="w-4 h-4 text-muted-foreground" /> <Compass className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Directions</h3> <h3 className="text-sm font-medium">Direzioni</h3>
<span className="text-xs text-muted-foreground ml-auto"> <span className="text-xs text-muted-foreground ml-auto">
{directions.length} active {directions.length} attive
</span> </span>
</div> </div>
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
@@ -541,7 +541,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4"> <section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3">
<Eye className="w-4 h-4 text-muted-foreground" /> <Eye className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Types</h3> <h3 className="text-sm font-medium">Tipo</h3>
</div> </div>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<div> <div>
@@ -663,7 +663,7 @@ export function NitroEditorDialog({
<Palette className="w-4 h-4 text-muted-foreground" /> <Palette className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Colori</h3> <h3 className="text-sm font-medium">Colori</h3>
<Badge variant="secondary" className="text-[10px] ml-auto"> <Badge variant="secondary" className="text-[10px] ml-auto">
{colorCount} colors {colorCount} varianti
</Badge> </Badge>
</div> </div>
<div className="space-y-3"> <div className="space-y-3">
@@ -672,7 +672,7 @@ export function NitroEditorDialog({
<div key={colorId} className="rounded-md border p-3"> <div key={colorId} className="rounded-md border p-3">
<div className="flex items-center gap-2 mb-2"> <div className="flex items-center gap-2 mb-2">
<span className="text-xs font-medium"> <span className="text-xs font-medium">
Color Variant #{colorId} Variante #{colorId}
</span> </span>
{/* Color preview dots */} {/* Color preview dots */}
<div className="flex gap-1 ml-auto"> <div className="flex gap-1 ml-auto">
@@ -784,7 +784,7 @@ export function NitroEditorDialog({
variant="secondary" variant="secondary"
className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]" className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]"
> >
Unsaved changes Modifiche non salvate
</Badge> </Badge>
)} )}
<div className="flex-1" /> <div className="flex-1" />
+13 -41
View File
@@ -24,7 +24,6 @@ import {
deleteRoomItem, deleteRoomItem,
roomRconAction, roomRconAction,
} from "@/actions/rooms"; } from "@/actions/rooms";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
@@ -92,7 +91,6 @@ function isWallType(t: string) {
export function FurniClient({ room, items = [], canEdit }: Props) { export function FurniClient({ room, items = [], canEdit }: Props) {
const { run, isPending } = useServerAction(); const { run, isPending } = useServerAction();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [view, setView] = useState<View>("flat"); const [view, setView] = useState<View>("flat");
@@ -233,44 +231,29 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
setSelected(next); setSelected(next);
} }
async function handleRcon(action: "reload" | "kick") { function handleRcon(action: "reload" | "kick") {
if (action === "kick") { if (action === "kick" && !confirm("Kick all users from this room?")) return;
const ok = await confirm({
title: "Kick Users",
description: "Kick all users from this room?",
confirmLabel: "Kick",
variant: "danger",
});
if (!ok) return;
}
run(() => roomRconAction({ roomId: room.id, action }), { run(() => roomRconAction({ roomId: room.id, action }), {
successMessage: successMessage:
action === "reload" ? "Room reloaded" : "All users kicked", action === "reload" ? "Room reloaded" : "All users kicked",
}); });
} }
async function handleDelete(itemId: number, name: string) { function handleDelete(itemId: number, name: string) {
const ok = await confirm({ if (!confirm(`Delete "${name}" (#${itemId}) from this room?`)) return;
title: "Delete Item",
description: `Delete "${name}" (#${itemId}) from this room?`,
confirmLabel: "Delete",
variant: "danger",
});
if (!ok) return;
run(() => deleteRoomItem({ roomId: room.id, itemId }), { run(() => deleteRoomItem({ roomId: room.id, itemId }), {
successMessage: "Item deleted", successMessage: "Item deleted",
}); });
} }
async function handleBulkDelete() { function handleBulkDelete() {
if (selected.size === 0) return; if (selected.size === 0) return;
const ok = await confirm({ if (
title: "Delete Items", !confirm(
description: `Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`, `Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`,
confirmLabel: "Delete", )
variant: "danger", )
}); return;
if (!ok) return;
run( run(
() => () =>
bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }), bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }),
@@ -281,18 +264,8 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
); );
} }
async function handleDeleteGroup( function handleDeleteGroup(_baseId: number, ids: number[], name: string) {
_baseId: number, if (!confirm(`Delete all ${ids.length} "${name}" from this room?`)) return;
ids: number[],
name: string,
) {
const ok = await confirm({
title: "Delete Items",
description: `Delete all ${ids.length} "${name}" from this room?`,
confirmLabel: "Delete",
variant: "danger",
});
if (!ok) return;
run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: ids }), { run(() => bulkDeleteRoomItems({ roomId: room.id, itemIds: ids }), {
successMessage: `${ids.length} item(s) deleted`, successMessage: `${ids.length} item(s) deleted`,
}); });
@@ -303,7 +276,6 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
return ( return (
<div className="space-y-6"> <div className="space-y-6">
{confirmDialog}
{/* ── Header ─────────────────────────────────────────── */} {/* ── Header ─────────────────────────────────────────── */}
<div className="flex flex-wrap items-center justify-between gap-4"> <div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
+6 -12
View File
@@ -12,7 +12,6 @@ import {
} from "lucide-react"; } from "lucide-react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { deleteRoom, roomRconAction, updateRoom } from "@/actions/rooms"; import { deleteRoom, roomRconAction, updateRoom } from "@/actions/rooms";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -64,17 +63,13 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
}); });
} }
const { confirm, dialog: confirmDialog } = useConfirmDialog(); function handleDelete() {
if (
async function handleDelete() { !confirm(
const ok = await confirm({
title: "Delete Room",
description:
"Are you sure you want to delete this room? This cannot be undone.", "Are you sure you want to delete this room? This cannot be undone.",
confirmLabel: "Delete", )
variant: "danger", )
}); return;
if (!ok) return;
run(() => deleteRoom({ id: room.id }), { redirectTo: "/admin/rooms" }); run(() => deleteRoom({ id: room.id }), { redirectTo: "/admin/rooms" });
} }
@@ -87,7 +82,6 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{confirmDialog}
<div className="grid gap-6 lg:grid-cols-2"> <div className="grid gap-6 lg:grid-cols-2">
{/* Edit Form */} {/* Edit Form */}
<Card> <Card>
+1 -1
View File
@@ -271,7 +271,7 @@ export function SoundsClient({
onEnded={() => setPlayingId(null)} onEnded={() => setPlayingId(null)}
onError={() => onError={() =>
toast.error( toast.error(
`Failed to play "${s.code}.mp3" from ${baseUrl}.`, `Impossibile riprodurre "${s.code}.mp3" da ${baseUrl}.`,
) )
} }
/> />
+2 -2
View File
@@ -100,7 +100,7 @@ export function TraxPlayer({
const AudioCtor = window.AudioContext; const AudioCtor = window.AudioContext;
if (!AudioCtor) { if (!AudioCtor) {
toast.error("Web Audio API is not supported by this browser."); toast.error("Web Audio API non supportata da questo browser.");
setStatus("error"); setStatus("error");
return; return;
} }
@@ -137,7 +137,7 @@ export function TraxPlayer({
if (failed > 0) { if (failed > 0) {
toast.warning( toast.warning(
`${failed}/${uniqueIds.length} samples failed to load — playback may have gaps.`, `${failed}/${uniqueIds.length} sample non caricati — la riproduzione potrebbe avere buchi.`,
); );
} }
if (failed === uniqueIds.length) { if (failed === uniqueIds.length) {
+5 -7
View File
@@ -1,4 +1,4 @@
import { and, asc, count, like, or, type SQL, sql } from "drizzle-orm"; import { and, asc, count, like, or, type SQL } from "drizzle-orm";
import { ExternalLink } from "lucide-react"; import { ExternalLink } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { getTranslations } from "next-intl/server"; import { getTranslations } from "next-intl/server";
@@ -34,12 +34,10 @@ export default async function EmulatorTranslationsPage({
const perPage = Math.min(Math.max(parseInt(sp.perPage || "50", 10), 10), 200); const perPage = Math.min(Math.max(parseInt(sp.perPage || "50", 10), 10), 200);
const page = Math.max(parseInt(sp.page || "1", 10), 1); const page = Math.max(parseInt(sp.page || "1", 10), 1);
const patternFilters = const patternFilters = or(
or( ...TRANSLATION_KEY_PATTERNS.map((p) => like(EmulatorSettings.key, `${p}%`)),
...TRANSLATION_KEY_PATTERNS.map((p) => );
like(EmulatorSettings.key, `${p}%`), if (!patternFilters) throw new Error("No emulator translation key patterns");
),
) ?? sql`1=0`;
const conditions: SQL[] = [patternFilters]; const conditions: SQL[] = [patternFilters];
if (group) conditions.push(like(EmulatorSettings.key, `${group}.%`)); if (group) conditions.push(like(EmulatorSettings.key, `${group}.%`));
+1 -1
View File
@@ -2,7 +2,7 @@ import { sql } from "drizzle-orm";
import { withAdmin } from "@/lib/api-handler"; import { withAdmin } from "@/lib/api-handler";
import { apiError } from "@/lib/api-response"; import { apiError } from "@/lib/api-response";
import { db } from "@/lib/db"; import { db } from "@/lib/db";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permission-slugs";
const VALID_REPORTS = new Set(["registrations", "online-by-hour", "economy"]); const VALID_REPORTS = new Set(["registrations", "online-by-hour", "economy"]);
+9 -26
View File
@@ -1,34 +1,17 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { fetchOpsHealth } from "@/lib/admin/ops-health"; import { fetchOpsHealth } from "@/lib/admin/ops-health";
import { withAdmin } from "@/lib/api-handler"; import { withAdmin } from "@/lib/api-handler";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => { export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => {
try { const health = await fetchOpsHealth();
const health = await fetchOpsHealth();
return NextResponse.json({ return NextResponse.json({
database: health.dbOk, database: health.dbOk,
dbLatency: health.dbLatencyMs, dbLatency: health.dbLatencyMs,
redis: health.redisOk, redis: health.redisOk,
emulator: health.emulatorOk, emulator: health.emulatorOk,
onlineUsers: health.onlineUsers, onlineUsers: health.onlineUsers,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
}); });
} catch (err) {
logger.error("Health check failed", { err });
return NextResponse.json(
{
database: false,
dbLatency: null,
redis: false,
emulator: false,
onlineUsers: 0,
timestamp: new Date().toISOString(),
error: "Health check partially failed",
},
{ status: 503 },
);
}
}); });
+4 -5
View File
@@ -1,5 +1,4 @@
import { withAdmin } from "@/lib/api-handler"; import { withAdmin } from "@/lib/api-handler";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { runCatalogAudit } from "@/lib/services/catalog-audit"; import { runCatalogAudit } from "@/lib/services/catalog-audit";
@@ -33,8 +32,8 @@ export const POST = withAdmin(
applySql = body.applySql === true; applySql = body.applySql === true;
repairFurniData = body.repairFurniData === true; repairFurniData = body.repairFurniData === true;
repairStructure = body.repairStructure === true; repairStructure = body.repairStructure === true;
} catch (err) { } catch {
logger.warn("Failed to parse audit request body", { err }); /* no body */
} }
const stream = new ReadableStream({ const stream = new ReadableStream({
@@ -65,8 +64,8 @@ export const POST = withAdmin(
try { try {
controller.close(); controller.close();
} catch (err) { } catch {
logger.warn("Failed to close audit SSE stream", { err }); /* ignore */
} }
}, },
}); });
@@ -7,15 +7,6 @@ import { getSource } from "@/lib/services/clone-sources";
// In-process cache of extracted icons, keyed by source+classname. // In-process cache of extracted icons, keyed by source+classname.
// null = known-missing (don't refetch the bundle every render). // null = known-missing (don't refetch the bundle every render).
const iconCache = new Map<string, Buffer | null>(); const iconCache = new Map<string, Buffer | null>();
const MAX_ICON_CACHE_SIZE = 500;
function pruneIconCache() {
while (iconCache.size > MAX_ICON_CACHE_SIZE) {
const oldest = iconCache.keys().next().value;
if (oldest === undefined) break;
iconCache.delete(oldest);
}
}
// GET ?source=<id>&classname=<cn> // GET ?source=<id>&classname=<cn>
// Fetches the source's .nitro bundle and returns the embedded furni icon as a // Fetches the source's .nitro bundle and returns the embedded furni icon as a
@@ -48,7 +39,6 @@ export const GET = withAdmin(
} }
icon = extractFurniIconPng(Buffer.from(await res.arrayBuffer())); icon = extractFurniIconPng(Buffer.from(await res.arrayBuffer()));
iconCache.set(cacheKey, icon); iconCache.set(cacheKey, icon);
pruneIconCache();
} catch { } catch {
iconCache.set(cacheKey, null); iconCache.set(cacheKey, null);
return apiError("Failed to fetch bundle", 502); return apiError("Failed to fetch bundle", 502);
+12 -18
View File
@@ -76,15 +76,8 @@ export const POST = withAdmin(
{ permission: PERMS.ASSETS_IMPORT }, { permission: PERMS.ASSETS_IMPORT },
async (request, ctx) => { async (request, ctx) => {
const body = await request.json(); const body = await request.json();
const { const { name, furnidataUrl, nitroBaseUrl, iconBaseUrl, hotel, id } =
name, body as Record<string, string>;
furnidataUrl,
nitroBaseUrl,
iconBaseUrl,
hotel,
id,
sourceSwfBaseUrl,
} = body as Record<string, string>;
const isHttps = (u: string) => { const isHttps = (u: string) => {
try { try {
@@ -96,21 +89,22 @@ export const POST = withAdmin(
if (!name?.trim()) return apiError("name is required", 400); if (!name?.trim()) return apiError("name is required", 400);
if (!furnidataUrl?.trim()) return apiError("furnidataUrl is required", 400); if (!furnidataUrl?.trim()) return apiError("furnidataUrl is required", 400);
if (!nitroBaseUrl?.trim()) return apiError("nitroBaseUrl is required", 400);
const normalized = (u: string | undefined) => if (!iconBaseUrl?.trim()) return apiError("iconBaseUrl is required", 400);
(u ?? "").trim().replace(/\/+$/, ""); if (
!isHttps(furnidataUrl) ||
if (!isHttps(furnidataUrl)) !isHttps(nitroBaseUrl) ||
return apiError("furnidataUrl must be a valid https:// URL", 400); !isHttps(iconBaseUrl)
)
return apiError("Source URLs must be valid https:// URLs", 400);
const entry = await upsertSource({ const entry = await upsertSource({
id, id,
name, name,
furnidataUrl, furnidataUrl,
nitroBaseUrl: normalized(nitroBaseUrl), nitroBaseUrl,
iconBaseUrl: normalized(iconBaseUrl), iconBaseUrl,
hotel: hotel ?? "", hotel: hotel ?? "",
sourceSwfBaseUrl: normalized(sourceSwfBaseUrl),
}); });
logAudit({ logAudit({
@@ -2,7 +2,6 @@ import { withAdmin } from "@/lib/api-handler";
import { apiError } from "@/lib/api-response"; import { apiError } from "@/lib/api-response";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { logAudit } from "@/lib/services/audit"; import { logAudit } from "@/lib/services/audit";
import { getSource } from "@/lib/services/clone-sources";
import { appendFurniEntriesBatch } from "@/lib/services/furni-data"; import { appendFurniEntriesBatch } from "@/lib/services/furni-data";
import { import {
ensureDirectories, ensureDirectories,
@@ -32,16 +31,9 @@ export const POST = withAdmin(
const body = await request.json(); const body = await request.json();
const rawItems: BatchItem[] = body.items || []; const rawItems: BatchItem[] = body.items || [];
const concurrency = Math.min(Math.max(body.concurrency || 3, 1), 5); const concurrency = Math.min(Math.max(body.concurrency || 3, 1), 5);
const sourceId: string | undefined = body.sourceId;
if (rawItems.length === 0) return apiError("No items to import", 400); if (rawItems.length === 0) return apiError("No items to import", 400);
// Look up clone source for SWF/nitro/icon URL fallbacks
let source: Awaited<ReturnType<typeof getSource>> | null = null;
if (sourceId) {
source = await getSource(sourceId);
}
// Deduplicate by (spriteId, classname) to avoid concurrent INSERT races on // Deduplicate by (spriteId, classname) to avoid concurrent INSERT races on
// items_base.id when the same item is listed twice in the request body. // items_base.id when the same item is listed twice in the request body.
const seen = new Set<string>(); const seen = new Set<string>();
@@ -102,9 +94,6 @@ export const POST = withAdmin(
revision: item.revision ?? 0, revision: item.revision ?? 0,
category: item.category ?? "unknown", category: item.category ?? "unknown",
skipFurniDataWrite: true, skipFurniDataWrite: true,
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl,
iconBaseUrl: source?.iconBaseUrl,
onProgress: (status: string) => { onProgress: (status: string) => {
send({ send({
type: "item_progress", type: "item_progress",
+1 -27
View File
@@ -6,7 +6,6 @@ import { apiError, apiOk } from "@/lib/api-response";
import { CatalogPages, db, ItemsBase } from "@/lib/db"; import { CatalogPages, db, ItemsBase } from "@/lib/db";
import { PERMS } from "@/lib/permissions"; import { PERMS } from "@/lib/permissions";
import { logAudit } from "@/lib/services/audit"; import { logAudit } from "@/lib/services/audit";
import { getSource } from "@/lib/services/clone-sources";
import { getFurniAssetDirs } from "@/lib/services/furni-asset-dirs"; import { getFurniAssetDirs } from "@/lib/services/furni-asset-dirs";
import { import {
autoPriceFurni, autoPriceFurni,
@@ -18,7 +17,6 @@ import {
ensureDirectories, ensureDirectories,
IMPORTED_PAGE_CAPTION_SAVE, IMPORTED_PAGE_CAPTION_SAVE,
importSingleFurni, importSingleFurni,
resetCatalogPageCache,
} from "@/lib/services/furni-import"; } from "@/lib/services/furni-import";
import { getOfficialHabboFurnidata } from "@/lib/services/habbo-furnidata-cache"; import { getOfficialHabboFurnidata } from "@/lib/services/habbo-furnidata-cache";
import { listFurniture } from "@/lib/services/habbofurni"; import { listFurniture } from "@/lib/services/habbofurni";
@@ -262,10 +260,6 @@ export const POST = withAdmin(
// ── Batch import ───────────────────────────────────────────────── // ── Batch import ─────────────────────────────────────────────────
if (Array.isArray(body.items)) { if (Array.isArray(body.items)) {
const { sourceId } = body as { sourceId?: string };
let source: Awaited<ReturnType<typeof getSource>> | null = null;
if (sourceId) source = await getSource(sourceId);
const results: Array<{ const results: Array<{
classname: string; classname: string;
ok: boolean; ok: boolean;
@@ -297,9 +291,6 @@ export const POST = withAdmin(
type: item.type ?? "flooritem", type: item.type ?? "flooritem",
revision: item.revision ?? 0, revision: item.revision ?? 0,
category: item.category ?? "unknown", category: item.category ?? "unknown",
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl || undefined,
iconBaseUrl: source?.iconBaseUrl || undefined,
}); });
results.push({ classname: item.classname, ...result }); results.push({ classname: item.classname, ...result });
@@ -350,22 +341,10 @@ export const POST = withAdmin(
} }
// ── Single import ──────────────────────────────────────────────── // ── Single import ────────────────────────────────────────────────
const { const { id, classname, name, description, type, revision, category } = body;
id,
classname,
name,
description,
type,
revision,
category,
sourceId,
} = body;
if (!classname || !name) return apiError("Missing classname or name", 400); if (!classname || !name) return apiError("Missing classname or name", 400);
let source: Awaited<ReturnType<typeof getSource>> | null = null;
if (sourceId) source = await getSource(sourceId);
const result = await importSingleFurni({ const result = await importSingleFurni({
id: id ?? 0, id: id ?? 0,
classname, classname,
@@ -374,9 +353,6 @@ export const POST = withAdmin(
type: type ?? "flooritem", type: type ?? "flooritem",
revision: revision ?? 0, revision: revision ?? 0,
category: category ?? "unknown", category: category ?? "unknown",
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl || undefined,
iconBaseUrl: source?.iconBaseUrl || undefined,
}); });
if (!result.ok) return apiError(result.error ?? "Import failed", 409); if (!result.ok) return apiError(result.error ?? "Import failed", 409);
@@ -821,8 +797,6 @@ export const PUT = withAdmin(
} }
if (!isDryRun) { if (!isDryRun) {
// Clear in-memory catalog page cache since we may have created/deleted pages
resetCatalogPageCache();
logAudit({ logAudit({
userId: ctx.session.user.id, userId: ctx.session.user.id,
action: "furni_reorganize", action: "furni_reorganize",
+1 -1
View File
@@ -12,7 +12,7 @@ export const GET = withAdmin(
{ permission: PERMS.ASSETS_IMPORT }, { permission: PERMS.ASSETS_IMPORT },
async (request) => { async (request) => {
if (request.nextUrl.searchParams.get("action") === "stats") if (request.nextUrl.searchParams.get("action") === "stats")
return apiOk(await getPetStats()); return apiOk(getPetStats());
const search = request.nextUrl.searchParams.get("search") || ""; const search = request.nextUrl.searchParams.get("search") || "";
return apiOk({ pets: getPetList(search) }); return apiOk({ pets: getPetList(search) });
}, },
@@ -14,7 +14,9 @@ export const GET = withAdmin({ permission: PERMS.PREFIXES_VIEW }, async () => {
sql`SELECT id, word FROM custom_prefix_blacklist ORDER BY word ASC`, sql`SELECT id, word FROM custom_prefix_blacklist ORDER BY word ASC`,
)) as unknown as [BlacklistWord[], unknown]; )) as unknown as [BlacklistWord[], unknown];
return apiOk({ words }); return apiOk({
words: words.map((w) => ({ ...w, created_at: "" })),
});
}); });
export const POST = withAdmin( export const POST = withAdmin(
+1
View File
@@ -52,6 +52,7 @@ export const GET = withAdmin(
icon: p.icon || "", icon: p.icon || "",
effect: p.effect || "", effect: p.effect || "",
active: Boolean(p.active), active: Boolean(p.active),
created_at: "",
})), })),
total, total,
page, page,
-95
View File
@@ -1,95 +0,0 @@
import { promises as fs } from "node:fs";
import { desc, eq } from "drizzle-orm";
import { withAdmin } from "@/lib/api-handler";
import { apiError, apiOk } from "@/lib/api-response";
import { db, Soundtracks } from "@/lib/db";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
import {
extractMp3Duration,
getSoundtrackPath,
isSafeSoundtrackCode,
MAX_SOUNDTRACK_SIZE,
validateMp3Bytes,
writeSoundtrackFile,
} from "@/lib/services/soundtracks";
export const POST = withAdmin(
{ permission: PERMS.CATALOG_EDIT, requireCsrf: true },
async (request) => {
const formData = await request.formData();
const file = formData.get("file");
const name = String(formData.get("name") ?? "").trim();
const author = String(formData.get("author") ?? "").trim();
if (!(file instanceof File)) {
return apiError("No file uploaded", 400);
}
if (!name) {
return apiError("Name is required", 400);
}
if (file.size > MAX_SOUNDTRACK_SIZE) {
return apiError("File exceeds 10 MB limit", 413);
}
if (file.size === 0) {
return apiError("File is empty", 400);
}
const buf = Buffer.from(await file.arrayBuffer());
if (!validateMp3Bytes(buf)) {
return apiError("File is not a valid MP3", 415);
}
const duration = await extractMp3Duration(buf);
const maxRow = await db
.select({ maxId: Soundtracks.id })
.from(Soundtracks)
.orderBy(desc(Soundtracks.id))
.limit(1)
.then((rows) => rows[0]?.maxId ?? 0)
.catch(() => 0);
const nextId = maxRow + 1;
const code = `song_${nextId}`;
if (!isSafeSoundtrackCode(code)) {
return apiError("Generated code is invalid", 500);
}
const existing = await db
.select({ id: Soundtracks.id })
.from(Soundtracks)
.where(eq(Soundtracks.code, code))
.limit(1)
.catch(() => null);
if (existing && existing.length > 0) {
return apiError("Song code already exists", 409);
}
await writeSoundtrackFile(code, buf);
let id: number;
try {
const result = await db.insert(Soundtracks).values({
code,
name: name.slice(0, 100),
author: author.slice(0, 50),
track: "",
length: duration,
});
id = Number(result[0].insertId);
} catch (err) {
logger.error("Failed to insert soundtrack record", { err, code });
try {
await fs.unlink(getSoundtrackPath(code));
} catch {
/* ignore cleanup failure */
}
return apiError("Failed to save soundtrack", 500);
}
return apiOk({ ok: true, id, code });
},
);
+58 -45
View File
@@ -8,16 +8,6 @@ export interface CloneSource {
nitroBaseUrl: string; nitroBaseUrl: string;
iconBaseUrl: string; iconBaseUrl: string;
hotel: string; hotel: string;
/**
* Optional per-source base URL for downloading SWF files.
* When set, the import service will try this URL before falling back
* to the official Habbo CDN (images.habbo.com).
*
* Retro hotels often have their own dcr/hof_furni structure,
* e.g. "https://virtualcity.nl/dcr" →
* "https://virtualcity.nl/dcr/hof_furni/{revision}/{classname}.swf"
*/
sourceSwfBaseUrl?: string;
} }
const KEY = "clone_sources"; const KEY = "clone_sources";
@@ -25,11 +15,17 @@ const KEY = "clone_sources";
/** /**
* Verified sources. Used as the default list and as the fallback when the * Verified sources. Used as the default list and as the fallback when the
* `clone_sources` site setting is empty. * `clone_sources` site setting is empty.
*
* Furnidata URLs verified HTTP 200 on 2026-08-06.
* Retro sources using Cloudflare may require browser-like headers on fetch.
*/ */
export const DEFAULT_SOURCES: CloneSource[] = [ export const DEFAULT_SOURCES: CloneSource[] = [
{
id: "default-habbo",
name: "Habbo (IT)",
furnidataUrl:
"https://raw.githubusercontent.com/Izzxt/habbo-resource/master/gamedata/furnidata.json",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "it",
},
{ {
id: "default-habbo-com", id: "default-habbo-com",
name: "Habbo (COM)", name: "Habbo (COM)",
@@ -94,59 +90,78 @@ export const DEFAULT_SOURCES: CloneSource[] = [
iconBaseUrl: "", iconBaseUrl: "",
hotel: "com.tr", hotel: "com.tr",
}, },
{
id: "default-habbo-it",
name: "Habbo (IT - GitHub mirror)",
furnidataUrl:
"https://raw.githubusercontent.com/Izzxt/habbo-resource/master/gamedata/furnidata.json",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "it",
},
{
id: "default-yabbohotel",
name: "YabboHotel",
furnidataUrl: "https://yabbohotel.com/gamedata/FurnitureData.json",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "com",
},
{ {
id: "default-wibbo", id: "default-wibbo",
name: "Wibbo", name: "Wibbo",
furnidataUrl: "https://assets.wibbo.org/gamedata/FurnitureData.json", furnidataUrl: "https://assets.wibbo.org/gamedata/FurnitureData.json",
nitroBaseUrl: "", nitroBaseUrl: "https://assets.wibbo.org/bundled/furniture",
iconBaseUrl: "", iconBaseUrl: "https://assets.wibbo.org/icons",
hotel: "com", hotel: "com",
}, },
{ {
id: "default-hubba", id: "default-hubba",
name: "Hubba.cc", name: "Hubba.cc",
furnidataUrl: "https://nitro.hubba.cc/gamedata/FurnitureData.json", furnidataUrl: "https://nitro.hubba.cc/gamedata/FurnitureData.json",
nitroBaseUrl: "https://nitro.hubba.cc/bundled/furniture",
iconBaseUrl: "",
hotel: "com",
},
{
id: "default-sodaho",
name: "Soda Ho",
furnidataUrl: "https://assets.sodaho.tel/gamedata/FurnitureData.json",
nitroBaseUrl: "", nitroBaseUrl: "",
iconBaseUrl: "", iconBaseUrl: "",
hotel: "com", hotel: "com",
}, },
{ {
id: "default-habblet-city", id: "default-leet",
name: "Leet",
furnidataUrl: "https://www.leet.ws/gamedata/furnidata.json",
nitroBaseUrl: "https://www.leet.ws/nitro/bundled/furniture",
iconBaseUrl: "https://www.leet.ws/nitro/icons",
hotel: "com",
},
{
id: "default-hubbly",
name: "Hubbly",
furnidataUrl: "https://www.hubbly.pw/gamedata/furnidata.json",
nitroBaseUrl: "https://www.hubbly.pw/nitro/bundled/furniture",
iconBaseUrl: "https://www.hubbly.pw/nitro/icons",
hotel: "com",
},
{
id: "default-habbletcity",
name: "Habblet City", name: "Habblet City",
furnidataUrl: "https://www.habblet.city/gamedata/furnidata.json", furnidataUrl: "https://www.habblet.city/gamedata/furnidata.json",
nitroBaseUrl: "https://www.habblet.city/nitro/bundled/furniture", nitroBaseUrl: "https://www.habblet.city/nitro/bundled/furniture",
iconBaseUrl: "https://www.habblet.city/nitro/icons", iconBaseUrl: "https://www.habblet.city/nitro/icons",
hotel: "com", hotel: "com",
// Retro hotels may use their own SWF server (Habbo official CDN still has legacy files)
// This field enables per-source SWF/nitro/icon download base URL fallback
// The import service will try: sourceSwfBaseUrl > images.habbo.com
sourceSwfBaseUrl: "https://www.habblet.city/dcr",
}, },
{ {
id: "default-virtualcity", id: "default-habbo-retro",
name: "VirtualCity", name: "Habbo Retro",
furnidataUrl: "https://virtualc.nl/gamedata/furnidata_json/1", furnidataUrl:
nitroBaseUrl: "https://virtualc.nl/nitro/bundled/furniture", "https://raw.githubusercontent.com/Izzxt/habbo-resource/master/gamedata/furnidata.json",
iconBaseUrl: "https://virtualc.nl/nitro/icons", nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "com",
},
{
id: "default-habbo-classic",
name: "Habbo Classic",
furnidataUrl: "https://www.habbo.com/gamedata/furnidata_json/1",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "com",
},
{
id: "default-habbo-original",
name: "Habbo Original",
furnidataUrl: "https://habbo.com/gamedata/furnidata_json/1",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "com", hotel: "com",
sourceSwfBaseUrl: "https://virtualc.nl/dcr",
}, },
]; ];
@@ -172,7 +187,6 @@ export async function upsertSource(
src: Omit<CloneSource, "id"> & { id?: string }, src: Omit<CloneSource, "id"> & { id?: string },
): Promise<CloneSource> { ): Promise<CloneSource> {
const sources = await listSources(); const sources = await listSources();
const swfBase = src.sourceSwfBaseUrl?.trim().replace(/\/+$/, "");
const entry: CloneSource = { const entry: CloneSource = {
id: src.id || randomUUID(), id: src.id || randomUUID(),
name: src.name.trim(), name: src.name.trim(),
@@ -180,7 +194,6 @@ export async function upsertSource(
nitroBaseUrl: src.nitroBaseUrl.trim().replace(/\/+$/, ""), nitroBaseUrl: src.nitroBaseUrl.trim().replace(/\/+$/, ""),
iconBaseUrl: src.iconBaseUrl.trim().replace(/\/+$/, ""), iconBaseUrl: src.iconBaseUrl.trim().replace(/\/+$/, ""),
hotel: (src.hotel ?? "").trim(), hotel: (src.hotel ?? "").trim(),
sourceSwfBaseUrl: swfBase || undefined,
}; };
const idx = sources.findIndex((s) => s.id === entry.id); const idx = sources.findIndex((s) => s.id === entry.id);
if (idx >= 0) sources[idx] = entry; if (idx >= 0) sources[idx] = entry;
+1 -48
View File
@@ -28,12 +28,7 @@ vi.mock("@/lib/services/swf-to-nitro", () => ({
extractIconFromSwf: vi.fn(), extractIconFromSwf: vi.fn(),
})); }));
import { import { buildItemsBaseEnrichmentUpdate } from "./furni-import";
autoPriceFurni,
buildItemsBaseEnrichmentUpdate,
classifyFurni,
resetCatalogPageCache,
} from "./furni-import";
describe("buildItemsBaseEnrichmentUpdate", () => { describe("buildItemsBaseEnrichmentUpdate", () => {
it("only updates columns present in the live Arcturus items_base schema", () => { it("only updates columns present in the live Arcturus items_base schema", () => {
@@ -55,45 +50,3 @@ describe("buildItemsBaseEnrichmentUpdate", () => {
expect(serialized).toContain("default"); expect(serialized).toContain("default");
}); });
}); });
describe("classifyFurni", () => {
it("classifies credits by classname prefix", () => {
expect(classifyFurni("CF_750_credits", "s")).toBe("credits");
expect(classifyFurni("exe_50", "s")).toBe("credits");
});
it("classifies wired by classname prefix", () => {
expect(classifyFurni("wf_act_1", "s")).toBe("wired");
});
it("classifies wall items by type", () => {
expect(classifyFurni("wallposter", "i")).toBe("walls");
});
it("falls back to 'other' for unknown classnames", () => {
expect(classifyFurni("custom_item", "s")).toBe("other");
});
});
describe("autoPriceFurni", () => {
it("extracts credit value from CF_ prefix", () => {
const price = autoPriceFurni("CF_750_credits");
expect(price.credits).toBe(750);
});
it("prices rares at 25 credits", () => {
const price = autoPriceFurni("rare_habbo_max");
expect(price.credits).toBe(25);
});
it("prices default items at 3 credits", () => {
const price = autoPriceFurni("random_furni");
expect(price.credits).toBe(3);
});
});
describe("resetCatalogPageCache", () => {
it("is a callable function that does not throw", () => {
expect(() => resetCatalogPageCache()).not.toThrow();
});
});
+31 -138
View File
@@ -182,21 +182,14 @@ export function buildItemsBaseEnrichmentUpdate(params: {
`; `;
} }
/** Get or create the root "Imported Furniture" parent page (no items directly on this page). /** Get or create the root "Imported Furniture" parent page (no items directly on this page). */
* Caches the page ID in-memory for the process lifetime to avoid redundant DB reads
* during batch imports */
export async function getOrCreateImportedParentPage(): Promise<number> { export async function getOrCreateImportedParentPage(): Promise<number> {
if (parentIdCache !== null) return parentIdCache;
const [existing] = await db const [existing] = await db
.select({ id: CatalogPages.id }) .select({ id: CatalogPages.id })
.from(CatalogPages) .from(CatalogPages)
.where(eq(CatalogPages.captionSave, IMPORTED_PAGE_CAPTION_SAVE)) .where(eq(CatalogPages.captionSave, IMPORTED_PAGE_CAPTION_SAVE))
.limit(1); .limit(1);
if (existing) { if (existing) return existing.id;
parentIdCache = existing.id;
return existing.id;
}
// Use raw SQL to avoid ENUM mismatch (page_layout, visible, enabled) // Use raw SQL to avoid ENUM mismatch (page_layout, visible, enabled)
// All string columns must be '' (not NULL) or the Java emulator may skip the page // All string columns must be '' (not NULL) or the Java emulator may skip the page
@@ -214,7 +207,6 @@ export async function getOrCreateImportedParentPage(): Promise<number> {
'Failed to create "Imported Furniture" parent catalog page', 'Failed to create "Imported Furniture" parent catalog page',
); );
} }
parentIdCache = created.id;
return created.id; return created.id;
} }
@@ -289,21 +281,6 @@ let catalogIdLastUsed = 0;
let catalogIdSeedChain: Promise<void> = Promise.resolve(); let catalogIdSeedChain: Promise<void> = Promise.resolve();
const CATALOG_ID_REFRESH_MS = 60_000; const CATALOG_ID_REFRESH_MS = 60_000;
// In-memory cache for catalog page IDs — avoids N+1 DB lookups during batch imports
// where many items belong to the same category.
let parentIdCache: number | null = null;
let categoryPageCache: Map<string, number> | null = null;
let categoryCacheTimestamp = 0;
const CATEGORY_CACHE_TTL_MS = 5 * 60_000; // 5 minutes
/** Drop the in-process catalog page cache. Call after bulk operations
* (e.g. the PUT re-organize route) to force a fresh DB lookup. */
export function resetCatalogPageCache(): void {
parentIdCache = null;
categoryPageCache = null;
categoryCacheTimestamp = 0;
}
/** Allocate a unique catalog_items id. Seeded once with MAX(id)+1, then handed /** Allocate a unique catalog_items id. Seeded once with MAX(id)+1, then handed
* out from an in-process counter so concurrent imports don't serialize on a * out from an in-process counter so concurrent imports don't serialize on a
* SELECT MAX + INSERT round-trip per item. Re-seeds when idle so rows added * SELECT MAX + INSERT round-trip per item. Re-seeds when idle so rows added
@@ -349,10 +326,7 @@ export function __resetCatalogIdAllocatorForTests(): void {
catalogIdSeedChain = Promise.resolve(); catalogIdSeedChain = Promise.resolve();
} }
/** Get or create a category sub-page under the imported parent page. /** Get or create a category sub-page under the imported parent page. */
* Caches category page IDs in-memory for CATEGORY_CACHE_TTL_MS to avoid
* redundant DB lookups during batch imports where many items map to the same
* category. */
export async function getOrCreateCategoryPage( export async function getOrCreateCategoryPage(
classname: string, classname: string,
itemType: string, itemType: string,
@@ -360,17 +334,6 @@ export async function getOrCreateCategoryPage(
const parentId = await getOrCreateImportedParentPage(); const parentId = await getOrCreateImportedParentPage();
const catKey = classifyFurni(classname, itemType); const catKey = classifyFurni(classname, itemType);
const captionSave = `imp_${catKey}`; const captionSave = `imp_${catKey}`;
// Check in-memory cache (TTL based)
const now = Date.now();
if (
categoryPageCache &&
now - categoryCacheTimestamp < CATEGORY_CACHE_TTL_MS
) {
const cached = categoryPageCache.get(captionSave);
if (cached !== undefined) return cached;
}
const catInfo = CATEGORY_PAGE[catKey] || CATEGORY_PAGE.other; const catInfo = CATEGORY_PAGE[catKey] || CATEGORY_PAGE.other;
const [existing] = await db const [existing] = await db
@@ -383,11 +346,7 @@ export async function getOrCreateCategoryPage(
), ),
) )
.limit(1); .limit(1);
if (existing) { if (existing) return existing.id;
if (!categoryPageCache) categoryPageCache = new Map();
categoryPageCache.set(captionSave, existing.id);
return existing.id;
}
await db.execute(sql` await db.execute(sql`
INSERT INTO catalog_pages (caption_save, caption, page_layout, parent_id, min_rank, order_num, icon_image, enabled, visible, includes, page_headline, page_teaser, page_special, page_text1, page_text2, page_text_details, page_text_teaser) INSERT INTO catalog_pages (caption_save, caption, page_layout, parent_id, min_rank, order_num, icon_image, enabled, visible, includes, page_headline, page_teaser, page_special, page_text1, page_text2, page_text_details, page_text_teaser)
@@ -409,8 +368,6 @@ export async function getOrCreateCategoryPage(
`Failed to create catalog sub-page "${captionSave}" under parent ${parentId}`, `Failed to create catalog sub-page "${captionSave}" under parent ${parentId}`,
); );
} }
if (!categoryPageCache) categoryPageCache = new Map();
categoryPageCache.set(captionSave, created.id);
return created.id; return created.id;
} }
@@ -426,11 +383,6 @@ export async function importSingleFurni(params: {
category: string; category: string;
skipFurniDataWrite?: boolean; skipFurniDataWrite?: boolean;
onProgress?: (status: string) => void; onProgress?: (status: string) => void;
/** Per-source SWF download base URL (e.g. "https://virtualc.nl/dcr"). */
sourceSwfBaseUrl?: string;
/** Per-source nitro bundle + icon base URL. */
nitroBaseUrl?: string;
iconBaseUrl?: string;
}): Promise<ImportSingleResult> { }): Promise<ImportSingleResult> {
const { const {
id: originalId, id: originalId,
@@ -442,9 +394,6 @@ export async function importSingleFurni(params: {
category, category,
skipFurniDataWrite, skipFurniDataWrite,
onProgress, onProgress,
sourceSwfBaseUrl,
nitroBaseUrl: sourceNitroBaseUrl,
iconBaseUrl: sourceIconBaseUrl,
} = params; } = params;
const warnings: string[] = []; const warnings: string[] = [];
@@ -546,71 +495,33 @@ export async function importSingleFurni(params: {
// fall back to base-classname icon (Nitro reuses base for all colors // fall back to base-classname icon (Nitro reuses base for all colors
// when no color-specific icon exists). // when no color-specific icon exists).
onProgress?.("downloading"); onProgress?.("downloading");
const iconColorAware = classname.replace(/\*/g, "_"); const iconColorAware = classname.replace(/\*/g, "_");
const iconUrl = hasColor
? `https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(iconColorAware)}_icon.png`
: `https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(baseClassname)}_icon.png`;
// Build candidate URL lists — source-specific URLs first, then Habbo CDN fallback const downloadResults = await Promise.allSettled([
const iconUrls: string[] = []; downloadFile(iconUrl, iconPath, { validate: "png" }),
const swfUrls: string[] = []; downloadFile(
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(safeSwfName)}.swf`,
swfPath,
{ validate: "swf" },
),
]);
// Source-specific icon URLs let iconOk =
if (sourceIconBaseUrl) { downloadResults[0].status === "fulfilled" && downloadResults[0].value.ok;
// e.g. https://habblet.city/nitro/icons/{classname}_icon.png const swfOk =
iconUrls.push( downloadResults[1].status === "fulfilled" && downloadResults[1].value.ok;
`${sourceIconBaseUrl}/${encodeURIComponent(iconColorAware)}_icon.png`,
`${sourceIconBaseUrl}/${encodeURIComponent(baseClassname)}_icon.png`, // If color-specific icon 404'd, try the base-classname icon.
if (!iconOk && hasColor) {
const dl = await downloadFile(
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(baseClassname)}_icon.png`,
iconPath,
{ validate: "png" },
); );
} if (dl.ok) iconOk = true;
// Source-specific SWF URLs
if (sourceSwfBaseUrl) {
// e.g. https://virtualc.nl/dcr/hof_furni/{rev}/{classname}.swf
swfUrls.push(
`${sourceSwfBaseUrl}/hof_furni/${rev}/${encodeURIComponent(safeSwfName)}.swf`,
);
}
// Official Habbo CDN fallbacks
iconUrls.push(
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(iconColorAware)}_icon.png`,
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(baseClassname)}_icon.png`,
);
swfUrls.push(
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(safeSwfName)}.swf`,
);
// Download icon (try all candidate URLs)
let iconOk = false;
for (const iconUrl of iconUrls) {
const dl = await downloadFile(iconUrl, iconPath, { validate: "png" });
if (dl.ok) {
iconOk = true;
break;
}
}
// Download SWF (try all candidate URLs)
let swfOk = false;
for (const swfUrl of swfUrls) {
const dl = await downloadFile(swfUrl, swfPath, { validate: "swf" });
if (dl.ok) {
swfOk = true;
break;
}
}
// ── Nitro bundle fallback: try downloading pre-made .nitro ────────
// If SWF download failed, try downloading a pre-made .nitro from the
// source's nitro base URL (many retro hotels ship .nitro bundles).
let nitroDownloadOk = false;
if (
!swfOk &&
sourceNitroBaseUrl &&
!existsSync(/*turbopackIgnore: true*/ nitroPath)
) {
const nitroUrl = `${sourceNitroBaseUrl}/${encodeURIComponent(safeNitroName)}.nitro`;
const dl = await downloadFile(nitroUrl, nitroPath, { validate: "png" });
if (dl.ok) nitroDownloadOk = true;
} }
// ── Icon fallback: extract from SWF if download failed ──────────── // ── Icon fallback: extract from SWF if download failed ────────────
@@ -620,8 +531,7 @@ export async function importSingleFurni(params: {
const iconPng = extractIconFromSwf(swfBuf, baseClassname); const iconPng = extractIconFromSwf(swfBuf, baseClassname);
if (iconPng) { if (iconPng) {
await fs.writeFile(/*turbopackIgnore: true*/ iconPath, iconPng); await fs.writeFile(/*turbopackIgnore: true*/ iconPath, iconPng);
iconOk = true; warnings.push("Icon extracted from SWF (external download failed)");
warnings.push("Icon extracted from SWF (download failed)");
} else { } else {
warnings.push( warnings.push(
"Icon download failed and SWF icon extraction returned nothing", "Icon download failed and SWF icon extraction returned nothing",
@@ -634,7 +544,7 @@ export async function importSingleFurni(params: {
warnings.push("Icon image download failed"); warnings.push("Icon image download failed");
} }
if (!swfOk && !nitroDownloadOk) warnings.push("SWF download failed"); if (!swfOk) warnings.push("SWF download failed");
// ── Convert SWF to Nitro ────────────────────────────────────────── // ── Convert SWF to Nitro ──────────────────────────────────────────
onProgress?.("converting"); onProgress?.("converting");
@@ -667,25 +577,8 @@ export async function importSingleFurni(params: {
} }
} }
// ── Rollback: if conversion/download failed AND no .nitro exists, remove DB record ── // ── Rollback: if conversion failed AND no .nitro exists, remove DB record ──
// Also validate that the .nitro file is non-trivial (≥ 128 bytes — a bare if (!existsSync(/*turbopackIgnore: true*/ nitroPath) && !conversionResult) {
// Nitro bundle header is larger than that, anything smaller is corrupt/empty).
const nitroStat = await fs
.stat(/*turbopackIgnore: true*/ nitroPath)
.catch(() => null);
const nitroValid = nitroStat && nitroStat.size >= 128;
if (!nitroValid && !conversionResult) {
if (nitroStat) {
warnings.push(
`Nitro file too small/corrupt (${nitroStat.size} bytes) — removing`,
);
try {
await fs.unlink(nitroPath);
} catch {
/* ignore */
}
}
try { try {
await db.execute( await db.execute(
sql`DELETE FROM items_base WHERE id = ${spriteId} AND item_name = ${classname}`, sql`DELETE FROM items_base WHERE id = ${spriteId} AND item_name = ${classname}`,
+5 -8
View File
@@ -154,14 +154,11 @@ export async function batchLookupByClassnames(
const result = new Map<string, HabboFurniItem>(); const result = new Map<string, HabboFurniItem>();
if (classnames.length === 0) return result; if (classnames.length === 0) return result;
// Parallel lookup — all share the same in-memory furnidata cache for (const cn of classnames) {
const lookedUp = await Promise.all( const item = await getFurnitureByClassname(cn);
classnames.map((cn) => getFurnitureByClassname(cn)), if (item?.name) {
); result.set(cn, item);
}
for (let i = 0; i < classnames.length; i++) {
const item = lookedUp[i];
if (item?.name) result.set(classnames[i], item);
} }
return result; return result;