Этап 7: редактор статей
- редактор по макету: CodeMirror 6 + живой предпросмотр тем же рендером @kb/md - тулбар вставки блоков, автодополнение [[ по названиям, подсветка битых ссылок - загрузка картинок: перетаскивание, Ctrl+V, выбор файла → сразу вставляется  - свойства: название, раздел, теги, оборудование, шифр, видимость, закрепление - черновик отдельно от опубликованного текста, автосохранение каждые 10 с - публикация с новой версией, история версий с diff и откатом - прикрепление исходников (PDF/DOC/DOCX/XLS/XLSX/DWG) с проверкой содержимого - API редактирования только для EDITOR и ADMIN; API админки (пользователи, приглашения, пространства, разделы) только для ADMIN - обновление данных на странице, когда service worker получил новую версию - scripts/check-roles.mjs: проверка прав гостя, читателя и редактора на сервере Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
90ad495901
commit
8920c16e6f
@@ -7,8 +7,10 @@ import { csrfGuard, loadUser } from './auth.js';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { adminRouter } from './routes/admin.js';
|
||||
import { authRouter } from './routes/auth.js';
|
||||
import { contentRouter } from './routes/content.js';
|
||||
import { editRouter } from './routes/edit.js';
|
||||
import { meRouter } from './routes/me.js';
|
||||
|
||||
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
|
||||
@@ -87,6 +89,8 @@ export function createApp() {
|
||||
app.use('/api', csrfGuard);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/me', meRouter);
|
||||
app.use('/api/edit', editRouter);
|
||||
app.use('/api/admin', adminRouter);
|
||||
app.use('/api', contentRouter);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
@@ -105,6 +109,11 @@ export function createApp() {
|
||||
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
|
||||
return;
|
||||
}
|
||||
if (err?.name === 'MulterError') {
|
||||
const big = err.code === 'LIMIT_FILE_SIZE';
|
||||
res.status(big ? 413 : 400).json({ error: big ? 'Файл слишком большой (картинки до 15 МБ, документы до 30 МБ)' : 'Не удалось принять файл' });
|
||||
return;
|
||||
}
|
||||
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') {
|
||||
res.status(400).json({ error: 'Некорректный запрос' });
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// Админка: пользователи, приглашения, пространства и разделы. Только для роли ADMIN.
|
||||
import { Router } from 'express';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { z } from 'zod';
|
||||
import type { AdminUserDto, InviteDto } from '@kb/shared';
|
||||
import { requireRole } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { env } from '../env.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { toSectionDto, toSpaceDto } from './content.js';
|
||||
import { slugify } from './edit.js';
|
||||
|
||||
export const adminRouter = Router();
|
||||
adminRouter.use(requireRole('ADMIN'));
|
||||
|
||||
const role = z.enum(['ADMIN', 'EDITOR', 'VIEWER']);
|
||||
const INVITE_DAYS = 7;
|
||||
|
||||
// ---------- Пользователи ----------
|
||||
adminRouter.get('/users', async (_req, res) => {
|
||||
const users = await prisma.user.findMany({ orderBy: [{ blocked: 'asc' }, { name: 'asc' }] });
|
||||
const list: AdminUserDto[] = users.map((u) => ({
|
||||
id: u.id,
|
||||
email: u.email,
|
||||
name: u.name,
|
||||
role: u.role,
|
||||
blocked: u.blocked,
|
||||
createdAt: u.createdAt.toISOString(),
|
||||
lastSeenAt: u.lastSeenAt?.toISOString() ?? null,
|
||||
}));
|
||||
res.json(list);
|
||||
});
|
||||
|
||||
/** Нельзя оставить систему без действующего администратора. */
|
||||
async function assertAdminRemains(exceptId: string) {
|
||||
const others = await prisma.user.count({ where: { role: 'ADMIN', blocked: false, id: { not: exceptId } } });
|
||||
if (!others) throw new HttpError(400, 'Должен остаться хотя бы один администратор');
|
||||
}
|
||||
|
||||
adminRouter.patch('/users/:id', async (req, res) => {
|
||||
const input = z.object({ role: role.optional(), blocked: z.boolean().optional(), name: z.string().trim().min(2).max(100).optional() }).parse(req.body);
|
||||
const id = String(req.params.id);
|
||||
const user = await prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new HttpError(404, 'Пользователь не найден');
|
||||
const losesAdmin = user.role === 'ADMIN' && ((input.role && input.role !== 'ADMIN') || input.blocked === true);
|
||||
if (losesAdmin) {
|
||||
if (id === req.user!.id) throw new HttpError(400, 'Нельзя понизить или заблокировать самого себя');
|
||||
await assertAdminRemains(id);
|
||||
}
|
||||
const updated = await prisma.user.update({ where: { id }, data: input });
|
||||
// Заблокированного сразу выкидываем со всех устройств
|
||||
if (input.blocked) await prisma.session.deleteMany({ where: { userId: id } });
|
||||
res.json({ id: updated.id, role: updated.role, blocked: updated.blocked, name: updated.name });
|
||||
});
|
||||
|
||||
adminRouter.delete('/users/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (id === req.user!.id) throw new HttpError(400, 'Нельзя удалить самого себя');
|
||||
const user = await prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new HttpError(404, 'Пользователь не найден');
|
||||
if (user.role === 'ADMIN') await assertAdminRemains(id);
|
||||
await prisma.user.delete({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Приглашения ----------
|
||||
const toInvite = (i: { id: string; token: string; role: 'ADMIN' | 'EDITOR' | 'VIEWER'; expiresAt: Date; usedAt: Date | null }): InviteDto => ({
|
||||
id: i.id,
|
||||
token: i.token,
|
||||
role: i.role,
|
||||
expiresAt: i.expiresAt.toISOString(),
|
||||
usedAt: i.usedAt?.toISOString() ?? null,
|
||||
url: `${env.PUBLIC_URL.replace(/\/$/, '')}/invite/${i.token}`,
|
||||
});
|
||||
|
||||
adminRouter.get('/invites', async (_req, res) => {
|
||||
const rows = await prisma.invite.findMany({ where: { usedAt: null, expiresAt: { gt: new Date() } }, orderBy: { createdAt: 'desc' } });
|
||||
res.json(rows.map(toInvite));
|
||||
});
|
||||
|
||||
adminRouter.post('/invites', async (req, res) => {
|
||||
const input = z.object({ role: role.default('VIEWER') }).parse(req.body);
|
||||
const invite = await prisma.invite.create({
|
||||
data: { token: nanoid(32), role: input.role, expiresAt: new Date(Date.now() + INVITE_DAYS * 86_400_000) },
|
||||
});
|
||||
res.status(201).json(toInvite(invite));
|
||||
});
|
||||
|
||||
adminRouter.delete('/invites/:id', async (req, res) => {
|
||||
await prisma.invite.deleteMany({ where: { id: String(req.params.id) } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Пространства ----------
|
||||
const spaceBody = z.object({ name: z.string().trim().min(1, 'Укажите название').max(60), icon: z.string().trim().max(4).nullish() });
|
||||
|
||||
async function freeSlug(base: string, taken: (slug: string) => Promise<boolean>) {
|
||||
for (let i = 1; ; i++) {
|
||||
const slug = i === 1 ? base : `${base}-${i}`;
|
||||
if (!(await taken(slug))) return slug;
|
||||
}
|
||||
}
|
||||
|
||||
adminRouter.post('/spaces', async (req, res) => {
|
||||
const input = spaceBody.parse(req.body);
|
||||
const slug = await freeSlug(slugify(input.name), async (s) => !!(await prisma.space.findUnique({ where: { slug: s } })));
|
||||
const last = await prisma.space.aggregate({ _max: { order: true } });
|
||||
const space = await prisma.space.create({
|
||||
data: { name: input.name, slug, icon: input.icon || input.name[0]!.toUpperCase(), order: (last._max.order ?? 0) + 1 },
|
||||
});
|
||||
res.status(201).json(toSpaceDto(space));
|
||||
});
|
||||
|
||||
adminRouter.patch('/spaces/:id', async (req, res) => {
|
||||
const input = spaceBody.partial().parse(req.body);
|
||||
const space = await prisma.space.update({ where: { id: String(req.params.id) }, data: input }).catch(() => null);
|
||||
if (!space) throw new HttpError(404, 'Пространство не найдено');
|
||||
res.json(toSpaceDto(space));
|
||||
});
|
||||
|
||||
adminRouter.delete('/spaces/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (await prisma.section.count({ where: { spaceId: id } })) throw new HttpError(400, 'Сначала удалите или перенесите разделы');
|
||||
await prisma.space.deleteMany({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Разделы ----------
|
||||
const color = z.enum(['yellow', 'orange', 'blue', 'green', 'ink']);
|
||||
const sectionBody = z.object({
|
||||
spaceId: z.string().min(1),
|
||||
name: z.string().trim().min(1, 'Укажите название').max(80),
|
||||
code: z.string().trim().min(1, 'Укажите код').max(4),
|
||||
color: color.default('ink'),
|
||||
icon: z.string().trim().max(4).nullish(),
|
||||
});
|
||||
|
||||
adminRouter.post('/sections', async (req, res) => {
|
||||
const input = sectionBody.parse(req.body);
|
||||
if (!(await prisma.space.findUnique({ where: { id: input.spaceId } }))) throw new HttpError(400, 'Пространство не найдено');
|
||||
const slug = await freeSlug(slugify(input.name), async (s) => !!(await prisma.section.findUnique({ where: { slug: s } })));
|
||||
const last = await prisma.section.aggregate({ where: { spaceId: input.spaceId }, _max: { order: true } });
|
||||
const section = await prisma.section.create({
|
||||
data: { ...input, code: input.code.toUpperCase(), slug, order: (last._max.order ?? 0) + 1 },
|
||||
});
|
||||
res.status(201).json(toSectionDto(section));
|
||||
});
|
||||
|
||||
adminRouter.patch('/sections/:id', async (req, res) => {
|
||||
const input = sectionBody.omit({ spaceId: true }).partial().parse(req.body);
|
||||
const section = await prisma.section
|
||||
.update({ where: { id: String(req.params.id) }, data: { ...input, ...(input.code ? { code: input.code.toUpperCase() } : {}) } })
|
||||
.catch(() => null);
|
||||
if (!section) throw new HttpError(404, 'Раздел не найден');
|
||||
res.json(toSectionDto(section));
|
||||
});
|
||||
|
||||
adminRouter.delete('/sections/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (await prisma.article.count({ where: { sectionId: id } })) throw new HttpError(400, 'В разделе есть статьи: сначала перенесите или удалите их');
|
||||
await prisma.section.deleteMany({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Новый порядок разделов после перетаскивания: присылается полный список id
|
||||
adminRouter.put('/sections/order', async (req, res) => {
|
||||
const { ids } = z.object({ ids: z.array(z.string()).min(1).max(500) }).parse(req.body);
|
||||
await prisma.$transaction(ids.map((id, order) => prisma.section.updateMany({ where: { id }, data: { order } })));
|
||||
res.status(204).end();
|
||||
});
|
||||
@@ -0,0 +1,311 @@
|
||||
// Редактирование статей. Все маршруты доступны только редакторам и админам:
|
||||
// проверка стоит здесь, на сервере, а не только в интерфейсе.
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import multer from 'multer';
|
||||
import { nanoid } from 'nanoid';
|
||||
import sharp from 'sharp';
|
||||
import { z } from 'zod';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { RevisionDto } from '@kb/shared';
|
||||
import { requireRole } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { deriveFacts, linkAssets, renderArticle, rerenderAll, updateSearchIndex } from '../services/articles.js';
|
||||
import { storeImage, uploadPath } from '../services/images.js';
|
||||
|
||||
export const editRouter = Router();
|
||||
editRouter.use(requireRole('EDITOR'));
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
export const MAX_IMAGE = 15 * MB;
|
||||
export const MAX_DOC = 30 * MB;
|
||||
|
||||
// Файлы принимаем в память: дальше картинку всё равно пережимает sharp, а документ проверяем по содержимому
|
||||
const uploadImage = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_IMAGE, files: 1 } }).single('file');
|
||||
const uploadDoc = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_DOC, files: 1 } }).single('file');
|
||||
|
||||
const meta = z.object({
|
||||
title: z.string().trim().min(2, 'Укажите название').max(200),
|
||||
summary: z.string().trim().max(500).default(''),
|
||||
sectionId: z.string().min(1, 'Выберите раздел'),
|
||||
tags: z.array(z.string().trim().min(1).max(60)).max(30).default([]),
|
||||
equipment: z.array(z.string().trim().min(1).max(80)).max(30).default([]),
|
||||
docCode: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(200)
|
||||
.nullish()
|
||||
.transform((v) => v || null),
|
||||
pinned: z.boolean().default(false),
|
||||
visibility: z.enum(['PRIVATE', 'PUBLIC']).default('PRIVATE'),
|
||||
order: z.number().int().min(0).max(9999).default(0),
|
||||
});
|
||||
const body = z.object({ md: z.string().max(400_000), meta });
|
||||
|
||||
const TRANSLIT: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
|
||||
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch',
|
||||
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
};
|
||||
|
||||
/** «Стойка въезда — слаботочка» → stoyka-vezda-slabotochka */
|
||||
export function slugify(title: string): string {
|
||||
const s = [...title.toLowerCase()]
|
||||
.map((ch) => TRANSLIT[ch] ?? ch)
|
||||
.join('')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 60)
|
||||
.replace(/-+$/, '');
|
||||
return s || 'statya';
|
||||
}
|
||||
|
||||
async function uniqueSlug(base: string): Promise<string> {
|
||||
for (let i = 1; ; i++) {
|
||||
const slug = i === 1 ? base : `${base}-${i}`;
|
||||
if (!(await prisma.article.findUnique({ where: { slug }, select: { id: true } }))) return slug;
|
||||
}
|
||||
}
|
||||
|
||||
async function getArticle(id: string) {
|
||||
const art = await prisma.article.findUnique({ where: { id } });
|
||||
if (!art) throw new HttpError(404, 'Статья не найдена');
|
||||
return art;
|
||||
}
|
||||
|
||||
// Данные для редактора: опубликованный текст, несохранённый черновик, вложения
|
||||
editRouter.get('/articles/:slug', async (req, res) => {
|
||||
const art = await prisma.article.findUnique({
|
||||
where: { slug: String(req.params.slug) },
|
||||
include: { attachments: { orderBy: { createdAt: 'asc' } } },
|
||||
});
|
||||
if (!art) throw new HttpError(404, 'Статья не найдена');
|
||||
res.json({
|
||||
id: art.id,
|
||||
slug: art.slug,
|
||||
status: art.status,
|
||||
version: art.version,
|
||||
updatedAt: art.updatedAt.toISOString(),
|
||||
md: art.bodyMd,
|
||||
meta: {
|
||||
title: art.title,
|
||||
summary: art.summary,
|
||||
sectionId: art.sectionId,
|
||||
tags: art.tags,
|
||||
equipment: art.equipment,
|
||||
docCode: art.docCode,
|
||||
pinned: art.pinned,
|
||||
visibility: art.visibility,
|
||||
order: art.order,
|
||||
},
|
||||
draft: art.draftMd !== null ? { md: art.draftMd, meta: art.draftMeta, at: art.draftAt?.toISOString() ?? null } : null,
|
||||
attachments: art.attachments.map((a) => ({ id: a.id, filename: a.filename, url: `/uploads/${a.path}`, size: a.size })),
|
||||
});
|
||||
});
|
||||
|
||||
// Новая статья: создаётся черновиком, читатели её не видят до публикации
|
||||
editRouter.post('/articles', async (req, res) => {
|
||||
const input = z.object({ title: meta.shape.title, sectionId: meta.shape.sectionId }).parse(req.body);
|
||||
const section = await prisma.section.findUnique({ where: { id: input.sectionId } });
|
||||
if (!section) throw new HttpError(400, 'Раздел не найден');
|
||||
const slug = await uniqueSlug(slugify(input.title));
|
||||
const last = await prisma.article.aggregate({ where: { sectionId: section.id }, _max: { order: true } });
|
||||
const art = await prisma.article.create({
|
||||
data: {
|
||||
slug,
|
||||
title: input.title,
|
||||
sectionId: section.id,
|
||||
bodyMd: '',
|
||||
bodyHtml: '',
|
||||
status: 'DRAFT',
|
||||
order: (last._max.order ?? 0) + 1,
|
||||
authorId: req.user!.id,
|
||||
},
|
||||
});
|
||||
res.status(201).json({ id: art.id, slug: art.slug });
|
||||
});
|
||||
|
||||
// Автосохранение и кнопка «Черновик»: пишем в отдельные поля, опубликованный текст не трогаем
|
||||
editRouter.put('/articles/:id/draft', async (req, res) => {
|
||||
const input = body.parse(req.body);
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const draftAt = new Date();
|
||||
await prisma.article.update({
|
||||
where: { id: art.id },
|
||||
data: { draftMd: input.md, draftMeta: input.meta as unknown as Prisma.InputJsonValue, draftAt },
|
||||
});
|
||||
res.json({ at: draftAt.toISOString() });
|
||||
});
|
||||
|
||||
editRouter.delete('/articles/:id/draft', async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.update({ where: { id: art.id }, data: { draftMd: null, draftMeta: Prisma.JsonNull, draftAt: null } }); // Prisma.JsonNull: так в JSON-поле пишется NULL
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Публикация: новая версия, запись в историю, пересчёт HTML и поискового индекса
|
||||
editRouter.post('/articles/:id/publish', async (req, res) => {
|
||||
const input = body.extend({ comment: z.string().trim().max(200).optional() }).parse(req.body);
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const section = await prisma.section.findUnique({ where: { id: input.meta.sectionId } });
|
||||
if (!section) throw new HttpError(400, 'Раздел не найден');
|
||||
if (!input.md.trim()) throw new HttpError(400, 'Нельзя опубликовать пустую статью');
|
||||
|
||||
const md = input.md.replace(/\r\n?/g, '\n').trim() + '\n';
|
||||
const first = art.status === 'DRAFT' && art.version === 1 && !art.bodyMd;
|
||||
const changed = md !== art.bodyMd || input.meta.title !== art.title;
|
||||
const version = first ? 1 : changed ? art.version + 1 : art.version;
|
||||
const titleChanged = input.meta.title !== art.title;
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Закреплённой (шпаргалкой) может быть только одна статья
|
||||
if (input.meta.pinned) await tx.article.updateMany({ where: { pinned: true, id: { not: art.id } }, data: { pinned: false } });
|
||||
await tx.article.update({
|
||||
where: { id: art.id },
|
||||
data: {
|
||||
...input.meta,
|
||||
bodyMd: md,
|
||||
version,
|
||||
status: 'PUBLISHED',
|
||||
updatedAt: new Date(),
|
||||
draftMd: null,
|
||||
draftMeta: Prisma.JsonNull,
|
||||
draftAt: null,
|
||||
},
|
||||
});
|
||||
if (first || changed) {
|
||||
await tx.articleRevision.upsert({
|
||||
where: { articleId_version: { articleId: art.id, version } },
|
||||
create: { articleId: art.id, version, title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment },
|
||||
update: { title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment, createdAt: new Date() },
|
||||
});
|
||||
}
|
||||
const render = await renderArticle(md, tx);
|
||||
await tx.article.update({
|
||||
where: { id: art.id },
|
||||
data: { bodyHtml: render.html, facts: deriveFacts(md, input.meta.pinned, render) as unknown as Prisma.InputJsonValue },
|
||||
});
|
||||
await updateSearchIndex(art.id, { ...input.meta, render }, tx);
|
||||
await linkAssets(art.id, render, tx);
|
||||
});
|
||||
|
||||
// Новая статья или новое название: в других статьях [[ссылки]] на неё должны показать актуальное название
|
||||
if (first || titleChanged) await rerenderAll();
|
||||
|
||||
res.json({ slug: art.slug, version, at: new Date().toISOString() });
|
||||
});
|
||||
|
||||
editRouter.post('/articles/:id/unpublish', async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.update({ where: { id: art.id }, data: { status: 'DRAFT' } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
editRouter.delete('/articles/:id', requireRole('ADMIN'), async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.delete({ where: { id: art.id } });
|
||||
await rerenderAll();
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- История версий ----------
|
||||
editRouter.get('/articles/:id/revisions', async (req, res) => {
|
||||
const rows = await prisma.articleRevision.findMany({
|
||||
where: { articleId: String(req.params.id) },
|
||||
orderBy: { version: 'desc' },
|
||||
include: { author: { select: { name: true } } },
|
||||
});
|
||||
const list: RevisionDto[] = rows.map((r) => ({
|
||||
id: r.id,
|
||||
version: r.version,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
authorName: r.author?.name ?? null,
|
||||
comment: r.comment,
|
||||
}));
|
||||
res.json(list);
|
||||
});
|
||||
|
||||
editRouter.get('/articles/:id/revisions/:version', async (req, res) => {
|
||||
const rev = await prisma.articleRevision.findUnique({
|
||||
where: { articleId_version: { articleId: String(req.params.id), version: Number(req.params.version) || 0 } },
|
||||
});
|
||||
if (!rev) throw new HttpError(404, 'Версия не найдена');
|
||||
res.json({ version: rev.version, title: rev.title, md: rev.bodyMd });
|
||||
});
|
||||
|
||||
// ---------- Загрузка картинок ----------
|
||||
const IMAGE_FORMATS = new Set(['jpeg', 'png', 'webp', 'gif', 'heif', 'tiff']);
|
||||
|
||||
editRouter.post('/images', uploadImage, async (req, res) => {
|
||||
const file = req.file;
|
||||
if (!file) throw new HttpError(400, 'Файл не получен');
|
||||
// Тип определяем по содержимому, а не по имени или заголовку: sharp читает сам файл
|
||||
let format: string | undefined;
|
||||
try {
|
||||
format = (await sharp(file.buffer).metadata()).format;
|
||||
} catch {
|
||||
format = undefined;
|
||||
}
|
||||
if (!format || !IMAGE_FORMATS.has(format)) throw new HttpError(400, 'Это не картинка (нужен JPG, PNG, WebP или HEIC)');
|
||||
|
||||
const now = new Date();
|
||||
const key = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${nanoid(12)}`;
|
||||
const img = await storeImage(file.buffer, key);
|
||||
const articleId = typeof req.body?.articleId === 'string' && req.body.articleId ? req.body.articleId : null;
|
||||
await prisma.asset.create({
|
||||
data: { path: img.path, mime: 'image/webp', size: img.size, width: img.width, height: img.height, uploadedById: req.user!.id, articleId },
|
||||
});
|
||||
res.status(201).json({ url: `/uploads/${img.path}`, width: img.width, height: img.height });
|
||||
});
|
||||
|
||||
// ---------- Исходники (PDF, DOCX…) ----------
|
||||
// Расширение → с каких байтов должен начинаться файл
|
||||
const DOC_SIGNATURES: Record<string, number[][]> = {
|
||||
pdf: [[0x25, 0x50, 0x44, 0x46]], // %PDF
|
||||
docx: [[0x50, 0x4b, 0x03, 0x04]], // ZIP
|
||||
xlsx: [[0x50, 0x4b, 0x03, 0x04]],
|
||||
doc: [[0xd0, 0xcf, 0x11, 0xe0]], // старый формат Office
|
||||
xls: [[0xd0, 0xcf, 0x11, 0xe0]],
|
||||
dwg: [[0x41, 0x43, 0x31, 0x30]], // AC10
|
||||
};
|
||||
|
||||
editRouter.post('/articles/:id/attachments', uploadDoc, async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const file = req.file;
|
||||
if (!file) throw new HttpError(400, 'Файл не получен');
|
||||
// multer отдаёт имя в latin1: возвращаем нормальный UTF-8
|
||||
const original = Buffer.from(file.originalname, 'latin1').toString('utf8');
|
||||
const ext = path.extname(original).slice(1).toLowerCase();
|
||||
const signatures = DOC_SIGNATURES[ext];
|
||||
if (!signatures) throw new HttpError(400, 'Можно прикрепить PDF, DOC, DOCX, XLS, XLSX или DWG');
|
||||
if (!signatures.some((sig) => sig.every((b, i) => file.buffer[i] === b))) {
|
||||
throw new HttpError(400, 'Содержимое файла не соответствует расширению');
|
||||
}
|
||||
|
||||
const base = slugify(path.basename(original, path.extname(original))).replace(/-/g, '_') || 'file';
|
||||
const rel = `originals/${art.id}/${base}.${ext}`;
|
||||
const abs = uploadPath(rel);
|
||||
await fs.mkdir(path.dirname(abs), { recursive: true });
|
||||
await fs.writeFile(abs, file.buffer);
|
||||
const data = { filename: `${base}.${ext}`, size: file.size };
|
||||
const att = await prisma.attachment.upsert({
|
||||
where: { articleId_path: { articleId: art.id, path: rel } },
|
||||
create: { articleId: art.id, path: rel, ...data },
|
||||
update: data,
|
||||
});
|
||||
res.status(201).json({ id: att.id, filename: att.filename, url: `/uploads/${att.path}`, size: att.size });
|
||||
});
|
||||
|
||||
editRouter.delete('/attachments/:id', async (req, res) => {
|
||||
const att = await prisma.attachment.findUnique({ where: { id: String(req.params.id) } });
|
||||
if (!att) throw new HttpError(404, 'Файл не найден');
|
||||
await prisma.attachment.delete({ where: { id: att.id } });
|
||||
// Файл стартового импорта может быть общим для нескольких статей: удаляем с диска, только если больше не нужен
|
||||
if (!(await prisma.attachment.count({ where: { path: att.path } }))) {
|
||||
await fs.rm(uploadPath(att.path), { force: true });
|
||||
}
|
||||
res.status(204).end();
|
||||
});
|
||||
Reference in New Issue
Block a user