games_app/backend/dist/services/faqService.js

507 lines
20 KiB
JavaScript

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFaqDocumentLang = parseFaqDocumentLang;
exports.sanitizeDownloadFilename = sanitizeDownloadFilename;
exports.buildFaqCategoryGuideFilename = buildFaqCategoryGuideFilename;
exports.buildVoterKey = buildVoterKey;
exports.publicFaqFileUrl = publicFaqFileUrl;
exports.resolveFaqFilePath = resolveFaqFilePath;
exports.finalizeFaqUpload = finalizeFaqUpload;
exports.faqFileContentDisposition = faqFileContentDisposition;
exports.resolvePublicFaqFile = resolvePublicFaqFile;
exports.getFaqPdfMaxBytes = getFaqPdfMaxBytes;
exports.listPublicCategories = listPublicCategories;
exports.listPublicFaqs = listPublicFaqs;
exports.listPopularFaqs = listPopularFaqs;
exports.getPublicFaq = getPublicFaq;
exports.recordFaqView = recordFaqView;
exports.recordFaqHelpful = recordFaqHelpful;
exports.listAdminCategories = listAdminCategories;
exports.createAdminCategory = createAdminCategory;
exports.updateAdminCategory = updateAdminCategory;
exports.deleteAdminCategory = deleteAdminCategory;
exports.listAdminFaqs = listAdminFaqs;
exports.createAdminFaq = createAdminFaq;
exports.updateAdminFaq = updateAdminFaq;
exports.deleteAdminFaq = deleteAdminFaq;
exports.readFaqFile = readFaqFile;
exports.uploadCategoryDocument = uploadCategoryDocument;
exports.deleteCategoryDocument = deleteCategoryDocument;
exports.resolvePublicCategoryDocument = resolvePublicCategoryDocument;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const crypto_1 = __importDefault(require("crypto"));
const uuid_1 = require("uuid");
const repo = __importStar(require("../repositories/faqRepository"));
const faqUpload_1 = require("../middleware/faqUpload");
const faqPdfUpload_1 = require("../middleware/faqPdfUpload");
const sanitizeHtml_1 = require("../utils/sanitizeHtml");
const uploadValidation_1 = require("../utils/uploadValidation");
const fileMagic_1 = require("../utils/fileMagic");
const fileIntegrityService_1 = require("./fileIntegrityService");
const connection_1 = require("../db/connection");
function slugify(text) {
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. */
function parseFaqDocumentLang(raw) {
if (raw === 'fr' || raw === 'en')
return raw;
throw new Error('Invalid document language (use fr or en)');
}
/** Safe download filename for Content-Disposition. */
function sanitizeDownloadFilename(name, fallback = 'guide.pdf') {
const base = path_1.default.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.
*/
function buildFaqCategoryGuideFilename(slugOrName, lang) {
const raw = slugify(slugOrName) || 'category';
const token = raw.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'category';
return `guide_${token}_${lang}.pdf`;
}
function mapPdfMeta(lang, slug, filename, _originalName) {
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) {
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) {
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) {
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(),
};
}
function buildVoterKey(req, userId) {
if (userId)
return `user:${userId}`;
const ip = req.ip ?? req.socket.remoteAddress ?? 'unknown';
const ua = req.get('user-agent') ?? '';
const hash = crypto_1.default.createHash('sha256').update(`${ip}|${ua}`).digest('hex').slice(0, 32);
return `anon:${hash}`;
}
function publicFaqFileUrl(filename) {
return `/api/v1/faq/files/${encodeURIComponent(filename)}`;
}
function resolveFaqFilePath(filename) {
return path_1.default.join((0, faqUpload_1.ensureFaqUploadDir)(), path_1.default.basename(filename));
}
function safeFaqDisplayName(originalName, mime) {
const ext = (0, fileMagic_1.extensionForMime)(mime);
const base = path_1.default
.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.
*/
async function finalizeFaqUpload(input) {
const tempPath = resolveFaqFilePath(input.tempFilename);
let detected;
try {
detected = await (0, uploadValidation_1.validateUploadedFile)(tempPath, input.allowedMimes);
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(tempPath);
throw e;
}
const ext = (0, fileMagic_1.extensionForMime)(detected);
const finalName = `${(0, uuid_1.v4)()}${ext}`;
const finalPath = resolveFaqFilePath(finalName);
fs_1.default.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 (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.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). */
function faqFileContentDisposition(downloadName, mime) {
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.
*/
async function resolvePublicFaqFile(filename) {
const safe = path_1.default.basename(filename);
if (!safe || safe === '.' || safe === '..')
return null;
const filePath = resolveFaqFilePath(safe);
if (!fs_1.default.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_1.default.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;
}
async function getFaqPdfMaxBytes() {
const rows = await (0, connection_1.query)(`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 faqPdfUpload_1.FAQ_PDF_DEFAULT_MAX_BYTES;
return Math.floor(n);
}
async function listPublicCategories() {
const rows = await repo.listCategories(true);
return rows.map(mapCategory);
}
async function listPublicFaqs(filters) {
const rows = await repo.listPublicEntries({
categorySlug: filters.category,
search: filters.search,
});
return rows.map(mapEntryPublic);
}
async function listPopularFaqs(limit) {
const rows = await repo.listPopularEntries(limit ?? 5);
return rows.map(mapEntryPublic);
}
async function getPublicFaq(id) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active)
throw new Error('FAQ not found');
return mapEntryPublic(row);
}
async function recordFaqView(id) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active)
throw new Error('FAQ not found');
await repo.incrementViewCount(id);
return { ok: true };
}
async function recordFaqHelpful(id, helpful, voterKey) {
const row = await repo.getEntryById(id);
if (!row || !row.is_active)
throw new Error('FAQ not found');
return repo.recordHelpfulVote(id, voterKey, helpful);
}
async function listAdminCategories() {
const rows = await repo.listCategories(false);
return rows.map(mapCategory);
}
function parseDescription(body) {
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;
}
async function createAdminCategory(body) {
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,
}));
}
async function updateAdminCategory(id, body) {
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) {
if (!filename)
return;
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(filename));
await (0, fileIntegrityService_1.forgetUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.faq, filename);
}
async function deleteAdminCategory(id) {
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 };
}
async function listAdminFaqs(filters) {
const rows = await repo.listAdminEntries(filters);
return rows.map(mapEntryAdmin);
}
async function createAdminFaq(userId, body) {
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: (0, sanitizeHtml_1.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);
}
async function updateAdminFaq(id, userId, body) {
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' ? (0, sanitizeHtml_1.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);
}
async function deleteAdminFaq(id) {
const ok = await repo.deleteEntry(id);
if (!ok)
throw new Error('FAQ not found');
return { ok: true };
}
function readFaqFile(filename) {
const filePath = resolveFaqFilePath(filename);
if (!fs_1.default.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.
*/
async function uploadCategoryDocument(input) {
const cat = await repo.getCategoryById(input.categoryId);
if (!cat) {
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(input.tempFilename));
throw new Error('Category not found');
}
const maxBytes = await getFaqPdfMaxBytes();
if (input.byteSize > maxBytes) {
(0, fileMagic_1.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: faqPdfUpload_1.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);
}
async function deleteCategoryDocument(categoryId, lang) {
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. */
async function resolvePublicCategoryDocument(slug, lang) {
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),
};
}
//# sourceMappingURL=faqService.js.map