import reportReasons from '../utils/report-reasons.js'; import { HttpError } from './errors.js'; import { knexOwner as knex } from './knex.js'; import initLogger from './logger.js'; import { verifyNotBanned } from './users.js'; const logger = initLogger(); const maxCommentLength = 2000; // roles that can review reports in the admin panel export function canReviewReports(reqUser) { return !!reqUser && reqUser.role !== 'user'; } function curateReport(report) { return { id: report.id, reasons: report.reasons?.split(',').filter(Boolean) || [], comment: report.comment, isRead: report.is_read, isCompleted: report.is_completed, createdAt: report.created_at, entity: report.entity_id && { id: report.entity_id, name: report.entity_name, slug: report.entity_slug, type: report.entity_type, }, user: report.user_id && { id: report.user_id, username: report.username, }, }; } export async function createReport(entityId, { reasons, comment }, reqUser) { if (!reqUser) { throw new HttpError('You must be logged in to submit a report', 401); } const curatedReasons = Array.from(new Set(Array.isArray(reasons) ? reasons : [])); const invalidReasons = curatedReasons.filter((reason) => !Object.hasOwn(reportReasons, reason)); const curatedComment = typeof comment === 'string' ? comment.trim() : ''; if (invalidReasons.length > 0) { throw new HttpError(`Invalid report reasons: ${invalidReasons.join(', ')}`, 400); } if (curatedReasons.length === 0 && !curatedComment) { throw new HttpError('Please select a reason or describe the problem', 400); } if (curatedComment.length > maxCommentLength) { throw new HttpError(`Comments can't be longer than ${maxCommentLength} characters`, 400); } await verifyNotBanned(reqUser, 'reports', 'You are not allowed to submit reports'); const entity = await knex('entities').select('id', 'name').where('id', entityId).first(); if (!entity) { throw new HttpError(`Entity ${entityId} does not exist`, 404); } // the partial unique index on open reports makes this race-proof, the error is just friendlier const [report] = await knex('reports') .insert({ entity_id: entity.id, user_id: reqUser.id, reasons: curatedReasons.join(',') || null, comment: curatedComment || null, }) .onConflict(knex.raw('(entity_id, user_id) WHERE is_completed = false')) .ignore() .returning('id'); if (!report) { throw new HttpError(`You already reported ${entity.name}, your report is awaiting review`, 409); } logger.info(`User ${reqUser.username} (${reqUser.id}) reported ${entity.name} (${entity.id}): ${curatedReasons.join(', ') || 'no reasons'}`); return report.id; } export async function hasOpenReport(entityId, reqUser) { if (!reqUser) { return false; } const report = await knex('reports') .where('entity_id', entityId) .where('user_id', reqUser.id) .where('is_completed', false) .first(); return !!report; } export async function fetchReports({ completed = false } = {}, reqUser) { if (!canReviewReports(reqUser)) { throw new HttpError('You are not allowed to view reports', 404); } const reports = await knex('reports') .select( 'reports.*', 'entities.name as entity_name', 'entities.slug as entity_slug', 'entities.type as entity_type', 'users.username', ) .leftJoin('entities', 'entities.id', 'reports.entity_id') .leftJoin('users', 'users.id', 'reports.user_id') .where('reports.is_completed', completed) .orderBy('reports.created_at', 'desc') .limit(500); return reports.map((report) => curateReport(report)); } export async function updateReport(reportId, { isRead, isCompleted }, reqUser) { if (!canReviewReports(reqUser)) { throw new HttpError('You are not allowed to update reports', 404); } const update = { ...(typeof isRead === 'boolean' && { is_read: isRead }), ...(typeof isCompleted === 'boolean' && { is_completed: isCompleted }), ...(isCompleted === true && { is_read: true }), // a completed report has necessarily been read }; if (Object.keys(update).length === 0) { throw new HttpError('Nothing to update', 400); } const [updatedReport] = await knex('reports') .where('id', reportId) .update(update) .returning('*') .catch((error) => { // reopening a report conflicts with a newer open report by the same user for the same entity if (error.code === '23505') { throw new HttpError('The reporter has since submitted a new report for this entity, which is still open', 409); } throw error; }); if (!updatedReport) { throw new HttpError(`Report ${reportId} does not exist`, 404); } return curateReport(updatedReport); } export async function countUnreadReports() { const { count } = await knex('reports') .where('is_read', false) .where('is_completed', false) .count() .first(); return Number(count); }