feat: connect guarded asset import api

This commit is contained in:
Simo committed 2026-07-12 19:12:25 +02:00
1 parent 3497df9dfd
commit eb759f54bf
26 files changed
+2342 -24

No files matched your search

@@ -0,0 +1,231 @@
import { existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import { withAdmin } from '@/lib/api-handler'
import { apiError } from '@/lib/api-response'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { getFurniAssetDirs } from '@/lib/services/furni-asset-dirs'
import { appendFurniEntriesBatch, buildFurniEntry, readFurniData } from '@/lib/services/furni-data'
import { downloadFile, ensureDirectories } from '@/lib/services/furni-import'
import { getHabboItFurnidata } from '@/lib/services/habbo-furnidata-cache'
import { rcon } from '@/lib/services/rcon'
import { convertSwfToNitro } from '@/lib/services/swf-to-nitro'
interface RegenItem {
classname: string
revision: number
}
/**
* SSE batch regenerate .nitro files.
* Streams progress events for each item.
*/
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request) => {
const body = await request.json()
const items: RegenItem[] = body.items || []
const concurrency = Math.min(Math.max(body.concurrency || 3, 1), 5)
if (items.length === 0) return apiError('No items to regenerate', 400)
await ensureDirectories()
const { swfDir, nitroDir } = await getFurniAssetDirs()
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
const send = (data: unknown) => {
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
} catch {
/* stream closed */
}
}
const startTime = Date.now()
send({ type: 'regen_start', total: items.length })
let succeeded = 0
let failed = 0
let skipped = 0
const furniDataEntries: Array<{ entry: Record<string, unknown>; itemType: string }> = []
// Load furnidata once for all items
const furnidata = await getHabboItFurnidata()
// Load existing FurnitureData.json classnames for dedup
const existingFD = (await readFurniData()) as {
roomitemtypes?: { furnitype?: Array<{ classname?: string }> }
wallitemtypes?: { furnitype?: Array<{ classname?: string }> }
}
const fdClassnames = new Set([
...(existingFD.roomitemtypes?.furnitype || []).map((e) => e.classname),
...(existingFD.wallitemtypes?.furnitype || []).map((e) => e.classname),
])
for (let i = 0; i < items.length; i += concurrency) {
const chunk = items.slice(i, i + concurrency)
const promises = chunk.map(async (item) => {
const starIdx = item.classname.indexOf('*')
const baseClassname =
starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname
const nitroPath = path.join(/*turbopackIgnore: true*/ nitroDir, `${baseClassname}.nitro`)
if (existsSync(/*turbopackIgnore: true*/ nitroPath)) {
skipped++
send({ type: 'regen_progress', classname: item.classname, status: 'skipped' })
return
}
send({ type: 'regen_progress', classname: item.classname, status: 'downloading' })
// Resolve revision
let rev = item.revision || 0
if (rev === 0) {
const fd =
furnidata.get(item.classname) ||
furnidata.get(baseClassname) ||
furnidata.get(`${baseClassname}*0`)
if (fd) rev = fd.revision
}
// Try spriteId as fallback revision
const revsToTry: number[] = []
if (rev > 0) revsToTry.push(rev)
const dbItem = await prisma.itemsBase.findFirst({
where: { itemName: item.classname },
select: { id: true, spriteId: true, publicName: true, type: true },
})
if (dbItem?.spriteId && !revsToTry.includes(dbItem.spriteId)) {
revsToTry.push(dbItem.spriteId)
}
if (revsToTry.length === 0) {
failed++
send({
type: 'regen_progress',
classname: item.classname,
status: 'failed',
message: 'No revision found',
})
return
}
const swfPath = path.join(swfDir, `${baseClassname}.swf`)
// Download SWF if needed
if (!existsSync(swfPath)) {
let downloaded = false
for (const tryRev of revsToTry) {
const dl = await downloadFile(
`https://images.habbo.com/dcr/hof_furni/${tryRev}/${encodeURIComponent(baseClassname)}.swf`,
swfPath,
{ validate: 'swf' },
)
if (dl.ok) {
rev = tryRev
downloaded = true
break
}
}
if (!downloaded) {
failed++
send({
type: 'regen_progress',
classname: item.classname,
status: 'failed',
message: `SWF not found (revs: ${revsToTry.join(', ')})`,
})
return
}
}
// Convert
send({ type: 'regen_progress', classname: item.classname, status: 'converting' })
try {
const swfBuffer = await fs.readFile(swfPath)
const conversion = convertSwfToNitro(swfBuffer, baseClassname)
await fs.writeFile(nitroPath, conversion.bundle)
// Build FurnitureData entry if missing
if (!fdClassnames.has(baseClassname) && !fdClassnames.has(item.classname)) {
const fd = furnidata.get(item.classname) || furnidata.get(baseClassname)
const itemType = dbItem?.type === 'i' ? 'i' : 's'
const entry = buildFurniEntry({
id: dbItem?.spriteId || 0,
classname: baseClassname,
revision: rev,
category: fd?.category || '',
name: dbItem?.publicName || baseClassname,
description: fd?.description || '',
spriteId: dbItem?.spriteId || 0,
dims: conversion.dimensions || { x: 1, y: 1, z: 1 },
metadata: conversion.metadata || null,
habboIt: fd || null,
})
furniDataEntries.push({ entry, itemType })
fdClassnames.add(baseClassname)
}
succeeded++
send({ type: 'regen_progress', classname: item.classname, status: 'done' })
} catch (err) {
failed++
send({
type: 'regen_progress',
classname: item.classname,
status: 'failed',
message: (err as Error).message,
})
}
})
await Promise.allSettled(promises)
}
// Batch write FurnitureData.json
if (furniDataEntries.length > 0) {
try {
await appendFurniEntriesBatch(furniDataEntries)
send({
type: 'regen_info',
message: `Added ${furniDataEntries.length} entries to FurnitureData.json`,
})
} catch (err) {
send({
type: 'regen_info',
message: `FurnitureData.json write failed: ${(err as Error).message}`,
})
}
}
// RCON refresh
try {
await rcon.updateItems()
await rcon.updateCatalog()
} catch {
/* non-fatal */
}
send({
type: 'regen_complete',
succeeded,
failed,
skipped,
furniDataAdded: furniDataEntries.length,
duration: Date.now() - startTime,
})
controller.close()
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
})
})
@@ -0,0 +1,198 @@
import { withAdmin } from '@/lib/api-handler'
import { apiError } from '@/lib/api-response'
import { PERMS } from '@/lib/permissions'
import { logAudit } from '@/lib/services/audit'
import { appendFurniEntriesBatch } from '@/lib/services/furni-data'
import { ensureDirectories, importSingleFurni } from '@/lib/services/furni-import'
import { rcon } from '@/lib/services/rcon'
import type { ImportSingleResult } from '@/types/furni'
interface BatchItem {
id: number
classname: string
name: string
description: string
type: string
revision: number
category: string
}
/**
* SSE batch import endpoint.
* Processes multiple furniture items with configurable concurrency,
* streaming real-time progress events to the client.
*/
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request, ctx) => {
const body = await request.json()
const rawItems: BatchItem[] = body.items || []
const concurrency = Math.min(Math.max(body.concurrency || 3, 1), 5)
if (rawItems.length === 0) return apiError('No items to import', 400)
// 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>()
const items: BatchItem[] = []
for (const it of rawItems) {
const key = `${it.id}:${it.classname}`
if (seen.has(key)) continue
seen.add(key)
items.push(it)
}
await ensureDirectories()
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
const send = (data: unknown) => {
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
} catch {
/* stream closed by client */
}
}
const startTime = Date.now()
send({ type: 'batch_start', total: items.length, concurrency })
let succeeded = 0
let failed = 0
let withWarnings = 0
const furniDataEntries: Array<{ entry: Record<string, unknown>; itemType: string }> = []
// Process in chunks of `concurrency`
for (let i = 0; i < items.length; i += concurrency) {
const chunk = items.slice(i, i + concurrency)
const promises = chunk.map(async (item, chunkIdx) => {
const index = i + chunkIdx
send({ type: 'item_progress', classname: item.classname, status: 'started', index })
try {
const result: ImportSingleResult = await importSingleFurni({
id: item.id ?? 0,
classname: item.classname,
name: item.name,
description: item.description ?? '',
type: item.type ?? 'flooritem',
revision: item.revision ?? 0,
category: item.category ?? 'unknown',
skipFurniDataWrite: true,
onProgress: (status: string) => {
send({ type: 'item_progress', classname: item.classname, status, index })
},
})
if (result.ok) {
succeeded++
if (result.warnings.length > 0) withWarnings++
if (result.furniDataEntry) furniDataEntries.push(result.furniDataEntry)
send({
type: 'item_progress',
classname: item.classname,
status: 'done',
index,
itemId: result.itemId,
warnings: result.warnings.length > 0 ? result.warnings : undefined,
})
logAudit({
userId: ctx.session.user.id,
action: 'furni_import',
target: 'ItemsBase',
targetId: result.itemId!,
after: {
classname: item.classname,
name: item.name,
type: item.type === 'wallitem' ? 'i' : 's',
catalogItemId: result.catalogItemId,
dimensions: result.dimensions,
batch: true,
},
})
} else {
failed++
send({
type: 'item_progress',
classname: item.classname,
status: 'failed',
index,
message: result.error,
})
}
} catch (err) {
failed++
send({
type: 'item_progress',
classname: item.classname,
status: 'failed',
index,
message: (err as Error).message,
})
}
})
await Promise.allSettled(promises)
}
// Batch write FurnitureData.json once at the end — BEFORE RCON so the
// emulator never sees items that the Nitro client can't render.
let furniDataWriteOk = true
if (furniDataEntries.length > 0) {
try {
await appendFurniEntriesBatch(furniDataEntries)
} catch (err) {
furniDataWriteOk = false
send({
type: 'item_progress',
classname: '_batch_',
status: 'failed',
index: -1,
message: `FurnitureData.json batch write failed: ${(err as Error).message}`,
})
}
}
// Refresh game server caches once — skip if FurnitureData write failed
// to avoid an inconsistent state (emulator sees items, client doesn't).
if (furniDataWriteOk) {
try {
const okCat = await rcon.updateCatalog()
const okItems = await rcon.updateItems()
if (!okCat || !okItems) {
send({
type: 'item_progress',
classname: '_rcon_',
status: 'failed',
index: -1,
message: 'RCON refresh failed — emulator cache may be stale',
})
}
} catch (err) {
console.warn('[import-furni] RCON update failed after batch:', (err as Error).message)
}
}
send({
type: 'batch_complete',
succeeded,
failed,
warnings: withWarnings,
duration: Date.now() - startTime,
})
controller.close()
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
})
})
@@ -0,0 +1,166 @@
import { existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import type { NextRequest } from 'next/server'
import { withAdmin } from '@/lib/api-handler'
import { apiError, apiOk } from '@/lib/api-response'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { logAudit } from '@/lib/services/audit'
import { getFurniAssetDirs } from '@/lib/services/furni-asset-dirs'
import { readFurniData, withFurniDataLock, writeFurniData } from '@/lib/services/furni-data'
import { rcon } from '@/lib/services/rcon'
import {
computeDefaultDir,
createNitroBundle,
extractPartColors,
parseNitroBundle,
} from '@/lib/services/swf-to-nitro'
function baseClassname(classname: string): string {
return classname.includes('*') ? classname.split('*')[0] : classname
}
// ── GET: Read .nitro metadata ──────────────────────────────────────
export const GET = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request: NextRequest) => {
const rawClassname = request.nextUrl.searchParams.get('classname')
if (!rawClassname) return apiError('Missing classname', 400)
const base = baseClassname(rawClassname)
const { nitroDir } = await getFurniAssetDirs()
const nitroPath = path.join(/*turbopackIgnore: true*/ nitroDir, `${base}.nitro`)
if (!existsSync(/*turbopackIgnore: true*/ nitroPath)) return apiError('Nitro file not found', 404)
try {
const buffer = await fs.readFile(/*turbopackIgnore: true*/ nitroPath)
const { json } = parseNitroBundle(buffer)
// Fetch interaction flags from DB
const items = await prisma.$queryRaw<
Array<{
allow_sit: string
allow_lay: string
allow_walk: string
}>
>`
SELECT allow_sit, allow_lay, allow_walk
FROM items_base WHERE item_name = ${rawClassname} LIMIT 1
`
const dbRow = items[0]
const flags = {
canstandon: dbRow?.allow_walk === '1',
cansiton: dbRow?.allow_sit === '1',
canlayon: dbRow?.allow_lay === '1',
}
return apiOk({ metadata: json, flags })
} catch (err) {
console.error('[nitro-editor] Failed to parse .nitro:', (err as Error).message)
return apiError('Failed to parse .nitro file', 500)
}
})
// ── PUT: Save .nitro metadata ──────────────────────────────────────
export const PUT = withAdmin(
{ permission: PERMS.ASSETS_IMPORT },
async (request: NextRequest, ctx) => {
const body = await request.json()
const { classname: rawClassname, metadata, canstandon, cansiton, canlayon } = body
if (!rawClassname || !metadata) return apiError('Missing classname or metadata', 400)
const base = baseClassname(rawClassname)
const { nitroDir } = await getFurniAssetDirs()
const nitroPath = path.join(/*turbopackIgnore: true*/ nitroDir, `${base}.nitro`)
if (!existsSync(/*turbopackIgnore: true*/ nitroPath))
return apiError('Nitro file not found', 404)
// 1. Read existing .nitro to extract PNG
const existingBuffer = await fs.readFile(/*turbopackIgnore: true*/ nitroPath)
const { png } = parseNitroBundle(existingBuffer)
// 2. Rebuild .nitro with updated JSON + same PNG
const newBundle = createNitroBundle(metadata, png, base)
await fs.writeFile(nitroPath, newBundle)
// 3. Extract dimensions from metadata
const dims = metadata.logic?.model?.dimensions || { x: 1, y: 1, z: 0 }
const directions: number[] = metadata.logic?.model?.directions || [0]
const visualizations = metadata.visualizations || []
// 4. Update FurnitureData.json (best-effort)
try {
await withFurniDataLock(async () => {
const furniData = (await readFurniData()) as Record<
string,
{ furnitype: Array<Record<string, unknown>> }
>
for (const section of ['roomitemtypes', 'wallitemtypes'] as const) {
const types = furniData[section]?.furnitype
if (!Array.isArray(types)) continue
const idx = types.findIndex((e) => e.classname === rawClassname)
if (idx !== -1) {
types[idx].xdim = dims.x
types[idx].ydim = dims.y
types[idx].defaultdir = computeDefaultDir(directions)
types[idx].partcolors = extractPartColors(visualizations)
types[idx].canstandon = canstandon ?? false
types[idx].cansiton = cansiton ?? false
types[idx].canlayon = canlayon ?? false
break
}
}
await writeFurniData(furniData as Record<string, unknown>)
})
} catch (err) {
console.warn('[nitro-editor] FurnitureData.json update failed:', (err as Error).message)
}
// 5. Update items_base (best-effort)
try {
await prisma.$executeRaw`
UPDATE items_base
SET width = ${dims.x}, length = ${dims.y}, stack_height = ${dims.z},
allow_sit = ${cansiton ? '1' : '0'},
allow_lay = ${canlayon ? '1' : '0'},
allow_walk = ${canstandon ? '1' : '0'}
WHERE item_name = ${rawClassname}
`
} catch (err) {
console.warn('[nitro-editor] items_base update failed:', (err as Error).message)
}
// 6. RCON refresh (best-effort)
try {
await rcon.updateItems()
} catch (err) {
console.warn('[nitro-editor] RCON updateItems failed:', (err as Error).message)
}
// 7. Audit log
try {
const dbItem = await prisma.itemsBase.findFirst({
where: { itemName: rawClassname },
select: { id: true },
})
await logAudit({
userId: ctx.session.user.id,
action: 'furni_edit_nitro',
target: 'ItemsBase',
targetId: dbItem?.id ?? 0,
after: { classname: rawClassname, dimensions: dims, canstandon, cansiton, canlayon },
})
} catch (err) {
console.warn('[nitro-editor] Audit log failed:', (err as Error).message)
}
return apiOk({ dimensions: dims })
},
)
@@ -0,0 +1,203 @@
import { existsSync } from 'node:fs'
import { withAdmin } from '@/lib/api-handler'
import { apiOk } from '@/lib/api-response'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import {
appendFurniEntriesBatch,
buildFurniEntry,
getFurnitureDataPath,
readFurniData,
} from '@/lib/services/furni-data'
import { lookupHabboIt } from '@/lib/services/habbo-furnidata-cache'
import { rcon } from '@/lib/services/rcon'
/**
* POST /api/admin/import/furni/resync
*
* Modes (query params, pick one):
* ?days=N — items imported in the last N days (from admin_audit_log).
* ?missing=1 — every items_base row whose classname is absent from
* FurnitureData.json (authoritative for "what's broken").
* ?all=1 — every items_base row (rebuilds entries for all imports).
*
* Default: ?days=7
*
* Entries are upserted by classname so running this repeatedly is safe.
* Triggers RCON updateCatalog + updateItems at the end.
*/
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request) => {
const qp = request.nextUrl.searchParams
const mode: 'days' | 'missing' | 'broken' | 'all' =
qp.get('all') === '1'
? 'all'
: qp.get('broken') === '1'
? 'broken'
: qp.get('missing') === '1'
? 'missing'
: 'days'
const days = Math.max(1, Math.min(parseInt(qp.get('days') || '7', 10) || 7, 365))
const targetIds = await resolveTargetIds(mode, days)
if (targetIds.length === 0) {
return apiOk({
mode,
days: mode === 'days' ? days : undefined,
examined: 0,
resynced: 0,
failed: 0,
errors: [],
})
}
// Process in chunks to keep memory flat and make progress visible.
const CHUNK = 500
let resynced = 0
const errors: Array<{ classname: string; message: string }> = []
for (let i = 0; i < targetIds.length; i += CHUNK) {
const slice = targetIds.slice(i, i + CHUNK)
const rows = await prisma.itemsBase.findMany({
where: { id: { in: slice } },
select: {
id: true,
spriteId: true,
itemName: true,
publicName: true,
type: true,
width: true,
length: true,
stackHeight: true,
},
})
const entries: Array<{ entry: Record<string, unknown>; itemType: string }> = []
for (const row of rows) {
try {
const classname = row.itemName
let habboIt = null
try {
habboIt = await lookupHabboIt(classname)
} catch {
/* optional */
}
const entry = buildFurniEntry({
id: row.id,
classname,
revision: habboIt?.revision ?? 0,
category: habboIt?.category || 'unknown',
name: row.publicName || habboIt?.name || classname,
description: habboIt?.description || '',
spriteId: row.spriteId,
dims: { x: row.width, y: row.length, z: Math.round(Number(row.stackHeight)) },
metadata: null,
habboIt,
})
entries.push({ entry, itemType: row.type === 'i' ? 'i' : 's' })
} catch (err) {
errors.push({ classname: row.itemName, message: (err as Error).message })
}
}
if (entries.length > 0) {
try {
await appendFurniEntriesBatch(entries)
resynced += entries.length
} catch (err) {
errors.push({
classname: `_chunk_${i}_${i + slice.length}_`,
message: `FurnitureData.json write failed: ${(err as Error).message}`,
})
break
}
}
}
let rconOk = false
try {
const a = await rcon.updateCatalog()
const b = await rcon.updateItems()
rconOk = a && b
} catch {
/* logged in rcon service */
}
return apiOk({
mode,
days: mode === 'days' ? days : undefined,
examined: targetIds.length,
resynced,
failed: errors.length,
rconOk,
errors: errors.slice(0, 50),
})
})
async function resolveTargetIds(
mode: 'days' | 'missing' | 'broken' | 'all',
days: number,
): Promise<number[]> {
if (mode === 'all') {
const rows = await prisma.itemsBase.findMany({ select: { id: true }, orderBy: { id: 'asc' } })
return rows.map((r) => r.id)
}
if (mode === 'missing' || mode === 'broken') {
const furniDataPath = await getFurnitureDataPath()
if (!existsSync(furniDataPath)) {
const rows = await prisma.itemsBase.findMany({ select: { id: true }, orderBy: { id: 'asc' } })
return rows.map((r) => r.id)
}
const furniData = (await readFurniData()) as {
roomitemtypes?: { furnitype: Array<Record<string, unknown>> }
wallitemtypes?: { furnitype: Array<Record<string, unknown>> }
}
const byClassname = new Map<string, Record<string, unknown>>()
for (const section of [furniData.roomitemtypes, furniData.wallitemtypes]) {
for (const e of section?.furnitype ?? []) {
if (typeof e?.classname === 'string') byClassname.set(e.classname, e)
}
}
const rows = await prisma.itemsBase.findMany({
select: { id: true, itemName: true, spriteId: true, width: true, length: true },
orderBy: { id: 'asc' },
})
if (mode === 'missing') {
return rows.filter((r) => !byClassname.has(r.itemName)).map((r) => r.id)
}
// broken: entry present but inconsistent with items_base
return rows
.filter((r) => {
const e = byClassname.get(r.itemName)
if (!e) return true
const entryId = Number(e.id ?? -1)
if (entryId !== r.id && entryId !== r.spriteId) return true
const xdim = Number(e.xdim ?? 0)
const ydim = Number(e.ydim ?? 0)
if (xdim <= 0 || ydim <= 0) return true
if (xdim !== r.width || ydim !== r.length) return true
return false
})
.map((r) => r.id)
}
// mode === 'days'
const sinceIso = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString()
const sinceMysql = sinceIso.slice(0, 19).replace('T', ' ')
const auditRows = await prisma.$queryRaw<Array<{ target_id: number }>>`
SELECT DISTINCT target_id
FROM admin_audit_log
WHERE action = 'furni_import'
AND target = 'ItemsBase'
AND target_id IS NOT NULL
AND created_at >= ${sinceMysql}
ORDER BY target_id ASC
`
return auditRows.map((r) => r.target_id).filter(Boolean)
}
+713
View File
@@ -0,0 +1,713 @@
import { existsSync, promises as fs } from 'node:fs'
import path from 'node:path'
import { withAdmin } from '@/lib/api-handler'
import { apiError, apiOk } from '@/lib/api-response'
import { PERMS } from '@/lib/permissions'
import { prisma } from '@/lib/prisma'
import { logAudit } from '@/lib/services/audit'
import { getFurniAssetDirs } from '@/lib/services/furni-asset-dirs'
import {
autoPriceFurni,
CATEGORY_PAGE,
classifyFurni,
cleanupConvertedSwfs,
deleteImportedItem,
downloadFile,
ensureDirectories,
IMPORTED_PAGE_CAPTION_SAVE,
importSingleFurni,
} from '@/lib/services/furni-import'
import { getHabboItFurnidata } from '@/lib/services/habbo-furnidata-cache'
import { listFurniture } from '@/lib/services/habbofurni'
import { rcon } from '@/lib/services/rcon'
import { convertSwfToNitro } from '@/lib/services/swf-to-nitro'
// Re-export for batch route backward compatibility
export { ensureDirectories, importSingleFurni } from '@/lib/services/furni-import'
export type { ImportSingleResult } from '@/types/furni'
// ── Delete imported item or clean up SWF files ──────────────────────
export const DELETE = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request, ctx) => {
const classname = request.nextUrl.searchParams.get('classname')
// ── Delete specific imported item ─────────────────────────────────
if (classname) {
try {
const { spriteId, deletedFiles, errors } = await deleteImportedItem(classname)
// Refresh game server caches
try {
await rcon.updateCatalog()
await rcon.updateItems()
} catch (err) {
errors.push(`RCON: ${(err as Error).message}`)
}
logAudit({
userId: ctx.session.user.id,
action: 'furni_delete',
target: 'ItemsBase',
targetId: spriteId,
after: { classname, deletedFiles, errors: errors.length > 0 ? errors : undefined },
})
return apiOk({
classname,
deletedFiles,
errors: errors.length > 0 ? errors : undefined,
})
} catch (err) {
return apiError((err as Error).message, 404)
}
}
// ── Clean up SWF files that have been converted to Nitro ──────────
const result = await cleanupConvertedSwfs()
if (result.total === 0 && result.deleted === 0) {
return apiOk({ deleted: 0, message: 'SWF directory does not exist' })
}
return apiOk({
deleted: result.deleted,
total: result.total,
remaining: result.remaining,
errors: result.errors.length > 0 ? result.errors : undefined,
})
})
// ── Search furni via official Habbo furnidata ───────────────────────
export const GET = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request) => {
const { nitroDir } = await getFurniAssetDirs()
// Stats endpoint
const action = request.nextUrl.searchParams.get('action')
if (action === 'stats') {
const [totalResult, catalogResult, nitroMissingResult] = await Promise.all([
prisma.$queryRaw<[{ cnt: bigint }]>`SELECT COUNT(*) as cnt FROM items_base`,
prisma.$queryRaw<
[{ cnt: bigint }]
>`SELECT COUNT(DISTINCT item_ids) as cnt FROM catalog_items`,
prisma.$queryRaw<
[{ cnt: bigint }]
>`SELECT COUNT(*) as cnt FROM items_base WHERE item_name NOT IN (SELECT catalog_name FROM catalog_items)`,
])
const totalInDb = Number(totalResult[0].cnt)
const inCatalog = Number(catalogResult[0].cnt)
const notInCatalog = Number(nitroMissingResult[0].cnt)
// Count missing .nitro files by checking filesystem
const importedItems = await prisma.$queryRaw<Array<{ item_name: string }>>`
SELECT ib.item_name FROM items_base ib
INNER JOIN catalog_items ci ON ci.catalog_name = ib.item_name
LIMIT 10000
`
let missingNitro = 0
for (const item of importedItems) {
const starIdx = item.item_name.indexOf('*')
const base = starIdx !== -1 ? item.item_name.substring(0, starIdx) : item.item_name
const nitroPath = path.join(/*turbopackIgnore: true*/ nitroDir, `${base}.nitro`)
if (!existsSync(/*turbopackIgnore: true*/ nitroPath)) missingNitro++
}
return apiOk({ totalInDb, inCatalog, notInCatalog, missingNitro })
}
// Missing nitro endpoint: returns only imported items missing .nitro files
if (action === 'missing-nitro') {
const pageNum = parseInt(request.nextUrl.searchParams.get('page') || '1', 10)
const perPage = 50
const importedItems = await prisma.$queryRaw<
Array<{
item_name: string
public_name: string
sprite_id: number
type: string
}>
>`
SELECT ib.item_name, ib.public_name, ib.sprite_id, ib.type FROM items_base ib
INNER JOIN catalog_items ci ON ci.catalog_name = ib.item_name
`
// Filter to only those missing .nitro on filesystem
const missing = importedItems.filter((item) => {
const starIdx = item.item_name.indexOf('*')
const base = starIdx !== -1 ? item.item_name.substring(0, starIdx) : item.item_name
const p = path.join(/*turbopackIgnore: true*/ nitroDir, `${base}.nitro`)
return !existsSync(/*turbopackIgnore: true*/ p)
})
const total = missing.length
const lastPage = Math.max(Math.ceil(total / perPage), 1)
const start = (pageNum - 1) * perPage
const pageItems = missing.slice(start, start + perPage)
// Enrich with revision from official furnidata
const furnidata = await getHabboItFurnidata()
const items = pageItems.map((item) => {
const fd =
furnidata.get(item.item_name) ||
furnidata.get(item.item_name.split('*')[0]) ||
furnidata.get(`${item.item_name}*0`)
return {
id: item.sprite_id,
classname: item.item_name,
name: item.public_name || item.item_name,
description: fd?.description || '',
type: item.type === 'i' ? 'wallitem' : 'flooritem',
revision: fd?.revision || 0,
category: fd?.category || fd?.furniline || '',
alreadyImported: true,
nitroExists: false,
}
})
return apiOk({
items,
meta: { currentPage: pageNum, lastPage, total, perPage },
})
}
const search = request.nextUrl.searchParams.get('search') || ''
const page = parseInt(request.nextUrl.searchParams.get('page') || '1', 10)
// Pull every imported classname once so we can both (a) sort non-imported
// items to the top *before* pagination and (b) skip the per-page lookup
// below. Single-column indexed query — fast even at 10k+ rows.
const allImported = await prisma.itemsBase.findMany({
select: { itemName: true },
})
const importedSet = new Set(allImported.map((e) => e.itemName).filter((n): n is string => !!n))
const result = await listFurniture({
search: search || undefined,
page,
perPage: 50,
importedSet,
})
const enriched = result.items.map((item) => {
const imported = importedSet.has(item.classname)
let nitroExists = false
if (imported) {
const starIdx = item.classname.indexOf('*')
const base = starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname
const p = path.join(/*turbopackIgnore: true*/ nitroDir, `${base}.nitro`)
nitroExists = existsSync(/*turbopackIgnore: true*/ p)
}
return { ...item, alreadyImported: imported, nitroExists }
})
return apiOk({ items: enriched, meta: result.meta })
})
// ── Import furni (single or batch) ──────────────────────────────────
export const POST = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request, ctx) => {
const body = await request.json()
await ensureDirectories()
// ── Batch import ─────────────────────────────────────────────────
if (Array.isArray(body.items)) {
const results: Array<{
classname: string
ok: boolean
itemId?: number
catalogItemId?: number | null
dimensions?: { x: number; y: number; z: number }
spriteCount?: number
warnings: string[]
error?: string
}> = []
for (const item of body.items) {
if (!item.classname || !item.name) {
results.push({
classname: item.classname || 'unknown',
ok: false,
warnings: [],
error: 'Missing classname or name',
})
continue
}
try {
const result = await importSingleFurni({
id: item.id ?? 0,
classname: item.classname,
name: item.name,
description: item.description ?? '',
type: item.type ?? 'flooritem',
revision: item.revision ?? 0,
category: item.category ?? 'unknown',
})
results.push({ classname: item.classname, ...result })
if (result.ok) {
logAudit({
userId: ctx.session.user.id,
action: 'furni_import',
target: 'ItemsBase',
targetId: result.itemId!,
after: {
classname: item.classname,
name: item.name,
type: item.type === 'wallitem' ? 'i' : 's',
catalogItemId: result.catalogItemId,
dimensions: result.dimensions,
batch: true,
warnings: result.warnings.length > 0 ? result.warnings : undefined,
},
})
}
} catch (err) {
results.push({
classname: item.classname,
ok: false,
warnings: [],
error: (err as Error).message,
})
}
}
// Refresh caches once after batch
try {
await rcon.updateCatalog()
await rcon.updateItems()
} catch (err) {
console.warn('[import-furni] RCON update failed after batch:', (err as Error).message)
}
const succeeded = results.filter((r) => r.ok).length
const failed = results.filter((r) => !r.ok).length
return apiOk({ batch: true, succeeded, failed, results })
}
// ── Single import ────────────────────────────────────────────────
const { id, classname, name, description, type, revision, category } = body
if (!classname || !name) return apiError('Missing classname or name', 400)
const result = await importSingleFurni({
id: id ?? 0,
classname,
name,
description: description ?? '',
type: type ?? 'flooritem',
revision: revision ?? 0,
category: category ?? 'unknown',
})
if (!result.ok) return apiError(result.error!, 409)
// Refresh game server caches
try {
await rcon.updateCatalog()
await rcon.updateItems()
} catch (err) {
console.warn('[import-furni] RCON update failed:', (err as Error).message)
result.warnings.push('RCON cache refresh failed')
}
logAudit({
userId: ctx.session.user.id,
action: 'furni_import',
target: 'ItemsBase',
targetId: result.itemId!,
after: {
classname,
name,
spriteId: id ?? 0,
type: type === 'wallitem' ? 'i' : 's',
catalogItemId: result.catalogItemId,
dimensions: result.dimensions,
spriteCount: result.spriteCount,
warnings: result.warnings.length > 0 ? result.warnings : undefined,
},
})
return apiOk({
id: result.itemId,
catalogItemId: result.catalogItemId,
dimensions: result.dimensions,
spriteCount: result.spriteCount,
warnings: result.warnings.length > 0 ? result.warnings : undefined,
})
})
// ── Re-generate missing .nitro files (PATCH) ─────────────────────────
export const PATCH = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request) => {
const body = await request.json()
const items: Array<{ classname: string; revision: number }> = body.items || []
if (items.length === 0) return apiError('No items provided', 400)
await ensureDirectories()
const { swfDir, nitroDir } = await getFurniAssetDirs()
const results: Array<{ classname: string; ok: boolean; warning?: string }> = []
for (const item of items) {
const starIdx = item.classname.indexOf('*')
const baseClassname = starIdx !== -1 ? item.classname.substring(0, starIdx) : item.classname
const nitroPath = path.join(/*turbopackIgnore: true*/ nitroDir, `${baseClassname}.nitro`)
// Skip if .nitro already exists
if (existsSync(/*turbopackIgnore: true*/ nitroPath)) {
results.push({ classname: item.classname, ok: true, warning: 'Already exists' })
continue
}
// Resolve revision: try furnidata first, then spriteId as fallback
let rev = item.revision || 0
if (rev === 0) {
const furnidata = await getHabboItFurnidata()
const fd =
furnidata.get(item.classname) ||
furnidata.get(baseClassname) ||
furnidata.get(`${baseClassname}*0`)
if (fd) rev = fd.revision
}
const swfPath = path.join(swfDir, `${baseClassname}.swf`)
// Download SWF if not present — try multiple revision candidates
if (!existsSync(swfPath)) {
// Build list of revisions to try: known rev, spriteId, common fallbacks
const spriteId = await prisma.itemsBase.findFirst({
where: { itemName: item.classname },
select: { spriteId: true },
})
const revsToTry = [...new Set([rev, spriteId?.spriteId || 0].filter((r) => r > 0))]
let downloaded = false
for (const tryRev of revsToTry) {
const dl = await downloadFile(
`https://images.habbo.com/dcr/hof_furni/${tryRev}/${encodeURIComponent(baseClassname)}.swf`,
swfPath,
{ validate: 'swf' },
)
if (dl.ok) {
rev = tryRev
downloaded = true
break
}
}
if (!downloaded) {
results.push({
classname: item.classname,
ok: false,
warning: `SWF not found on Habbo CDN (tried revisions: ${revsToTry.join(', ') || 'none'})`,
})
continue
}
}
// Convert SWF → Nitro + update FurnitureData.json
try {
const swfBuffer = await fs.readFile(swfPath)
const conversion = convertSwfToNitro(swfBuffer, baseClassname)
await fs.writeFile(nitroPath, conversion.bundle)
// Add to FurnitureData.json if not already present
try {
const { buildFurniEntry, appendFurniEntry, readFurniData } = await import(
'@/lib/services/furni-data'
)
const furniData = (await readFurniData()) as {
roomitemtypes?: { furnitype?: Array<{ classname?: string }> }
wallitemtypes?: { furnitype?: Array<{ classname?: string }> }
}
// Check if already in FurnitureData
const allEntries = [
...(furniData.roomitemtypes?.furnitype || []),
...(furniData.wallitemtypes?.furnitype || []),
]
const alreadyInFD = allEntries.some(
(e) => e.classname === baseClassname || e.classname === item.classname,
)
if (!alreadyInFD) {
const dbItem = await prisma.itemsBase.findFirst({
where: { itemName: item.classname },
select: { id: true, spriteId: true, publicName: true, type: true },
})
const furnidata = await getHabboItFurnidata()
const fd = furnidata.get(item.classname) || furnidata.get(baseClassname)
const itemType = dbItem?.type === 'i' ? 'i' : 's'
const entry = buildFurniEntry({
id: dbItem?.spriteId || 0,
classname: baseClassname,
revision: rev,
category: fd?.category || '',
name: dbItem?.publicName || baseClassname,
description: fd?.description || '',
spriteId: dbItem?.spriteId || 0,
dims: conversion.dimensions || { x: 1, y: 1, z: 1 },
metadata: conversion.metadata || null,
habboIt: fd || null,
})
await appendFurniEntry(entry, itemType)
}
} catch (fdErr) {
console.warn(
`[regen] FurnitureData update skipped for ${item.classname}:`,
(fdErr as Error).message,
)
}
results.push({ classname: item.classname, ok: true })
} catch (err) {
results.push({ classname: item.classname, ok: false, warning: (err as Error).message })
}
}
const succeeded = results.filter((r) => r.ok).length
const failed = results.filter((r) => !r.ok).length
return apiOk({ succeeded, failed, results })
})
// ── Re-classify ALL imported items across all sub-pages + update prices (PUT) ──
// Supports ?dryrun=1 to preview changes without applying them.
export const PUT = withAdmin({ permission: PERMS.ASSETS_IMPORT }, async (request, ctx) => {
const isDryRun = request.nextUrl.searchParams.get('dryrun') === '1'
// 1. Find the root "imported_furni" page
const parentPage = await prisma.catalogPages.findFirst({
where: { captionSave: IMPORTED_PAGE_CAPTION_SAVE },
select: { id: true },
})
if (!parentPage) {
return apiOk({
dryRun: isDryRun,
moved: 0,
repriced: 0,
message: 'No imported_furni page found — nothing to reorganize',
})
}
// 2. Collect ALL imported page IDs (parent + every imp_* sub-page)
const subPages = await prisma.catalogPages.findMany({
where: { parentId: parentPage.id },
select: { id: true, captionSave: true },
})
const allImportedPageIds = [String(parentPage.id), ...subPages.map((p) => String(p.id))]
// 3. Find ALL catalog_items across all imported pages
// page_id is VARCHAR in DB so we use string placeholders
const inPlaceholders = allImportedPageIds.map(() => '?').join(',')
const allItems = await prisma.$queryRawUnsafe<
Array<{
id: number
item_ids: string
catalog_name: string
page_id: string
cost_credits: number
}>
>(
`SELECT id, item_ids, catalog_name, page_id, cost_credits FROM catalog_items WHERE page_id IN (${inPlaceholders})`,
...allImportedPageIds,
)
if (allItems.length === 0) {
return apiOk({
dryRun: isDryRun,
moved: 0,
repriced: 0,
message: 'No imported items found — nothing to reorganize',
})
}
// 4. Build classname → type map from items_base
const uniqueItemIds = [...new Set(allItems.map((i) => Number(i.item_ids)))].filter(
(n) => !Number.isNaN(n),
)
const dbItems =
uniqueItemIds.length > 0
? await prisma.itemsBase.findMany({
where: { id: { in: uniqueItemIds } },
select: { id: true, itemName: true, type: true },
})
: []
const typeMap = new Map<string, string>()
for (const di of dbItems) {
if (di.itemName) typeMap.set(di.itemName, di.type || 's')
}
// 5. Pre-load category page map (captionSave → pageId) to avoid N+1 queries
const categoryPageMap = new Map<string, number>()
for (const sp of subPages) {
if (sp.captionSave) categoryPageMap.set(sp.captionSave, sp.id)
}
// Helper: resolve or create category page using the cached map
async function resolvePageId(catKey: string): Promise<string> {
const captionSave = `imp_${catKey}`
const cached = categoryPageMap.get(captionSave)
if (cached !== undefined) return String(cached)
if (isDryRun) return 'new'
// Create the page (only happens once per new category)
const catInfo = CATEGORY_PAGE[catKey] || CATEGORY_PAGE.other
const parentId = parentPage!.id
await prisma.$executeRaw`
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)
VALUES (${captionSave}, ${catInfo.label}, 'default_3x3', ${parentId}, '1', ${catInfo.order}, ${catInfo.icon}, '1', '1', '', '', '', '', '', '', '', '')
`
const created = await prisma.catalogPages.findFirst({
where: { captionSave, parentId },
select: { id: true },
})
categoryPageMap.set(captionSave, created!.id)
return String(created!.id)
}
// 6. Classify all items (pure computation + cached lookups, no per-item DB queries)
let moved = 0
let repriced = 0
let skipped = 0
const errors: string[] = []
const categoryCounts: Record<string, number> = {}
const pagesWithItems = new Set<string>()
// Collect batched updates: key = "pageId|credits|points|pointsType" → item ids
const updateBatches = new Map<string, number[]>()
// First pass: resolve any new category pages (max ~14 DB inserts)
const neededCategories = new Set<string>()
for (const item of allItems) {
const itemType = typeMap.get(item.catalog_name) || 's'
neededCategories.add(classifyFurni(item.catalog_name, itemType))
}
for (const catKey of neededCategories) {
try {
await resolvePageId(catKey)
} catch (err) {
errors.push(`create page ${catKey}: ${(err as Error).message}`)
}
}
// Second pass: classify items (no DB calls)
for (const item of allItems) {
const itemType = typeMap.get(item.catalog_name) || 's'
const catKey = classifyFurni(item.catalog_name, itemType)
categoryCounts[catKey] = (categoryCounts[catKey] || 0) + 1
const captionSave = `imp_${catKey}`
const cachedPageId = categoryPageMap.get(captionSave)
const correctPageIdStr = cachedPageId !== undefined ? String(cachedPageId) : 'new'
const price = autoPriceFurni(item.catalog_name)
const needsMove = item.page_id !== correctPageIdStr
const needsReprice = item.cost_credits !== price.credits
pagesWithItems.add(correctPageIdStr)
if (!needsMove && !needsReprice) {
skipped++
continue
}
if (needsMove) moved++
if (needsReprice) repriced++
if (!isDryRun) {
const batchKey = `${correctPageIdStr}|${price.credits}|${price.points}|${price.pointsType}`
const batch = updateBatches.get(batchKey)
if (batch) {
batch.push(item.id)
} else {
updateBatches.set(batchKey, [item.id])
}
}
}
// 7. Apply batched updates (one UPDATE per category/price combo instead of per item)
if (!isDryRun) {
for (const [batchKey, ids] of updateBatches) {
const [pageId, credits, points, pointsType] = batchKey.split('|')
try {
const idPlaceholders = ids.map(() => '?').join(',')
await prisma.$queryRawUnsafe(
`UPDATE catalog_items SET page_id = ?, cost_credits = ?, cost_points = ?, points_type = ? WHERE id IN (${idPlaceholders})`,
pageId,
Number(credits),
Number(points),
Number(pointsType),
...ids,
)
} catch (err) {
errors.push(`batch update: ${(err as Error).message}`)
}
}
}
// 8. Cleanup empty sub-pages (only if NOT dry-run)
let pagesDeleted = 0
if (!isDryRun) {
for (const subPage of subPages) {
const subPageIdStr = String(subPage.id)
if (!pagesWithItems.has(subPageIdStr)) {
try {
const remaining = await prisma.$queryRawUnsafe<Array<{ cnt: bigint }>>(
`SELECT COUNT(*) as cnt FROM catalog_items WHERE page_id = ?`,
subPageIdStr,
)
const count = Number(remaining[0]?.cnt ?? 0)
if (count === 0) {
await prisma.$executeRaw`DELETE FROM catalog_pages WHERE id = ${subPage.id}`
pagesDeleted++
}
} catch (err) {
errors.push(`cleanup ${subPage.captionSave}: ${(err as Error).message}`)
}
}
}
}
// 9. Refresh game server caches (only if NOT dry-run and changes were made)
if (!isDryRun && (moved > 0 || repriced > 0 || pagesDeleted > 0)) {
try {
await rcon.updateCatalog()
} catch (err) {
errors.push(`RCON: ${(err as Error).message}`)
}
}
if (!isDryRun) {
logAudit({
userId: ctx.session.user.id,
action: 'furni_reorganize',
target: 'CatalogItems',
targetId: parentPage.id,
after: {
moved,
repriced,
skipped,
pagesDeleted,
categoryCounts,
errors: errors.length > 0 ? errors : undefined,
},
})
}
return apiOk({
dryRun: isDryRun,
moved,
repriced,
skipped,
pagesDeleted,
total: allItems.length,
categoryCounts,
errors: errors.length > 0 ? errors : undefined,
})
})