docs: вложения статей (doc_files), подписи и библиотека картинок, быстрое ред. отзыва
This commit is contained in:
@@ -80,6 +80,17 @@ const {
|
||||
deleteArticle: deleteDocArticle,
|
||||
reorderArticles: reorderDocArticles,
|
||||
registerImage: registerDocImage,
|
||||
listDocImages: listDocImages,
|
||||
deleteDocImage: deleteDocImage,
|
||||
updateDocImageCaption: updateDocImageCaption,
|
||||
listAllImages: listAllDocImages,
|
||||
listAllFiles: listAllDocFiles,
|
||||
registerFile: registerFile,
|
||||
listDocFiles,
|
||||
listUnattachedDocFiles,
|
||||
attachDocFile,
|
||||
replaceDocFile,
|
||||
deleteDocFile,
|
||||
searchArticles: searchDocArticles,
|
||||
publicTree: publicDocTree,
|
||||
publicArticle: publicDocArticle,
|
||||
@@ -871,7 +882,13 @@ async function sendImageThumb(res, key) {
|
||||
const tp = thumbFileFor(key);
|
||||
try {
|
||||
if (fs.existsSync(tp)) {
|
||||
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
// self-heal: if the original is gone, drop the stale thumb and 404
|
||||
const origExists = await storage.head(key);
|
||||
if (!origExists) {
|
||||
try { fs.unlinkSync(tp); } catch {}
|
||||
return res.status(404).end();
|
||||
}
|
||||
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||
return res.sendFile(tp);
|
||||
}
|
||||
} catch {}
|
||||
@@ -887,7 +904,7 @@ async function sendImageThumb(res, key) {
|
||||
await sharp(local).rotate().resize({ width: THUMB_WIDTH, withoutEnlargement: true }).webp({ quality: 85 }).toFile(tmp);
|
||||
fs.renameSync(tmp, tp);
|
||||
}
|
||||
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||||
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||
return res.sendFile(tp);
|
||||
} catch {
|
||||
try { if (fs.existsSync(tp)) fs.unlinkSync(tp); } catch {}
|
||||
@@ -1601,6 +1618,30 @@ const adminUpload = multer({
|
||||
},
|
||||
});
|
||||
|
||||
const DOC_FILE_ALLOWED_EXT = new Set(['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.md', '.csv', '.rtf', '.odt', '.ods', '.odp', '.zip', '.rar', '.7z', '.json', '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.avif']);
|
||||
const docFileUpload = multer({
|
||||
storage: multer.diskStorage({
|
||||
destination: (_, __, cb) => {
|
||||
fs.mkdirSync('uploads', { recursive: true });
|
||||
cb(null, 'uploads');
|
||||
},
|
||||
filename: (_, file, cb) => {
|
||||
const original = fixFilename(file.originalname);
|
||||
const ext = path.extname(original) || '.bin';
|
||||
cb(null, `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`);
|
||||
},
|
||||
}),
|
||||
limits: { fileSize: MAX_FILE_UPLOAD_BYTES },
|
||||
fileFilter: (req, file, cb) => {
|
||||
file.originalname = fixFilename(file.originalname);
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
if (!ext || !DOC_FILE_ALLOWED_EXT.has(ext)) {
|
||||
return cb(new Error('Not allowed extension'));
|
||||
}
|
||||
cb(null, true);
|
||||
},
|
||||
});
|
||||
|
||||
async function getSetting(key, def) {
|
||||
const cached = await cacheGet('setting:' + key);
|
||||
if (cached !== undefined) return cached;
|
||||
@@ -1767,7 +1808,7 @@ async function removeEntryFiles(entryId) {
|
||||
async function sweepOrphanedUploads() {
|
||||
const dir = UPLOADS_DIR;
|
||||
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }] = await Promise.all([
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }] = await Promise.all([
|
||||
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM project_files'),
|
||||
pool.query('SELECT photo_path AS p FROM group_photos'),
|
||||
@@ -1786,9 +1827,10 @@ async function sweepOrphanedUploads() {
|
||||
pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT photo_path AS p FROM student_face_refs'),
|
||||
pool.query('SELECT path AS p FROM doc_images'),
|
||||
pool.query('SELECT path AS p FROM doc_files'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos].forEach(r => {
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles].forEach(r => {
|
||||
const key = storage.keyFromPath(r.p);
|
||||
if (key) refs.add(key);
|
||||
});
|
||||
@@ -1826,6 +1868,7 @@ const BROKEN_IMAGE_SOURCES = [
|
||||
{ key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' },
|
||||
{ key: 'student_face_refs.photo_path', table: 'student_face_refs', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Эталон лица' },
|
||||
{ key: 'doc_images.path', table: 'doc_images', column: 'path', idColumn: 'id', kind: 'row', label: 'Картинка документации' },
|
||||
{ key: 'doc_files.path', table: 'doc_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение документации' },
|
||||
{ key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' },
|
||||
{ key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' },
|
||||
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
|
||||
@@ -5401,7 +5444,12 @@ app.delete('/api/docs/articles/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const id = reqInt(req.params.id);
|
||||
const images = await deleteDocArticle(pool, req.user, id);
|
||||
images.forEach(p => { safeUnlink(p); thumbUnlinkFor(p); });
|
||||
await Promise.all(images.map(async p => {
|
||||
safeUnlink(p);
|
||||
thumbUnlinkFor(p);
|
||||
const key = storage.keyFromPath(p);
|
||||
if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } }
|
||||
}));
|
||||
await logAudit(req, 'docs.article.delete', { id });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
@@ -5431,6 +5479,163 @@ app.post('/api/docs/images', requireAuth, (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/docs/articles/:id/files', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const items = await listDocFiles(pool, req.user, reqInt(req.params.id));
|
||||
res.json({ items });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить вложения', 'docs files list');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/files/unattached', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listUnattachedDocFiles(pool, req.user) });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить файлы', 'docs files unattached');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/docs/files', requireAuth, (req, res) => {
|
||||
docFileUpload.single('file')(req, res, async err => {
|
||||
if (err) {
|
||||
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
|
||||
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
|
||||
return res.status(400).json({ error: 'Недопустимый файл' });
|
||||
}
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
const item = await registerFile(pool, {
|
||||
path: `/uploads/${req.file.filename}`,
|
||||
name: req.file.originalname,
|
||||
size: req.file.size,
|
||||
mime: req.file.mimetype,
|
||||
userId: req.user.id,
|
||||
articleId: req.body?.article_id ? reqInt(req.body.article_id) : null,
|
||||
});
|
||||
await logAudit(req, 'docs.file.create', { id: item.id, path: item.path, article_id: item.article_id });
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
removeUpload(req.file);
|
||||
docsError(res, e, 'Не удалось загрузить файл', 'docs file upload');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.put('/api/docs/files/:id/attach', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const item = await attachDocFile(pool, req.user, reqInt(req.params.id), req.body?.article_id == null ? null : reqInt(req.body.article_id));
|
||||
await logAudit(req, 'docs.file.attach', { id: item.id, article_id: item.article_id });
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось изменить привязку файла', 'docs file attach');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/docs/files/:id/replace', requireAuth, (req, res) => {
|
||||
docFileUpload.single('file')(req, res, async err => {
|
||||
if (err) {
|
||||
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
|
||||
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
|
||||
return res.status(400).json({ error: 'Недопустимый файл' });
|
||||
}
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
const { item, oldPath } = await replaceDocFile(pool, req.user, reqInt(req.params.id), {
|
||||
path: `/uploads/${req.file.filename}`,
|
||||
name: req.file.originalname,
|
||||
size: req.file.size,
|
||||
mime: req.file.mimetype,
|
||||
});
|
||||
safeUnlink(oldPath);
|
||||
thumbUnlinkFor(oldPath);
|
||||
const oldKey = storage.keyFromPath(oldPath);
|
||||
if (oldKey && storage.isRemote()) { try { await storage.del(oldKey); } catch (e) { console.error('Upload delete failed:', oldKey, e.message); } }
|
||||
await logAudit(req, 'docs.file.replace', { id: item.id, old: oldPath, new: item.path });
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
removeUpload(req.file);
|
||||
docsError(res, e, 'Не удалось заменить файл', 'docs file replace');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.delete('/api/docs/files/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const path = await deleteDocFile(pool, req.user, reqInt(req.params.id));
|
||||
safeUnlink(path);
|
||||
thumbUnlinkFor(path);
|
||||
const key = storage.keyFromPath(path);
|
||||
if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } }
|
||||
await logAudit(req, 'docs.file.delete', { path });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось удалить файл', 'docs file delete');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/images', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listAllDocImages(pool, req.user) });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить изображения', 'docs images all');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/files', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const articleId = req.query.article_id ? reqInt(req.query.article_id) : null;
|
||||
if (articleId) {
|
||||
res.json({ items: await listDocFiles(pool, req.user, articleId) });
|
||||
} else {
|
||||
res.json({ items: await listAllDocFiles(pool, req.user) });
|
||||
}
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить файлы', 'docs files all');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/articles/:id/images', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const items = await listDocImages(pool, req.user, reqInt(req.params.id));
|
||||
res.json({ items });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить изображения', 'docs images list');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/images/unattached', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await listDocImages(pool, req.user, null) });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось загрузить изображения', 'docs images unattached');
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/docs/images/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const result = await updateDocImageCaption(pool, req.user, reqInt(req.params.id), req.body?.caption);
|
||||
await logAudit(req, 'docs.image.caption', { path: result.path, caption: result.caption });
|
||||
res.json({ item: result });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось сохранить подпись', 'docs image caption');
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/docs/images/:id', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const path = await deleteDocImage(pool, req.user, reqInt(req.params.id));
|
||||
safeUnlink(path);
|
||||
thumbUnlinkFor(path);
|
||||
const key = storage.keyFromPath(path);
|
||||
if (key && storage.isRemote()) { try { await storage.del(key); } catch (e) { console.error('Upload delete failed:', key, e.message); } }
|
||||
await logAudit(req, 'docs.image.delete', { path });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
docsError(res, e, 'Не удалось удалить изображение', 'docs image delete');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/public/tree', apiLimiter, async (req, res) => {
|
||||
try {
|
||||
res.json(await publicDocTree(pool));
|
||||
@@ -6868,6 +7073,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM photo_faces');
|
||||
await client.query('DELETE FROM student_face_refs');
|
||||
await client.query('DELETE FROM doc_images');
|
||||
await client.query('DELETE FROM doc_files');
|
||||
await client.query('DELETE FROM doc_articles');
|
||||
await client.query('DELETE FROM doc_sections');
|
||||
await client.query('DELETE FROM users');
|
||||
@@ -6931,8 +7137,14 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
for (const x of (ndata.doc_images || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO doc_images (id, article_id, path, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, (SELECT id FROM users WHERE id = $4), $5)',
|
||||
[x.id, x.article_id, x.path, x.uploaded_by, x.created_at || null]
|
||||
'INSERT INTO doc_images (id, article_id, path, caption, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, $4, (SELECT id FROM users WHERE id = $5), $6)',
|
||||
[x.id, x.article_id, x.path, x.caption || null, x.uploaded_by, x.created_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.doc_files || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO doc_files (id, article_id, name, path, size_bytes, mime, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, $4, $5, $6, (SELECT id FROM users WHERE id = $7), $8)',
|
||||
[x.id, x.article_id, x.name, x.path, x.size_bytes, x.mime, x.uploaded_by, x.created_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.user_branches) {
|
||||
|
||||
Reference in New Issue
Block a user