games_app/backend/src/services/faqService.ts
2026-11-09 18:14:42 +02:00

517 lines
17 KiB
TypeScript

import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import { v4 as uuidv4 } from 'uuid';
import { Request } from 'express';
import * as repo from '../repositories/faqRepository';
import { FaqCategoryRow, FaqDocumentLang } from '../models/faq.model';
import { ensureFaqUploadDir } from '../middleware/faqUpload';
import {
FAQ_PDF_ALLOWED_MIMES,
FAQ_PDF_DEFAULT_MAX_BYTES,
} from '../middleware/faqPdfUpload';
import { sanitizeFaqHtml } from '../utils/sanitizeHtml';
import { validateUploadedFile } from '../utils/uploadValidation';
import { extensionForMime, removeUploadedFile } from '../utils/fileMagic';
import {
recordUploadedFile,
forgetUploadedFile,
FILE_INTEGRITY_ROOTS,
} from './fileIntegrityService';
import { query } from '../db/connection';
function slugify(text: string): string {
return text
.trim()
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 64);
}
/** Validate and normalize document language param. */
export function parseFaqDocumentLang(raw: string): FaqDocumentLang {
if (raw === 'fr' || raw === 'en') return raw;
throw new Error('Invalid document language (use fr or en)');
}
/** Safe download filename for Content-Disposition. */
export function sanitizeDownloadFilename(name: string, fallback = 'guide.pdf'): string {
const base = path.basename(name || fallback).replace(/[^\w.\- ()[\]]+/g, '_').trim();
if (!base || base === '.' || base === '..') return fallback;
return base.toLowerCase().endsWith('.pdf') ? base : `${base}.pdf`;
}
/**
* Public download name: `guide_<category>_<lang>.pdf`
* Uses the category slug when available so users immediately see topic + language.
*/
export function buildFaqCategoryGuideFilename(
slugOrName: string,
lang: FaqDocumentLang
): string {
const raw = slugify(slugOrName) || 'category';
const token = raw.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'category';
return `guide_${token}_${lang}.pdf`;
}
function mapPdfMeta(
lang: FaqDocumentLang,
slug: string,
filename: string | null,
_originalName: string | null
) {
if (!filename) return null;
return {
// Display / download label always reflects category + language.
originalName: buildFaqCategoryGuideFilename(slug, lang),
url: `/api/v1/faq/categories/${encodeURIComponent(slug)}/documents/${lang}`,
};
}
function mapCategory(row: FaqCategoryRow) {
return {
id: row.id,
slug: row.slug,
name: row.name,
description: row.description,
sortOrder: row.sort_order,
isActive: row.is_active,
pdfFr: mapPdfMeta('fr', row.slug, row.pdf_fr_filename, row.pdf_fr_original_name),
pdfEn: mapPdfMeta('en', row.slug, row.pdf_en_filename, row.pdf_en_original_name),
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
};
}
function mapEntryPublic(row: repo.FaqEntryWithCategory) {
return {
id: row.id,
categoryId: row.category_id,
categorySlug: row.category_slug,
categoryName: row.category_name,
question: row.question,
answerHtml: row.answer_html,
sortOrder: row.sort_order,
viewCount: row.view_count,
helpfulYes: row.helpful_yes,
helpfulNo: row.helpful_no,
};
}
function mapEntryAdmin(row: repo.FaqEntryAdminRow) {
return {
...mapEntryPublic(row),
isActive: row.is_active,
createdBy: row.created_by,
updatedBy: row.updated_by,
createdByName: row.created_by_name,
updatedByName: row.updated_by_name,
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
};
}
export function buildVoterKey(req: Request, userId?: string): string {
if (userId) return `user:${userId}`;
const ip = req.ip ?? req.socket.remoteAddress ?? 'unknown';
const ua = req.get('user-agent') ?? '';
const hash = crypto.createHash('sha256').update(`${ip}|${ua}`).digest('hex').slice(0, 32);
return `anon:${hash}`;
}
export function publicFaqFileUrl(filename: string): string {
return `/api/v1/faq/files/${encodeURIComponent(filename)}`;
}
export function resolveFaqFilePath(filename: string): string {
return path.join(ensureFaqUploadDir(), path.basename(filename));
}
function safeFaqDisplayName(originalName: string | undefined, mime: string): string {
const ext = extensionForMime(mime);
const base = path
.basename(originalName || 'file')
.replace(/[^\w.\-()+ ]+/g, '_')
.slice(0, 180);
const withoutExt = base.replace(/\.[^.]+$/, '') || 'file';
return `${withoutExt}${ext}`;
}
/**
* Validate magic/ClamAV, rename to uuid+safeExt, register legitimacy row.
*/
export async function finalizeFaqUpload(input: {
tempFilename: string;
originalName?: string;
kind: 'media' | 'category_pdf';
categoryId?: number | null;
uploadedByUserId?: string | null;
allowedMimes: Set<string>;
}): Promise<{ filename: string; mime: string; originalName: string; url: string }> {
const tempPath = resolveFaqFilePath(input.tempFilename);
let detected: string;
try {
detected = await validateUploadedFile(tempPath, input.allowedMimes);
} catch (e) {
removeUploadedFile(tempPath);
throw e;
}
const ext = extensionForMime(detected);
const finalName = `${uuidv4()}${ext}`;
const finalPath = resolveFaqFilePath(finalName);
fs.renameSync(tempPath, finalPath);
const originalName = safeFaqDisplayName(input.originalName, detected);
await repo.insertUploadedFile({
filename: finalName,
mime: detected,
originalName,
kind: input.kind,
categoryId: input.categoryId ?? null,
uploadedByUserId: input.uploadedByUserId ?? null,
});
await recordUploadedFile(FILE_INTEGRITY_ROOTS.faq, finalName);
return {
filename: finalName,
mime: detected,
originalName,
url: publicFaqFileUrl(finalName),
};
}
/** Content-Disposition for FAQ downloads (attachment for PDF, inline for media). */
export function faqFileContentDisposition(
downloadName: string,
mime: string
): string {
const ascii = downloadName.replace(/[^\x20-\x7E]/g, '_').replace(/"/g, '');
const encoded = encodeURIComponent(downloadName);
const disposition = mime === 'application/pdf' ? 'attachment' : 'inline';
return `${disposition}; filename="${ascii}"; filename*=UTF-8''${encoded}`;
}
/**
* Resolve a legitimate FAQ file for public download.
* Registry first; legacy fallback for category PDFs / answer HTML references.
*/
export async function resolvePublicFaqFile(filename: string): Promise<{
filePath: string;
mime: string;
downloadName: string;
} | null> {
const safe = path.basename(filename);
if (!safe || safe === '.' || safe === '..') return null;
const filePath = resolveFaqFilePath(safe);
if (!fs.existsSync(filePath)) return null;
const registered = await repo.findUploadedFile(safe);
if (registered) {
return {
filePath,
mime: registered.mime,
downloadName: registered.original_name || safe,
};
}
if (await repo.isCategoryPdfFilename(safe)) {
return {
filePath,
mime: 'application/pdf',
downloadName: safe.toLowerCase().endsWith('.pdf') ? safe : `${safe}.pdf`,
};
}
if (await repo.isReferencedInFaqAnswerHtml(safe)) {
const ext = path.extname(safe).toLowerCase();
const mime =
ext === '.jpg' || ext === '.jpeg'
? 'image/jpeg'
: ext === '.png'
? 'image/png'
: ext === '.gif'
? 'image/gif'
: ext === '.webp'
? 'image/webp'
: ext === '.mp4'
? 'video/mp4'
: ext === '.webm'
? 'video/webm'
: ext === '.pdf'
? 'application/pdf'
: null;
if (!mime) return null;
return { filePath, mime, downloadName: safe };
}
return null;
}
export async function getFaqPdfMaxBytes(): Promise<number> {
const rows = await query<{ value: string }[]>(
`SELECT value FROM system_settings WHERE key = $1 LIMIT 1`,
['faq_pdf_max_bytes']
);
const n = Number(rows[0]?.value);
if (!Number.isFinite(n) || n <= 0) return FAQ_PDF_DEFAULT_MAX_BYTES;
return Math.floor(n);
}
export async function listPublicCategories() {
const rows = await repo.listCategories(true);
return rows.map(mapCategory);
}
export async function listPublicFaqs(filters: { category?: string; search?: string }) {
const rows = await repo.listPublicEntries({
categorySlug: filters.category,
search: filters.search,
});
return rows.map(mapEntryPublic);
}
export async function listPopularFaqs(limit?: number) {
const rows = await repo.listPopularEntries(limit ?? 5);
return rows.map(mapEntryPublic);
}
export async function getPublicFaq(id: string) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active) throw new Error('FAQ not found');
return mapEntryPublic(row);
}
export async function recordFaqView(id: string) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active) throw new Error('FAQ not found');
await repo.incrementViewCount(id);
return { ok: true };
}
export async function recordFaqHelpful(id: string, helpful: boolean, voterKey: string) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active) throw new Error('FAQ not found');
return repo.recordHelpfulVote(id, voterKey, helpful);
}
export async function listAdminCategories() {
const rows = await repo.listCategories(false);
return rows.map(mapCategory);
}
function parseDescription(body: Record<string, unknown>): string | null | undefined {
if (!('description' in body)) return undefined;
if (body.description === null) return null;
if (typeof body.description === 'string') {
const trimmed = body.description.trim();
return trimmed.length ? trimmed : null;
}
return undefined;
}
export async function createAdminCategory(body: Record<string, unknown>) {
const name = typeof body.name === 'string' ? body.name.trim() : '';
if (!name) throw new Error('Category name is required');
const slug =
typeof body.slug === 'string' && body.slug.trim()
? slugify(body.slug)
: slugify(name);
if (!slug) throw new Error('Invalid category slug');
const description = parseDescription(body);
return mapCategory(
await repo.createCategory({
slug,
name,
description: description === undefined ? null : description,
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : 0,
isActive: body.isActive !== false,
})
);
}
export async function updateAdminCategory(id: number, body: Record<string, unknown>) {
const description = parseDescription(body);
const updated = await repo.updateCategory(id, {
slug: typeof body.slug === 'string' ? slugify(body.slug) : undefined,
name: typeof body.name === 'string' ? body.name.trim() : undefined,
description,
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined,
isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined,
});
if (!updated) throw new Error('Category not found');
return mapCategory(updated);
}
/** Removes a FAQ PDF from disk and clears its FIM baseline (intentional delete). */
async function unlinkFaqFileQuiet(filename: string | null | undefined): Promise<void> {
if (!filename) return;
removeUploadedFile(resolveFaqFilePath(filename));
await forgetUploadedFile(FILE_INTEGRITY_ROOTS.faq, filename);
}
export async function deleteAdminCategory(id: number) {
const count = await repo.countEntriesInCategory(id);
if (count > 0) {
throw new Error('Cannot delete category that still contains FAQ entries');
}
const existing = await repo.getCategoryById(id);
if (!existing) throw new Error('Category not found');
const ok = await repo.deleteCategory(id);
if (!ok) throw new Error('Category not found');
await unlinkFaqFileQuiet(existing.pdf_fr_filename);
await unlinkFaqFileQuiet(existing.pdf_en_filename);
return { ok: true };
}
export async function listAdminFaqs(filters: {
categoryId?: number;
search?: string;
isActive?: boolean;
}) {
const rows = await repo.listAdminEntries(filters);
return rows.map(mapEntryAdmin);
}
export async function createAdminFaq(userId: string, body: Record<string, unknown>) {
const question = typeof body.question === 'string' ? body.question.trim() : '';
const answerHtml = typeof body.answerHtml === 'string' ? body.answerHtml : '';
const categoryId = Number(body.categoryId);
if (!question) throw new Error('Question is required');
if (!answerHtml.trim()) throw new Error('Answer is required');
if (!Number.isFinite(categoryId)) throw new Error('categoryId is required');
const cat = await repo.getCategoryById(categoryId);
if (!cat) throw new Error('Category not found');
const row = await repo.createEntry({
categoryId,
question,
answerHtml: sanitizeFaqHtml(answerHtml),
isActive: body.isActive !== false,
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : 0,
userId,
});
const adminRows = await repo.listAdminEntries({});
const full = adminRows.find((r) => r.id === row.id);
if (!full) throw new Error('FAQ created but not found');
return mapEntryAdmin(full);
}
export async function updateAdminFaq(id: string, userId: string, body: Record<string, unknown>) {
const updated = await repo.updateEntry(id, {
categoryId: typeof body.categoryId === 'number' ? body.categoryId : undefined,
question: typeof body.question === 'string' ? body.question.trim() : undefined,
answerHtml: typeof body.answerHtml === 'string' ? sanitizeFaqHtml(body.answerHtml) : undefined,
isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined,
sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined,
userId,
});
if (!updated) throw new Error('FAQ not found');
const adminRows = await repo.listAdminEntries({});
const full = adminRows.find((r) => r.id === id);
if (!full) throw new Error('FAQ not found');
return mapEntryAdmin(full);
}
export async function deleteAdminFaq(id: string) {
const ok = await repo.deleteEntry(id);
if (!ok) throw new Error('FAQ not found');
return { ok: true };
}
export function readFaqFile(filename: string): string | null {
const filePath = resolveFaqFilePath(filename);
if (!fs.existsSync(filePath)) return null;
return filePath;
}
/**
* Upload or replace a category PDF. Validates magic + size; only swaps DB pointer
* after success so a failed upload never drops the previous document.
*/
export async function uploadCategoryDocument(input: {
categoryId: number;
lang: FaqDocumentLang;
tempFilename: string;
originalName: string;
byteSize: number;
uploadedByUserId?: string | null;
}): Promise<ReturnType<typeof mapCategory>> {
const cat = await repo.getCategoryById(input.categoryId);
if (!cat) {
removeUploadedFile(resolveFaqFilePath(input.tempFilename));
throw new Error('Category not found');
}
const maxBytes = await getFaqPdfMaxBytes();
if (input.byteSize > maxBytes) {
removeUploadedFile(resolveFaqFilePath(input.tempFilename));
throw new Error(`PDF exceeds maximum size of ${maxBytes} bytes`);
}
const saved = await finalizeFaqUpload({
tempFilename: input.tempFilename,
originalName: input.originalName,
kind: 'category_pdf',
categoryId: input.categoryId,
uploadedByUserId: input.uploadedByUserId ?? null,
allowedMimes: FAQ_PDF_ALLOWED_MIMES,
});
const previous =
input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
// Prefer a clear guide name over the uploader's original filename.
const originalName = buildFaqCategoryGuideFilename(cat.slug || cat.name, input.lang);
const updated = await repo.setCategoryDocument(
input.categoryId,
input.lang,
saved.filename,
originalName
);
if (!updated) {
await unlinkFaqFileQuiet(saved.filename);
await repo.deleteUploadedFile(saved.filename);
throw new Error('Category not found');
}
if (previous && previous !== saved.filename) {
await unlinkFaqFileQuiet(previous);
await repo.deleteUploadedFile(previous).catch(() => undefined);
}
return mapCategory(updated);
}
export async function deleteCategoryDocument(categoryId: number, lang: FaqDocumentLang) {
const result = await repo.clearCategoryDocument(categoryId, lang);
if (!result) throw new Error('Category not found');
if (result.removedFilename) {
await unlinkFaqFileQuiet(result.removedFilename);
await repo.deleteUploadedFile(result.removedFilename).catch(() => undefined);
}
return mapCategory(result.row);
}
/** Resolve a public download for an active category document. */
export async function resolvePublicCategoryDocument(
slug: string,
lang: FaqDocumentLang
): Promise<{ filePath: string; downloadName: string } | null> {
const cat = await repo.getCategoryBySlug(slug);
if (!cat || !cat.is_active) return null;
const filename = lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
if (!filename) return null;
const filePath = readFaqFile(filename);
if (!filePath) return null;
// Always derive from current category + language (survives rename / old uploads).
return {
filePath,
downloadName: buildFaqCategoryGuideFilename(cat.slug || cat.name, lang),
};
}