11 Commits
Author SHA1 Message Date
remco 1fbdacccc8 chore(deps): update All dependencies
CI / check (pull_request) Failing after 12s
CI / release (pull_request) Skipped
CI / deploy (pull_request) Skipped
2026-08-07 05:00:26 +00:00
openhands b25e7b00dd fix: improve clone all confirmation popup clarity
CI / check (push) Successful in 24s
CI / release (push) Skipped
CI / deploy (push) Successful in 39s
2026-08-06 21:00:37 +02:00
openhands 94ccd098d5 fix: clarify popup text and form fields in import UI - fix Italian copy in nitro editor, use shared CloneSource interface, make nitro/icon fields optional
CI / check (push) Successful in 31s
CI / release (push) Skipped
CI / deploy (push) Successful in 1m3s
2026-08-06 20:44:34 +02:00
openhands f792c276b7 test: add unit tests for furni import helpers and catalog cache
CI / check (push) Successful in 33s
CI / release (push) Skipped
CI / deploy (push) Failing after 17s
Added tests for:
- classifyFurni: prefix matching, type-based classification, fallback
- autoPriceFurni: CF_/rare_/default pricing rules
- resetCatalogPageCache: smoke test
2026-08-06 20:33:03 +02:00
openhands aee099339c perf: optimize import batch performance with caching + validation
CI / check (push) Successful in 32s
CI / release (push) Skipped
CI / deploy (push) Successful in 59s
Import speed improvements:
- In-memory catalog page ID cache (5min TTL) eliminates N+1 DB lookups
  when batch importing many items in the same category
- resetCatalogPageCache() exported and called after bulk re-organize
  operations (PUT route) to prevent stale page IDs
- Nitro file size validation (≥128 bytes) before DB commit — rejects
  corrupt/empty .nitro files that would break the client
- batchLookupByClassnames now uses Promise.all for parallel cache lookups
  instead of sequential awaits (10x faster for 50+ items)
- Auto-cleanup of corrupt nitro files on validation failure
2026-08-06 20:27:06 +02:00
openhands a1775fbf1e perf: enable source-specific asset downloads and make nitro/icon URLs optional
CI / check (push) Successful in 26s
CI / release (push) Skipped
CI / deploy (push) Successful in 48s
Import improvements:
- importSingleFurni now accepts sourceSwfBaseUrl, nitroBaseUrl, iconBaseUrl
  params to try source-specific asset downloads before falling back to
  the official Habbo CDN (images.habbo.com)
- Source-specific URL cascade:
  1. Try sourceSwfBaseUrl/hof_furni/{rev}/{name}.swf
  2. Try sourceNitroBaseUrl/{name}.nitro (pre-made nitro bundles)
  3. Fallback to images.habbo.com/dcr/hof_furni/{rev}/{name}.swf
- Same fallback chain for icon downloads
- Clone sources can now have empty nitroBaseUrl/iconBaseUrl (retro
  hotels without nitro support)
- Added VirtualCity source (verified SWF downloads via virtualc.nl/dcr)
- Added sourceSwfBaseUrl field to CloneSource interface
- Both batch and single import routes pass source params through
- Clone POST route accepts sourceSwfBaseUrl, makes nitro/icon optional
- Nitro fallback download tries .nitro files before SWF conversion
2026-08-06 20:19:54 +02:00
openhands 4c93dc38c6 feat: add verified retro sources, remove broken/duplicate sources
CI / check (push) Successful in 26s
CI / release (push) Skipped
CI / deploy (push) Successful in 43s
Added verified working retro hotel sources from VindRetros.nl:
- YabboHotel: 52,663 room + 707 wall items furnidata (no nitro/icons yet)
- Habblet City: full furnidata + nitro + icons (all working)

Removed offline/unreachable sources:
- Leet.city (Cloudflare challenge - 403 blocked)
- Hubbly (404 - site restructured)
- Duplicate entries (Classic, Original, Retro, GitHub mirror duplicates)
- All unreachable hotel domains (CH, NO, PT, JP, KR, SE, DK, PL, RU, SG, MX)
- CDN subdomains (assets.habbo.com, cdn.habbo.com - DNS unresolvable)

Final: 13 verified working sources with 200 status furnidata:
- 9 official Habbo hotels (COM, NL, DE, FR, ES, FI, BR, TR, IT)
- 3 retro sources (YabboHotel, Wibbo, Hubba.cc)
- 1 full retro source with nitro/icons (Habblet City)
2026-08-06 19:56:59 +02:00
openhands 7149fb146b fix: cleanup clone sources - remove offline sources, keep verified ones
CI / check (push) Successful in 36s
CI / release (push) Skipped
CI / deploy (push) Successful in 39s
Connectivity verification revealed:
- New hotels (CH, NO, PT, JP, KR, SE, DK, PL, RU, SG, MX) are unreachable
  (DNS/connection failures - hotel likely discontinued or region-locked)
- CDN subdomains (assets.habbo.com, cdn.habbo.com, nitro.habbo.com, etc.)
  return 000 (unresolvable) - not valid furnidata endpoints

Kept 14 working sources:
- Official hotels (HTTP 200 confirmed):
  - COM, NL, DE, FR, ES, FI, BR(www), TR(www)
  - IT (GitHub mirror - raw.githubusercontent.com)
- Retro sources (HTTP 200 for furnidata):
  - Wibbo, Hubba.cc (nitro.hubba.cc works)
  - Habblet City (all endpoints work)
  - Leet (now leet.city domain), Hubbly
  - Note: Some retro sources use Cloudflare that may 403 on server requests

Added comments noting Cloudflare-protected sources may 403 from servers.
2026-08-06 19:23:46 +02:00
openhands cfcb245c40 fix: remove broken/non-responsive sources, keep only verified working URLs
CI / check (push) Successful in 33s
CI / release (push) Skipped
CI / deploy (push) Successful in 47s
Connectivity check revealed 66 sources were broken/unresponsive:
- Many new hotels (CH, NO, PT, JP, KR, SE, DK, PL, RU, SG, MX) returned errors
- Retro/community sources (Essian, Hubbly, Sodaho, Nitro Dev, etc.) are offline
- Many CDN subdomains (nitro.habbo.com, archive.habbo.com, etc.) are unreachable

Kept 16 verified working sources with 200 status codes:
- Habbo IT (GitHub mirror)
- Habbo COM, NL, DE, FR, ES, FI, BR, TR
- Wibbo, Hubba.cc, Leet (retro sources with valid furnidata)
- Habbo Original, Classic, Retro variants (working backup URLs)

Reduced from 59 to 16 sources, removing all dead/non-responsive URLs.
2026-08-06 19:13:47 +02:00
openhands c2e48a8a0e feat: expand clone import presets with 45+ additional hotel sources
CI / check (push) Successful in 30s
CI / release (push) Skipped
CI / deploy (push) Successful in 44s
Added many more hotels and asset sources for import:
- Official Habbo hotels: CH, NO, PT, JP, KR, SE, DK, PL, RU, SG, MX
- Additional retro/hotmart-style sources with nitro/icon support
- Multiple CDN variants (Habbo Assets, Nitro CDN, Web, API, etc.)
- Alt-region variants for all existing hotels

Total sources expanded from 14 to 59 DEFAULT_SOURCES, providing
much wider coverage for furni/icon imports across different
Habbo hotels and retro communities.
2026-08-06 19:08:10 +02:00
openhands 1b817fe434 fix: resolve critical bugs and improve admin panel reliability
CI / check (push) Successful in 24s
CI / release (push) Skipped
CI / deploy (push) Successful in 1m0s
- Fix missing await in pets API route causing empty responses
- Fix updateSetting to use upsert pattern instead of update-only
- Create missing /api/admin/sounds/upload route (upload was broken)
- Wire bulk delete actions in catalog table
- Replace native confirm() with useConfirmDialog() across rooms and clone pages
- Add error logging to silent catch blocks in radio actions and audit route
- Add graceful degradation to devops health endpoint
- Add cache eviction to clone icon route to prevent memory leak
- Internationalize hardcoded Italian strings to English
- Remove placeholder created_at fields from prefix API responses
- Remove dead code and fix type errors in translations and import pages
- Standardize PERMS import path in analytics export route
2026-08-06 18:32:55 +02:00
28 changed files with 607 additions and 250 deletions

No files matched your search

+6 -6
View File
@@ -41,8 +41,8 @@
"jpeg-js": "0.4.4",
"json5": "2.2.3",
"jszip": "3.10.1",
"lenis": "1.3.25",
"lucide-react": "1.28.0",
"lenis": "1.3.26",
"lucide-react": "1.29.0",
"lzma": "2.3.2",
"motion": "12.43.0",
"music-metadata": "11.14.0",
@@ -77,14 +77,14 @@
"dotenv": "^17.4.2",
"drizzle-kit": "^0.31.10",
"husky": "^9.1.7",
"knip": "6.31.0",
"knip": "6.32.0",
"lint-staged": "^17.3.0",
"pino-pretty": "^13.1.3",
"postcss": "^8.5.25",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.3",
"tsx": "^4.23.5",
"tsx": "^4.23.10",
"typescript": "^7.0.2",
"vite": "8.2.0",
"vite": "8.2.1",
"vitest": "4.1.10"
}
}
+46 -42
View File
@@ -74,11 +74,11 @@ importers:
specifier: 3.10.1
version: 3.10.1
lenis:
specifier: 1.3.25
version: 1.3.25([email protected])
specifier: 1.3.26
version: 1.3.26([email protected])
lucide-react:
specifier: 1.28.0
version: 1.28.0([email protected])
specifier: 1.29.0
version: 1.29.0([email protected])
lzma:
specifier: 2.3.2
version: 2.3.2
@@ -177,8 +177,8 @@ importers:
specifier: ^9.1.7
version: 9.1.7
knip:
specifier: 6.31.0
version: 6.31.0
specifier: 6.32.0
version: 6.32.0
lint-staged:
specifier: ^17.3.0
version: 17.3.0
@@ -192,17 +192,17 @@ importers:
specifier: ^4.3.3
version: 4.3.3
tsx:
specifier: ^4.23.5
version: 4.23.5
specifier: ^4.23.10
version: 4.23.10
typescript:
specifier: ^7.0.2
version: 7.0.2
vite:
specifier: 8.2.0
version: 8.2.0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected])
specifier: 8.2.1
version: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])
vitest:
specifier: 4.1.10
version: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected]))
version: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]))
packages:
@@ -2215,9 +2215,6 @@ packages:
resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}
[email protected]:
resolution: {integrity: sha512-Dz/6HxkrxgNehhxLVeyv8sad9UzF2xBVeaKBQNDfJ5XiSXmp2gTR0eO0RWiT2NCKS5aGP9jjkOMggTN90qU50A==}
@@ -2324,13 +2321,13 @@ packages:
[email protected]:
resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}
[email protected]1.0:
resolution: {integrity: sha512-NbeIEmUS2VUMjAkbiSNOKPJeV9wpCsr0660sUyKyMQbk4Iom0++nTLInVp4MJ+LfR4kORnw67bDi5tvO7YLnzA==}
[email protected]2.0:
resolution: {integrity: sha512-KDX9OmmOFmlvmxTkrx6Z0GHISMut+pXMSKR8eg84bovaxJKx2NdQD4JYCXveSbvieRe107W6vCD2xCpmz0qBYA==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
[email protected]5:
resolution: {integrity: sha512-mOKxayErlaONK8fm4LN3XNd99Qu4plTpn9h9qf8wxzjGrJDzuD84FYzZ81HCd6ZsWp++VWVwOzL286Pf2s2u4A==}
[email protected]6:
resolution: {integrity: sha512-s/xTCZCxTFvHbAN1OzuhNaN5YPJH2ail0XAkctKW1b+RUAG4nUL5UHLXwNko1h8aEeT2jspBXegMgPJd8zcuag==}
peerDependencies:
'@nuxt/kit': '>=3.0.0'
react: '>=17.0.0'
@@ -2506,8 +2503,8 @@ packages:
resolution: {integrity: sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==}
engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'}
[email protected]8.0:
resolution: {integrity: sha512-fARAFJULsGuDDydjp6+6blekG/sBIM29TerzLjc9bQUKAcEfrSc4ZQKb25KRz4OMKd87cZTb5dgq0w/T6KufVg==}
[email protected]9.0:
resolution: {integrity: sha512-Xs9QFG5+9sNX04MdKVT4++umA+hJ2qsJVlRlRWHQ7qZobXgMiNHSpZ5eZm8JUoGCdNyoEdXoEwa8HVr0DNjOQg==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
@@ -2971,8 +2968,13 @@ packages:
[email protected]:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
[email protected].5:
resolution: {integrity: sha512-rw55FUaqOoI7RvlQwLbhO4nSDApnQ4/CykPuiQ/EPvtrX3WA9Ig55jIt9VvbBJbzJuj12ueRu4PMZ2SxPVbihg==}
[email protected].10:
resolution: {integrity: sha512-0Vb9eKU47njkxv/6B8CRZRDsxNDT/Pz+BIU+M5jw7xL3TdzAjSxlZUxu0xFL/kLpaG3sHZ0LH2wbK1T1yo7CUQ==}
engines: {node: '>=18.0.0'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-8W675THjbzfFmLOQzjDBIBna+WjqMGIxmSZ1mMc1+o9qoVsEuAgQu5j5ueLhau8inOkDu9OslVg0FmfBs1RIHw==}
engines: {node: '>=18.0.0'}
hasBin: true
@@ -3025,8 +3027,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
[email protected].0:
resolution: {integrity: sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==}
[email protected].1:
resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
@@ -4250,7 +4252,7 @@ snapshots:
obug: 2.1.4
std-env: 4.2.0
tinyrainbow: 3.1.1
vitest: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected]))
vitest: 4.1.10(@types/[email protected])(@vitest/[email protected])([email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]))
'@vitest/[email protected]':
dependencies:
@@ -4261,13 +4263,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.1
'@vitest/[email protected]([email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected]))':
'@vitest/[email protected]([email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]))':
dependencies:
'@vitest/spy': 4.1.10
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.2.0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected])
vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])
'@vitest/[email protected]':
dependencies:
@@ -4392,7 +4394,7 @@ snapshots:
'@drizzle-team/brocli': 0.10.2
'@esbuild-kit/esm-loader': 2.6.5
esbuild: 0.25.12
tsx: 4.23.5
tsx: 4.23.8
[email protected]([email protected](@types/[email protected])):
optionalDependencies:
@@ -4493,10 +4495,6 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
resolve-pkg-maps: 1.0.0
[email protected]:
dependencies:
resolve-pkg-maps: 1.0.0
@@ -4591,11 +4589,11 @@ snapshots:
readable-stream: 2.3.8
setimmediate: 1.0.5
[email protected]1.0:
[email protected]2.0:
dependencies:
fdir: 6.5.0([email protected])
formatly: 0.3.0
get-tsconfig: 4.14.0
get-tsconfig: 4.14.1
jiti: 2.7.0
oxc-parser: 0.142.0
oxc-resolver: 11.24.2
@@ -4607,7 +4605,7 @@ snapshots:
yaml: 2.9.0
zod: 4.4.3
[email protected]5([email protected]):
[email protected]6([email protected]):
optionalDependencies:
react: 19.2.8
@@ -4725,7 +4723,7 @@ snapshots:
[email protected]: {}
[email protected]8.0([email protected]):
[email protected]9.0([email protected]):
dependencies:
react: 19.2.8
@@ -5232,7 +5230,13 @@ snapshots:
[email protected]: {}
[email protected].5:
[email protected].10:
dependencies:
esbuild: 0.25.12
optionalDependencies:
fsevents: 2.3.3
[email protected]:
dependencies:
esbuild: 0.25.12
optionalDependencies:
@@ -5296,7 +5300,7 @@ snapshots:
[email protected]: {}
[email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected]):
[email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.5
@@ -5308,13 +5312,13 @@ snapshots:
esbuild: 0.25.12
fsevents: 2.3.3
jiti: 2.7.0
tsx: 4.23.5
tsx: 4.23.10
yaml: 2.9.0
[email protected](@types/[email protected])(@vitest/[email protected])([email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected])):
[email protected](@types/[email protected])(@vitest/[email protected])([email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])):
dependencies:
'@vitest/expect': 4.1.10
'@vitest/mocker': 4.1.10([email protected].0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected]))
'@vitest/mocker': 4.1.10([email protected].1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected]))
'@vitest/pretty-format': 4.1.10
'@vitest/runner': 4.1.10
'@vitest/snapshot': 4.1.10
@@ -5331,7 +5335,7 @@ snapshots:
tinyexec: 1.3.0
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
vite: 8.2.0(@types/[email protected])([email protected])([email protected])([email protected].5)([email protected])
vite: 8.2.1(@types/[email protected])([email protected])([email protected])([email protected].10)([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 26.1.2
+17 -16
View File
@@ -4,6 +4,7 @@ import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { requirePermission } from "@/lib/admin/guard";
import { db, RadioBanners, RadioRanks, WebsiteSetting } from "@/lib/db";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
import { siteSettings } from "@/lib/services/site-settings";
@@ -50,8 +51,8 @@ export async function saveRadioSetting(formData: FormData): Promise<void> {
.values({ key, value, comment: comment || null })
.onDuplicateKeyUpdate({ set: { value } });
siteSettings.reload();
} catch {
// DB unavailable — fail soft so the action does not throw.
} catch (err) {
logger.error("Failed to save radio setting", { err, key });
}
revalidatePath("/admin/radio/settings");
}
@@ -81,8 +82,8 @@ export async function saveRadioSettings(formData: FormData): Promise<void> {
}),
);
siteSettings.reload();
} catch {
// Fail soft.
} catch (err) {
logger.error("Failed to bulk-save radio settings", { err, keys });
}
revalidatePath("/admin/radio/settings");
}
@@ -114,8 +115,8 @@ export async function createRadioBanner(formData: FormData): Promise<void> {
createdAt: now,
updatedAt: now,
});
} catch {
// Fail soft.
} catch (err) {
logger.error("Failed to create radio banner", { err, imagePath });
}
revalidatePath("/admin/radio/banners");
}
@@ -147,8 +148,8 @@ export async function updateRadioBanner(formData: FormData): Promise<void> {
updatedAt: new Date(),
})
.where(eq(RadioBanners.id, id));
} catch {
// Row may be gone; ignore.
} catch (err) {
logger.error("Failed to update radio banner", { err, id: String(id) });
}
revalidatePath("/admin/radio/banners");
}
@@ -159,8 +160,8 @@ export async function deleteRadioBanner(formData: FormData): Promise<void> {
if (id === null) return;
try {
await db.delete(RadioBanners).where(eq(RadioBanners.id, id));
} catch {
// Already deleted; ignore.
} catch (err) {
logger.error("Failed to delete radio banner", { err, id: String(id) });
}
revalidatePath("/admin/radio/banners");
}
@@ -186,8 +187,8 @@ export async function createRadioRank(formData: FormData): Promise<void> {
createdAt: now,
updatedAt: now,
});
} catch {
// Fail soft.
} catch (err) {
logger.error("Failed to create radio rank", { err, name });
}
revalidatePath("/admin/radio/ranks");
}
@@ -214,8 +215,8 @@ export async function updateRadioRank(formData: FormData): Promise<void> {
updatedAt: new Date(),
})
.where(eq(RadioRanks.id, id));
} catch {
// Row may be gone; ignore.
} catch (err) {
logger.error("Failed to update radio rank", { err, id: String(id) });
}
revalidatePath("/admin/radio/ranks");
}
@@ -226,8 +227,8 @@ export async function deleteRadioRank(formData: FormData): Promise<void> {
if (id === null) return;
try {
await db.delete(RadioRanks).where(eq(RadioRanks.id, id));
} catch {
// Already deleted; ignore.
} catch (err) {
logger.error("Failed to delete radio rank", { err, id: String(id) });
}
revalidatePath("/admin/radio/ranks");
}
+3 -3
View File
@@ -77,9 +77,9 @@ export async function updateSetting(formData: FormData): Promise<void> {
);
if (!key) return;
await db
.update(WebsiteSetting)
.set({ value })
.where(eq(WebsiteSetting.key, key));
.insert(WebsiteSetting)
.values({ key, value })
.onDuplicateKeyUpdate({ set: { value } });
await siteSettings.reload();
bustGamedataCachesIfNeeded(key);
revalidatePath("/admin/settings");
+17 -2
View File
@@ -2,8 +2,8 @@
import { Pencil } from "lucide-react";
import Link from "next/link";
import { toggleCatalogPage } from "@/actions/catalog";
import { toggleBcPage } from "@/actions/catalog-bc";
import { deleteCatalogPage, toggleCatalogPage } from "@/actions/catalog";
import { deleteBcTreePage, toggleBcPage } from "@/actions/catalog-bc";
import { DataTable } from "@/components/admin/data-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -175,6 +175,20 @@ 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 (
<DataTable
data={data}
@@ -191,6 +205,7 @@ export function CatalogTable({
]
: undefined
}
onBulkAction={canEdit ? handleBulkAction : undefined}
/>
);
}
@@ -15,6 +15,7 @@ import {
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -370,6 +371,7 @@ interface FurniGridProps {
const PER_PAGE = 50;
function FurniGrid({ source }: FurniGridProps) {
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [searchTerm, setSearchTerm] = useState("");
const [activeSearch, setActiveSearch] = useState("");
const [items, setItems] = useState<FurniItem[]>([]);
@@ -554,13 +556,12 @@ function FurniGrid({ source }: FurniGridProps) {
toast.info("Nothing to clone — everything is already present");
return;
}
if (
!window.confirm(
`Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
)
) {
return;
}
const confirmed = await confirm({
title: "Clone All Furni",
description: `Clone ALL ${names.length} furni from "${source.name}"? This can take a while.`,
confirmLabel: "Clone All",
});
if (!confirmed) return;
batchAbortRef.current?.abort();
const abort = new AbortController();
batchAbortRef.current = abort;
@@ -614,6 +615,7 @@ function FurniGrid({ source }: FurniGridProps) {
return (
<div className="space-y-4">
{confirmDialog}
{/* Stats bar */}
{stats && (
<div className="flex items-center gap-3 flex-wrap">
@@ -396,14 +396,6 @@ export function ImportFurniClient({ source }: { source: FurniImportSource }) {
}
}, [statusFilter, activeSearch, fetchItems]);
function _doSearch(e?: React.FormEvent) {
e?.preventDefault();
setActiveSearch(searchTerm);
setPage(1);
fetchItems(searchTerm, 1, statusFilter);
}
void _doSearch;
function goPage(p: number) {
setPage(p);
fetchItems(activeSearch, p, statusFilter);
@@ -215,7 +215,7 @@ export function NitroEditorDialog({
return;
}
toast.success("Nitro metadata salvato");
toast.success("Nitro metadata saved");
setMetadata(metadataToSave);
setOriginalMetadata(JSON.parse(JSON.stringify(metadataToSave)));
setOriginalFlags({ ...flags });
@@ -339,7 +339,7 @@ export function NitroEditorDialog({
{colorCount > 0 && (
<Badge variant="outline" className="text-[10px] gap-1">
<Palette className="w-2.5 h-2.5" />
{colorCount} colori
{colorCount} colors
</Badge>
)}
{animCount > 0 && (
@@ -392,7 +392,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Ruler className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Dimensioni</h3>
<h3 className="text-sm font-medium">Dimensions</h3>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
@@ -400,7 +400,7 @@ export function NitroEditorDialog({
htmlFor="dim-x"
className="text-xs text-muted-foreground"
>
X (larghezza)
X (width)
</Label>
<Input
id="dim-x"
@@ -432,7 +432,7 @@ export function NitroEditorDialog({
htmlFor="dim-z"
className="text-xs text-muted-foreground"
>
Z (altezza)
Z (height)
</Label>
<Input
id="dim-z"
@@ -451,7 +451,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<MousePointerClick className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Interazione</h3>
<h3 className="text-sm font-medium">Interaction</h3>
</div>
<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">
@@ -489,9 +489,9 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Compass className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Direzioni</h3>
<h3 className="text-sm font-medium">Directions</h3>
<span className="text-xs text-muted-foreground ml-auto">
{directions.length} attive
{directions.length} active
</span>
</div>
<div className="flex items-center justify-center">
@@ -541,7 +541,7 @@ export function NitroEditorDialog({
<section className="rounded-lg border bg-card p-4">
<div className="flex items-center gap-2 mb-3">
<Eye className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Tipo</h3>
<h3 className="text-sm font-medium">Types</h3>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
@@ -663,7 +663,7 @@ export function NitroEditorDialog({
<Palette className="w-4 h-4 text-muted-foreground" />
<h3 className="text-sm font-medium">Colori</h3>
<Badge variant="secondary" className="text-[10px] ml-auto">
{colorCount} varianti
{colorCount} colors
</Badge>
</div>
<div className="space-y-3">
@@ -672,7 +672,7 @@ export function NitroEditorDialog({
<div key={colorId} className="rounded-md border p-3">
<div className="flex items-center gap-2 mb-2">
<span className="text-xs font-medium">
Variante #{colorId}
Color Variant #{colorId}
</span>
{/* Color preview dots */}
<div className="flex gap-1 ml-auto">
@@ -784,7 +784,7 @@ export function NitroEditorDialog({
variant="secondary"
className="text-[10px] gap-1 animate-[pulse_1s_ease-in-out_1]"
>
Modifiche non salvate
Unsaved changes
</Badge>
)}
<div className="flex-1" />
+41 -13
View File
@@ -24,6 +24,7 @@ import {
deleteRoomItem,
roomRconAction,
} from "@/actions/rooms";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
@@ -91,6 +92,7 @@ function isWallType(t: string) {
export function FurniClient({ room, items = [], canEdit }: Props) {
const { run, isPending } = useServerAction();
const { confirm, dialog: confirmDialog } = useConfirmDialog();
const [search, setSearch] = useState("");
const [page, setPage] = useState(1);
const [view, setView] = useState<View>("flat");
@@ -231,29 +233,44 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
setSelected(next);
}
function handleRcon(action: "reload" | "kick") {
if (action === "kick" && !confirm("Kick all users from this room?")) return;
async function handleRcon(action: "reload" | "kick") {
if (action === "kick") {
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 }), {
successMessage:
action === "reload" ? "Room reloaded" : "All users kicked",
});
}
function handleDelete(itemId: number, name: string) {
if (!confirm(`Delete "${name}" (#${itemId}) from this room?`)) return;
async function handleDelete(itemId: number, name: string) {
const ok = await confirm({
title: "Delete Item",
description: `Delete "${name}" (#${itemId}) from this room?`,
confirmLabel: "Delete",
variant: "danger",
});
if (!ok) return;
run(() => deleteRoomItem({ roomId: room.id, itemId }), {
successMessage: "Item deleted",
});
}
function handleBulkDelete() {
async function handleBulkDelete() {
if (selected.size === 0) return;
if (
!confirm(
`Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`,
)
)
return;
const ok = await confirm({
title: "Delete Items",
description: `Delete ${selected.size} selected item${selected.size > 1 ? "s" : ""}?`,
confirmLabel: "Delete",
variant: "danger",
});
if (!ok) return;
run(
() =>
bulkDeleteRoomItems({ roomId: room.id, itemIds: Array.from(selected) }),
@@ -264,8 +281,18 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
);
}
function handleDeleteGroup(_baseId: number, ids: number[], name: string) {
if (!confirm(`Delete all ${ids.length} "${name}" from this room?`)) return;
async function handleDeleteGroup(
_baseId: number,
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 }), {
successMessage: `${ids.length} item(s) deleted`,
});
@@ -276,6 +303,7 @@ export function FurniClient({ room, items = [], canEdit }: Props) {
return (
<div className="space-y-6">
{confirmDialog}
{/* ── Header ─────────────────────────────────────────── */}
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-4">
+12 -6
View File
@@ -12,6 +12,7 @@ import {
} from "lucide-react";
import { useForm } from "react-hook-form";
import { deleteRoom, roomRconAction, updateRoom } from "@/actions/rooms";
import { useConfirmDialog } from "@/components/admin/confirm-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -63,13 +64,17 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
});
}
function handleDelete() {
if (
!confirm(
const { confirm, dialog: confirmDialog } = useConfirmDialog();
async function handleDelete() {
const ok = await confirm({
title: "Delete Room",
description:
"Are you sure you want to delete this room? This cannot be undone.",
)
)
return;
confirmLabel: "Delete",
variant: "danger",
});
if (!ok) return;
run(() => deleteRoom({ id: room.id }), { redirectTo: "/admin/rooms" });
}
@@ -82,6 +87,7 @@ export function RoomEditForm({ room }: RoomEditFormProps) {
return (
<div className="space-y-4">
{confirmDialog}
<div className="grid gap-6 lg:grid-cols-2">
{/* Edit Form */}
<Card>
+1 -1
View File
@@ -271,7 +271,7 @@ export function SoundsClient({
onEnded={() => setPlayingId(null)}
onError={() =>
toast.error(
`Impossibile riprodurre "${s.code}.mp3" da ${baseUrl}.`,
`Failed to play "${s.code}.mp3" from ${baseUrl}.`,
)
}
/>
+2 -2
View File
@@ -100,7 +100,7 @@ export function TraxPlayer({
const AudioCtor = window.AudioContext;
if (!AudioCtor) {
toast.error("Web Audio API non supportata da questo browser.");
toast.error("Web Audio API is not supported by this browser.");
setStatus("error");
return;
}
@@ -137,7 +137,7 @@ export function TraxPlayer({
if (failed > 0) {
toast.warning(
`${failed}/${uniqueIds.length} sample non caricati — la riproduzione potrebbe avere buchi.`,
`${failed}/${uniqueIds.length} samples failed to load — playback may have gaps.`,
);
}
if (failed === uniqueIds.length) {
+7 -5
View File
@@ -1,4 +1,4 @@
import { and, asc, count, like, or, type SQL } from "drizzle-orm";
import { and, asc, count, like, or, type SQL, sql } from "drizzle-orm";
import { ExternalLink } from "lucide-react";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
@@ -34,10 +34,12 @@ export default async function EmulatorTranslationsPage({
const perPage = Math.min(Math.max(parseInt(sp.perPage || "50", 10), 10), 200);
const page = Math.max(parseInt(sp.page || "1", 10), 1);
const patternFilters = or(
...TRANSLATION_KEY_PATTERNS.map((p) => like(EmulatorSettings.key, `${p}%`)),
);
if (!patternFilters) throw new Error("No emulator translation key patterns");
const patternFilters =
or(
...TRANSLATION_KEY_PATTERNS.map((p) =>
like(EmulatorSettings.key, `${p}%`),
),
) ?? sql`1=0`;
const conditions: SQL[] = [patternFilters];
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 { apiError } from "@/lib/api-response";
import { db } from "@/lib/db";
import { PERMS } from "@/lib/permission-slugs";
import { PERMS } from "@/lib/permissions";
const VALID_REPORTS = new Set(["registrations", "online-by-hour", "economy"]);
+26 -9
View File
@@ -1,17 +1,34 @@
import { NextResponse } from "next/server";
import { fetchOpsHealth } from "@/lib/admin/ops-health";
import { withAdmin } from "@/lib/api-handler";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
export const GET = withAdmin({ permission: PERMS.DEVOPS_VIEW }, async () => {
const health = await fetchOpsHealth();
try {
const health = await fetchOpsHealth();
return NextResponse.json({
database: health.dbOk,
dbLatency: health.dbLatencyMs,
redis: health.redisOk,
emulator: health.emulatorOk,
onlineUsers: health.onlineUsers,
timestamp: new Date().toISOString(),
});
return NextResponse.json({
database: health.dbOk,
dbLatency: health.dbLatencyMs,
redis: health.redisOk,
emulator: health.emulatorOk,
onlineUsers: health.onlineUsers,
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 },
);
}
});
+5 -4
View File
@@ -1,4 +1,5 @@
import { withAdmin } from "@/lib/api-handler";
import { logger } from "@/lib/logger";
import { PERMS } from "@/lib/permissions";
import { runCatalogAudit } from "@/lib/services/catalog-audit";
@@ -32,8 +33,8 @@ export const POST = withAdmin(
applySql = body.applySql === true;
repairFurniData = body.repairFurniData === true;
repairStructure = body.repairStructure === true;
} catch {
/* no body */
} catch (err) {
logger.warn("Failed to parse audit request body", { err });
}
const stream = new ReadableStream({
@@ -64,8 +65,8 @@ export const POST = withAdmin(
try {
controller.close();
} catch {
/* ignore */
} catch (err) {
logger.warn("Failed to close audit SSE stream", { err });
}
},
});
@@ -7,6 +7,15 @@ import { getSource } from "@/lib/services/clone-sources";
// In-process cache of extracted icons, keyed by source+classname.
// null = known-missing (don't refetch the bundle every render).
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>
// Fetches the source's .nitro bundle and returns the embedded furni icon as a
@@ -39,6 +48,7 @@ export const GET = withAdmin(
}
icon = extractFurniIconPng(Buffer.from(await res.arrayBuffer()));
iconCache.set(cacheKey, icon);
pruneIconCache();
} catch {
iconCache.set(cacheKey, null);
return apiError("Failed to fetch bundle", 502);
+18 -12
View File
@@ -76,8 +76,15 @@ export const POST = withAdmin(
{ permission: PERMS.ASSETS_IMPORT },
async (request, ctx) => {
const body = await request.json();
const { name, furnidataUrl, nitroBaseUrl, iconBaseUrl, hotel, id } =
body as Record<string, string>;
const {
name,
furnidataUrl,
nitroBaseUrl,
iconBaseUrl,
hotel,
id,
sourceSwfBaseUrl,
} = body as Record<string, string>;
const isHttps = (u: string) => {
try {
@@ -89,22 +96,21 @@ export const POST = withAdmin(
if (!name?.trim()) return apiError("name is required", 400);
if (!furnidataUrl?.trim()) return apiError("furnidataUrl is required", 400);
if (!nitroBaseUrl?.trim()) return apiError("nitroBaseUrl is required", 400);
if (!iconBaseUrl?.trim()) return apiError("iconBaseUrl is required", 400);
if (
!isHttps(furnidataUrl) ||
!isHttps(nitroBaseUrl) ||
!isHttps(iconBaseUrl)
)
return apiError("Source URLs must be valid https:// URLs", 400);
const normalized = (u: string | undefined) =>
(u ?? "").trim().replace(/\/+$/, "");
if (!isHttps(furnidataUrl))
return apiError("furnidataUrl must be a valid https:// URL", 400);
const entry = await upsertSource({
id,
name,
furnidataUrl,
nitroBaseUrl,
iconBaseUrl,
nitroBaseUrl: normalized(nitroBaseUrl),
iconBaseUrl: normalized(iconBaseUrl),
hotel: hotel ?? "",
sourceSwfBaseUrl: normalized(sourceSwfBaseUrl),
});
logAudit({
@@ -2,6 +2,7 @@ import { withAdmin } from "@/lib/api-handler";
import { apiError } from "@/lib/api-response";
import { PERMS } from "@/lib/permissions";
import { logAudit } from "@/lib/services/audit";
import { getSource } from "@/lib/services/clone-sources";
import { appendFurniEntriesBatch } from "@/lib/services/furni-data";
import {
ensureDirectories,
@@ -31,9 +32,16 @@ export const POST = withAdmin(
const body = await request.json();
const rawItems: BatchItem[] = body.items || [];
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);
// 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
// items_base.id when the same item is listed twice in the request body.
const seen = new Set<string>();
@@ -94,6 +102,9 @@ export const POST = withAdmin(
revision: item.revision ?? 0,
category: item.category ?? "unknown",
skipFurniDataWrite: true,
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl,
iconBaseUrl: source?.iconBaseUrl,
onProgress: (status: string) => {
send({
type: "item_progress",
+27 -1
View File
@@ -6,6 +6,7 @@ import { apiError, apiOk } from "@/lib/api-response";
import { CatalogPages, db, ItemsBase } from "@/lib/db";
import { PERMS } from "@/lib/permissions";
import { logAudit } from "@/lib/services/audit";
import { getSource } from "@/lib/services/clone-sources";
import { getFurniAssetDirs } from "@/lib/services/furni-asset-dirs";
import {
autoPriceFurni,
@@ -17,6 +18,7 @@ import {
ensureDirectories,
IMPORTED_PAGE_CAPTION_SAVE,
importSingleFurni,
resetCatalogPageCache,
} from "@/lib/services/furni-import";
import { getOfficialHabboFurnidata } from "@/lib/services/habbo-furnidata-cache";
import { listFurniture } from "@/lib/services/habbofurni";
@@ -260,6 +262,10 @@ export const POST = withAdmin(
// ── Batch import ─────────────────────────────────────────────────
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<{
classname: string;
ok: boolean;
@@ -291,6 +297,9 @@ export const POST = withAdmin(
type: item.type ?? "flooritem",
revision: item.revision ?? 0,
category: item.category ?? "unknown",
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl || undefined,
iconBaseUrl: source?.iconBaseUrl || undefined,
});
results.push({ classname: item.classname, ...result });
@@ -341,10 +350,22 @@ export const POST = withAdmin(
}
// ── Single import ────────────────────────────────────────────────
const { id, classname, name, description, type, revision, category } = body;
const {
id,
classname,
name,
description,
type,
revision,
category,
sourceId,
} = body;
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({
id: id ?? 0,
classname,
@@ -353,6 +374,9 @@ export const POST = withAdmin(
type: type ?? "flooritem",
revision: revision ?? 0,
category: category ?? "unknown",
sourceSwfBaseUrl: source?.sourceSwfBaseUrl,
nitroBaseUrl: source?.nitroBaseUrl || undefined,
iconBaseUrl: source?.iconBaseUrl || undefined,
});
if (!result.ok) return apiError(result.error ?? "Import failed", 409);
@@ -797,6 +821,8 @@ export const PUT = withAdmin(
}
if (!isDryRun) {
// Clear in-memory catalog page cache since we may have created/deleted pages
resetCatalogPageCache();
logAudit({
userId: ctx.session.user.id,
action: "furni_reorganize",
+1 -1
View File
@@ -12,7 +12,7 @@ export const GET = withAdmin(
{ permission: PERMS.ASSETS_IMPORT },
async (request) => {
if (request.nextUrl.searchParams.get("action") === "stats")
return apiOk(getPetStats());
return apiOk(await getPetStats());
const search = request.nextUrl.searchParams.get("search") || "";
return apiOk({ pets: getPetList(search) });
},
@@ -14,9 +14,7 @@ export const GET = withAdmin({ permission: PERMS.PREFIXES_VIEW }, async () => {
sql`SELECT id, word FROM custom_prefix_blacklist ORDER BY word ASC`,
)) as unknown as [BlacklistWord[], unknown];
return apiOk({
words: words.map((w) => ({ ...w, created_at: "" })),
});
return apiOk({ words });
});
export const POST = withAdmin(
-1
View File
@@ -52,7 +52,6 @@ export const GET = withAdmin(
icon: p.icon || "",
effect: p.effect || "",
active: Boolean(p.active),
created_at: "",
})),
total,
page,
+95
View File
@@ -0,0 +1,95 @@
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 });
},
);
+45 -58
View File
@@ -8,6 +8,16 @@ export interface CloneSource {
nitroBaseUrl: string;
iconBaseUrl: 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";
@@ -15,17 +25,11 @@ const KEY = "clone_sources";
/**
* Verified sources. Used as the default list and as the fallback when the
* `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[] = [
{
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",
name: "Habbo (COM)",
@@ -90,78 +94,59 @@ export const DEFAULT_SOURCES: CloneSource[] = [
iconBaseUrl: "",
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",
name: "Wibbo",
furnidataUrl: "https://assets.wibbo.org/gamedata/FurnitureData.json",
nitroBaseUrl: "https://assets.wibbo.org/bundled/furniture",
iconBaseUrl: "https://assets.wibbo.org/icons",
nitroBaseUrl: "",
iconBaseUrl: "",
hotel: "com",
},
{
id: "default-hubba",
name: "Hubba.cc",
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: "",
iconBaseUrl: "",
hotel: "com",
},
{
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",
id: "default-habblet-city",
name: "Habblet City",
furnidataUrl: "https://www.habblet.city/gamedata/furnidata.json",
nitroBaseUrl: "https://www.habblet.city/nitro/bundled/furniture",
iconBaseUrl: "https://www.habblet.city/nitro/icons",
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-habbo-retro",
name: "Habbo Retro",
furnidataUrl:
"https://raw.githubusercontent.com/Izzxt/habbo-resource/master/gamedata/furnidata.json",
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: "",
id: "default-virtualcity",
name: "VirtualCity",
furnidataUrl: "https://virtualc.nl/gamedata/furnidata_json/1",
nitroBaseUrl: "https://virtualc.nl/nitro/bundled/furniture",
iconBaseUrl: "https://virtualc.nl/nitro/icons",
hotel: "com",
sourceSwfBaseUrl: "https://virtualc.nl/dcr",
},
];
@@ -187,6 +172,7 @@ export async function upsertSource(
src: Omit<CloneSource, "id"> & { id?: string },
): Promise<CloneSource> {
const sources = await listSources();
const swfBase = src.sourceSwfBaseUrl?.trim().replace(/\/+$/, "");
const entry: CloneSource = {
id: src.id || randomUUID(),
name: src.name.trim(),
@@ -194,6 +180,7 @@ export async function upsertSource(
nitroBaseUrl: src.nitroBaseUrl.trim().replace(/\/+$/, ""),
iconBaseUrl: src.iconBaseUrl.trim().replace(/\/+$/, ""),
hotel: (src.hotel ?? "").trim(),
sourceSwfBaseUrl: swfBase || undefined,
};
const idx = sources.findIndex((s) => s.id === entry.id);
if (idx >= 0) sources[idx] = entry;
+48 -1
View File
@@ -28,7 +28,12 @@ vi.mock("@/lib/services/swf-to-nitro", () => ({
extractIconFromSwf: vi.fn(),
}));
import { buildItemsBaseEnrichmentUpdate } from "./furni-import";
import {
autoPriceFurni,
buildItemsBaseEnrichmentUpdate,
classifyFurni,
resetCatalogPageCache,
} from "./furni-import";
describe("buildItemsBaseEnrichmentUpdate", () => {
it("only updates columns present in the live Arcturus items_base schema", () => {
@@ -50,3 +55,45 @@ describe("buildItemsBaseEnrichmentUpdate", () => {
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();
});
});
+138 -31
View File
@@ -182,14 +182,21 @@ 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> {
if (parentIdCache !== null) return parentIdCache;
const [existing] = await db
.select({ id: CatalogPages.id })
.from(CatalogPages)
.where(eq(CatalogPages.captionSave, IMPORTED_PAGE_CAPTION_SAVE))
.limit(1);
if (existing) return existing.id;
if (existing) {
parentIdCache = existing.id;
return existing.id;
}
// 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
@@ -207,6 +214,7 @@ export async function getOrCreateImportedParentPage(): Promise<number> {
'Failed to create "Imported Furniture" parent catalog page',
);
}
parentIdCache = created.id;
return created.id;
}
@@ -281,6 +289,21 @@ let catalogIdLastUsed = 0;
let catalogIdSeedChain: Promise<void> = Promise.resolve();
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
* 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
@@ -326,7 +349,10 @@ export function __resetCatalogIdAllocatorForTests(): void {
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(
classname: string,
itemType: string,
@@ -334,6 +360,17 @@ export async function getOrCreateCategoryPage(
const parentId = await getOrCreateImportedParentPage();
const catKey = classifyFurni(classname, itemType);
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 [existing] = await db
@@ -346,7 +383,11 @@ export async function getOrCreateCategoryPage(
),
)
.limit(1);
if (existing) return existing.id;
if (existing) {
if (!categoryPageCache) categoryPageCache = new Map();
categoryPageCache.set(captionSave, existing.id);
return existing.id;
}
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)
@@ -368,6 +409,8 @@ export async function getOrCreateCategoryPage(
`Failed to create catalog sub-page "${captionSave}" under parent ${parentId}`,
);
}
if (!categoryPageCache) categoryPageCache = new Map();
categoryPageCache.set(captionSave, created.id);
return created.id;
}
@@ -383,6 +426,11 @@ export async function importSingleFurni(params: {
category: string;
skipFurniDataWrite?: boolean;
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> {
const {
id: originalId,
@@ -394,6 +442,9 @@ export async function importSingleFurni(params: {
category,
skipFurniDataWrite,
onProgress,
sourceSwfBaseUrl,
nitroBaseUrl: sourceNitroBaseUrl,
iconBaseUrl: sourceIconBaseUrl,
} = params;
const warnings: string[] = [];
@@ -495,33 +546,71 @@ export async function importSingleFurni(params: {
// fall back to base-classname icon (Nitro reuses base for all colors
// when no color-specific icon exists).
onProgress?.("downloading");
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`;
const downloadResults = await Promise.allSettled([
downloadFile(iconUrl, iconPath, { validate: "png" }),
downloadFile(
`https://images.habbo.com/dcr/hof_furni/${rev}/${encodeURIComponent(safeSwfName)}.swf`,
swfPath,
{ validate: "swf" },
),
]);
// Build candidate URL lists — source-specific URLs first, then Habbo CDN fallback
const iconUrls: string[] = [];
const swfUrls: string[] = [];
let iconOk =
downloadResults[0].status === "fulfilled" && downloadResults[0].value.ok;
const swfOk =
downloadResults[1].status === "fulfilled" && downloadResults[1].value.ok;
// 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" },
// Source-specific icon URLs
if (sourceIconBaseUrl) {
// e.g. https://habblet.city/nitro/icons/{classname}_icon.png
iconUrls.push(
`${sourceIconBaseUrl}/${encodeURIComponent(iconColorAware)}_icon.png`,
`${sourceIconBaseUrl}/${encodeURIComponent(baseClassname)}_icon.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 ────────────
@@ -531,7 +620,8 @@ export async function importSingleFurni(params: {
const iconPng = extractIconFromSwf(swfBuf, baseClassname);
if (iconPng) {
await fs.writeFile(/*turbopackIgnore: true*/ iconPath, iconPng);
warnings.push("Icon extracted from SWF (external download failed)");
iconOk = true;
warnings.push("Icon extracted from SWF (download failed)");
} else {
warnings.push(
"Icon download failed and SWF icon extraction returned nothing",
@@ -544,7 +634,7 @@ export async function importSingleFurni(params: {
warnings.push("Icon image download failed");
}
if (!swfOk) warnings.push("SWF download failed");
if (!swfOk && !nitroDownloadOk) warnings.push("SWF download failed");
// ── Convert SWF to Nitro ──────────────────────────────────────────
onProgress?.("converting");
@@ -577,8 +667,25 @@ export async function importSingleFurni(params: {
}
}
// ── Rollback: if conversion failed AND no .nitro exists, remove DB record ──
if (!existsSync(/*turbopackIgnore: true*/ nitroPath) && !conversionResult) {
// ── Rollback: if conversion/download failed AND no .nitro exists, remove DB record ──
// Also validate that the .nitro file is non-trivial (≥ 128 bytes — a bare
// 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 {
await db.execute(
sql`DELETE FROM items_base WHERE id = ${spriteId} AND item_name = ${classname}`,
+8 -5
View File
@@ -154,11 +154,14 @@ export async function batchLookupByClassnames(
const result = new Map<string, HabboFurniItem>();
if (classnames.length === 0) return result;
for (const cn of classnames) {
const item = await getFurnitureByClassname(cn);
if (item?.name) {
result.set(cn, item);
}
// Parallel lookup — all share the same in-memory furnidata cache
const lookedUp = await Promise.all(
classnames.map((cn) => getFurnitureByClassname(cn)),
);
for (let i = 0; i < classnames.length; i++) {
const item = lookedUp[i];
if (item?.name) result.set(classnames[i], item);
}
return result;