groups: AI enhance for gallery photos (photo_jobs.group_photo_id, before/after compare modal)
This commit is contained in:
@@ -352,7 +352,15 @@ async function pushNotification({ type, title, body, link, target, branchId, lev
|
||||
}
|
||||
}
|
||||
|
||||
async function notifyEntry(entryId, { type, title, body, link, target, level }) {
|
||||
async function notifyEntry(entryIdOrJob, { type, title, body, link, target, level }) {
|
||||
if (entryIdOrJob && typeof entryIdOrJob === 'object' && !Array.isArray(entryIdOrJob)) {
|
||||
const job = entryIdOrJob;
|
||||
if (job.group_photo_id) {
|
||||
return notifyGroupPhoto(job.group_photo_id, { type, title, body, link, target, level });
|
||||
}
|
||||
return notifyEntry(job.entry_id, { type, title, body, link, target, level });
|
||||
}
|
||||
const entryId = entryIdOrJob;
|
||||
const id = parseInt(entryId, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return null;
|
||||
const { rows } = await pool.query(
|
||||
@@ -376,6 +384,30 @@ async function notifyEntry(entryId, { type, title, body, link, target, level })
|
||||
});
|
||||
}
|
||||
|
||||
async function notifyGroupPhoto(groupPhotoId, { type, title, body, link, target, level }) {
|
||||
const id = parseInt(groupPhotoId, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return null;
|
||||
const { rows } = await pool.query(
|
||||
`SELECT gp.id, gp.group_id, g.name AS group_name, g.branch_id
|
||||
FROM group_photos gp LEFT JOIN groups g ON g.id = gp.group_id WHERE gp.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!rows.length) return null;
|
||||
const ctx = rows[0];
|
||||
const fill = s => String(s === null || s === undefined ? '' : s)
|
||||
.replace(/\{student\}/g, '')
|
||||
.replace(/\{group\}/g, ctx.group_name || '—');
|
||||
return pushNotification({
|
||||
type,
|
||||
level,
|
||||
title: fill(title),
|
||||
body: fill(body),
|
||||
link: link || 'groups.html',
|
||||
target: Object.assign({ group_photo_id: ctx.id, group_id: ctx.group_id, group_name: ctx.group_name }, target || {}),
|
||||
branchId: ctx.branch_id,
|
||||
});
|
||||
}
|
||||
|
||||
async function notifyEntryCreated(entryId) {
|
||||
return notifyEntry(entryId, {
|
||||
type: 'entry.new',
|
||||
@@ -796,6 +828,15 @@ app.get('/uploads/*', async (req, res) => {
|
||||
app.use('/vendor', express.static(path.join(__dirname, 'public', 'vendor'), { maxAge: '30d' }));
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
app.get('/certs/cert.pem', (req, res) => {
|
||||
const certPath = path.join(__dirname, 'certs', 'cert.pem');
|
||||
if (fs.existsSync(certPath)) {
|
||||
res.download(certPath, 'cert.pem');
|
||||
} else {
|
||||
res.status(404).send('Certificate not found');
|
||||
}
|
||||
});
|
||||
|
||||
const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function formatBytes(bytes) {
|
||||
@@ -1495,10 +1536,11 @@ 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: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }] = 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: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }] = 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'),
|
||||
pool.query('SELECT photo_original_path AS p FROM group_photos WHERE photo_original_path IS NOT NULL'),
|
||||
pool.query('SELECT photo_path AS p FROM entry_photos'),
|
||||
pool.query(`SELECT after_path AS p FROM photo_jobs WHERE status = 'done' AND applied = false AND after_path IS NOT NULL`),
|
||||
pool.query('SELECT photo_path AS p FROM modules WHERE photo_path IS NOT NULL'),
|
||||
@@ -1511,7 +1553,7 @@ async function sweepOrphanedUploads() {
|
||||
pool.query('SELECT path AS p FROM chat_attachments'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles].forEach(r => {
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles].forEach(r => {
|
||||
const key = storage.keyFromPath(r.p);
|
||||
if (key) refs.add(key);
|
||||
});
|
||||
@@ -1653,6 +1695,7 @@ async function ensureLessonReportsTable() {
|
||||
|
||||
async function ensurePhotoOriginalColumn() {
|
||||
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`);
|
||||
await pool.query(`ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`);
|
||||
}
|
||||
|
||||
async function ensureEntryAiColumns() {
|
||||
@@ -1689,7 +1732,8 @@ async function ensureEntryAiColumns() {
|
||||
async function ensurePhotoJobsTable() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS photo_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
entry_id INT NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
|
||||
entry_id INT REFERENCES entries(id) ON DELETE CASCADE,
|
||||
group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE,
|
||||
action VARCHAR(20) NOT NULL DEFAULT 'ai',
|
||||
params JSONB,
|
||||
before_path VARCHAR(255),
|
||||
@@ -1702,8 +1746,11 @@ async function ensurePhotoJobsTable() {
|
||||
finished_at TIMESTAMPTZ
|
||||
)`);
|
||||
await pool.query(`ALTER TABLE photo_jobs ADD COLUMN IF NOT EXISTS applied BOOLEAN NOT NULL DEFAULT false`);
|
||||
await pool.query(`ALTER TABLE photo_jobs ADD COLUMN IF NOT EXISTS group_photo_id INT REFERENCES group_photos(id) ON DELETE CASCADE`);
|
||||
await pool.query(`ALTER TABLE photo_jobs ALTER COLUMN entry_id DROP NOT NULL`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_pending ON photo_jobs(id) WHERE status = 'pending'`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_entry_id ON photo_jobs(entry_id)`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_photo_jobs_group_photo_id ON photo_jobs(group_photo_id)`);
|
||||
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_worker_enabled', 'true') ON CONFLICT (key) DO NOTHING`);
|
||||
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_mode', 'off') ON CONFLICT (key) DO NOTHING`);
|
||||
await pool.query(`INSERT INTO settings (key, value) VALUES ('photo_ai_face_model', $1) ON CONFLICT (key) DO NOTHING`, [PHOTO_AI_FACE_MODEL]);
|
||||
@@ -4706,11 +4753,18 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
);
|
||||
}
|
||||
for (const x of ndata.photo_jobs) {
|
||||
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
let ok = false;
|
||||
if (x.group_photo_id) {
|
||||
const gpx = await client.query('SELECT 1 FROM group_photos WHERE id = $1', [x.group_photo_id]);
|
||||
ok = !!gpx.rowCount;
|
||||
} else if (x.entry_id) {
|
||||
const ex = await client.query('SELECT 1 FROM entries WHERE id = $1', [x.entry_id]);
|
||||
ok = !!ex.rowCount;
|
||||
}
|
||||
if (!ok) continue;
|
||||
await client.query(
|
||||
'INSERT INTO photo_jobs (id, entry_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)',
|
||||
[x.id, x.entry_id, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at]
|
||||
'INSERT INTO photo_jobs (id, entry_id, group_photo_id, action, params, before_path, after_path, status, applied, attempts, error, created_at, finished_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)',
|
||||
[x.id, x.entry_id || null, x.group_photo_id || null, x.action, x.params, x.before_path, x.after_path, x.status, x.applied, x.attempts, x.error, x.created_at, x.finished_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.project_files) {
|
||||
@@ -4721,8 +4775,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
}
|
||||
for (const x of ndata.group_photos) {
|
||||
await client.query(
|
||||
'INSERT INTO group_photos (id, group_id, photo_path, caption, taken_at, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
|
||||
[x.id, x.group_id, x.photo_path, x.caption, x.taken_at, x.sort_order, x.created_at]
|
||||
'INSERT INTO group_photos (id, group_id, photo_path, photo_original_path, caption, taken_at, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
|
||||
[x.id, x.group_id, x.photo_path, x.photo_original_path || null, x.caption, x.taken_at, x.sort_order, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.entry_photos) {
|
||||
@@ -5310,7 +5364,9 @@ async function hardDeleteGroup(groupId) {
|
||||
await client.query('BEGIN');
|
||||
const g = await client.query('SELECT id FROM groups WHERE id = $1', [groupId]);
|
||||
if (!g.rowCount) { await client.query('ROLLBACK'); return null; }
|
||||
const gres = await client.query('SELECT photo_path AS p FROM group_photos WHERE group_id = $1', [groupId]);
|
||||
const gres = await client.query(`SELECT photo_path AS p FROM group_photos WHERE group_id = $1
|
||||
UNION ALL
|
||||
SELECT photo_original_path AS p FROM group_photos WHERE group_id = $1 AND photo_original_path IS NOT NULL`, [groupId]);
|
||||
const eres = await client.query(
|
||||
`SELECT photo_path AS p FROM entries WHERE group_id = $1
|
||||
UNION ALL
|
||||
@@ -5612,11 +5668,12 @@ app.delete('/api/groups/:id/photos/:photoId', requireAuth, async (req, res) => {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2',
|
||||
'SELECT photo_path, photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2',
|
||||
[req.params.photoId, req.params.id]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
safeUnlink(rows[0].photo_path);
|
||||
if (rows[0].photo_original_path) safeUnlink(rows[0].photo_original_path);
|
||||
await pool.query('UPDATE groups SET cover_path = NULL WHERE id = $1 AND cover_path = $2', [req.params.id, rows[0].photo_path]);
|
||||
await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]);
|
||||
await logAudit(req, 'group.photo.delete', { group_id: req.params.id, photo_id: req.params.photoId });
|
||||
@@ -5643,6 +5700,314 @@ app.put('/api/groups/:id/photos/:photoId/cover', requireAuth, async (req, res) =
|
||||
res.json(gRows[0]);
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos/:photoId/enhance-ai', requireAuth, async (req, res) => {
|
||||
if (!PHOTO_AI_URL) return res.status(503).json({ error: 'ИИ-обработка фото не настроена' });
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(photoId)) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {};
|
||||
const hasParams = Object.keys(body).some((k) => body[k] !== undefined && body[k] !== null && body[k] !== '');
|
||||
const parsed = hasParams ? parsePhotoAiRequest(body) : { action: 'ai', params: null };
|
||||
if (parsed.error) return res.status(400).json({ error: parsed.error });
|
||||
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
if (!cur[0].photo_path) return res.status(400).json({ error: 'У фото нет изображения' });
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO photo_jobs (group_photo_id, action, status, params) VALUES ($1, $2, 'pending', $3) RETURNING id`,
|
||||
[photoId, parsed.action, parsed.params ? JSON.stringify(parsed.params) : null]
|
||||
);
|
||||
if (photoWorker) photoWorker.notify();
|
||||
await logAudit(req, 'group.photo.enhance-ai.queue', {
|
||||
group_id: req.params.id,
|
||||
photo_id: photoId,
|
||||
job_id: rows[0].id,
|
||||
action: parsed.action,
|
||||
params: parsed.params,
|
||||
});
|
||||
res.json({ jobId: rows[0].id, action: parsed.action, params: parsed.params });
|
||||
} catch (e) {
|
||||
console.error('POST /api/groups/:id/photos/:photoId/enhance-ai:', e);
|
||||
res.status(500).json({ error: 'Ошибка постановки задания в очередь' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/groups/:id/photos/:photoId/enhance-ai/:jobId', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
try {
|
||||
const jobId = parseInt(req.params.jobId, 10);
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
const { rows } = await pool.query(
|
||||
'SELECT id, status, error, after_path, applied FROM photo_jobs WHERE id = $1 AND group_photo_id = $2',
|
||||
[jobId, photoId]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
const job = rows[0];
|
||||
const out = { status: job.status, applied: job.applied, job_id: job.id };
|
||||
if (job.status === 'error') out.error = job.error;
|
||||
if (job.status === 'done') out.photo_path = job.after_path;
|
||||
res.json(out);
|
||||
} catch (e) {
|
||||
console.error('GET /api/groups/:id/photos/:photoId/enhance-ai/:jobId:', e);
|
||||
res.status(500).json({ error: 'Ошибка получения статуса задания' });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/apply', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const jobId = parseInt(req.params.jobId, 10);
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
await client.query('BEGIN');
|
||||
const { rows: jobRows } = await client.query(
|
||||
`SELECT id, group_photo_id, action, status, applied, after_path FROM photo_jobs
|
||||
WHERE id = $1 AND group_photo_id = $2 FOR UPDATE`,
|
||||
[jobId, photoId]
|
||||
);
|
||||
const job = jobRows[0];
|
||||
if (!job) { await client.query('ROLLBACK'); return res.status(404).json({ error: 'Задание не найдено' }); }
|
||||
if (job.status !== 'done') { await client.query('ROLLBACK'); return res.status(400).json({ error: 'Результат ещё не готов' }); }
|
||||
if (job.applied) { await client.query('ROLLBACK'); return res.status(400).json({ error: 'Результат уже применён' }); }
|
||||
if (!job.after_path || !isSafeUploadPath(job.after_path)) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(400).json({ error: 'Некорректный путь результата' });
|
||||
}
|
||||
if (!(await storage.exists(job.after_path))) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(400).json({ error: 'Файл результата не найден' });
|
||||
}
|
||||
const { rows: photoRows } = await client.query(
|
||||
'SELECT group_id, photo_path, photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2 FOR UPDATE',
|
||||
[photoId, req.params.id]
|
||||
);
|
||||
if (!photoRows.length) { await client.query('ROLLBACK'); return res.status(404).json({ error: 'Фото не найдено' }); }
|
||||
const oldPath = photoRows[0].photo_path;
|
||||
if (oldPath === job.after_path) {
|
||||
await client.query('UPDATE photo_jobs SET applied = true WHERE id = $1', [jobId]);
|
||||
await client.query('COMMIT');
|
||||
await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, after_path: job.after_path });
|
||||
invalidateShare();
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
return res.json({ ok: true, photo_path: job.after_path });
|
||||
}
|
||||
let originalPath = photoRows[0].photo_original_path;
|
||||
let beforePath = originalPath;
|
||||
const oldKey = oldPath ? storage.keyFromPath(oldPath) : null;
|
||||
if (oldKey && (await storage.exists(oldKey))) {
|
||||
try {
|
||||
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
|
||||
if (await storage.copyObject(oldKey, backupKey)) {
|
||||
beforePath = `/uploads/${backupKey}`;
|
||||
if (!originalPath) originalPath = beforePath;
|
||||
safeUnlink(oldKey);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('group photo apply backup failed:', e);
|
||||
}
|
||||
}
|
||||
await client.query('UPDATE group_photos SET photo_path = $1, photo_original_path = $2 WHERE id = $3 AND group_id = $4', [job.after_path, originalPath, photoId, req.params.id]);
|
||||
await client.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [job.after_path, req.params.id, oldPath]);
|
||||
thumbUnlinkFor(oldPath);
|
||||
await client.query(`UPDATE photo_jobs SET applied = true, before_path = COALESCE(before_path, $1) WHERE id = $2`, [beforePath, jobId]);
|
||||
await client.query('COMMIT');
|
||||
await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, before_path: beforePath, after_path: job.after_path });
|
||||
invalidateShare();
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
res.json({ ok: true, photo_path: job.after_path });
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/apply:', e);
|
||||
res.status(500).json({ error: 'Ошибка применения фотографии' });
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/reject', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
try {
|
||||
const jobId = parseInt(req.params.jobId, 10);
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, status, applied, after_path FROM photo_jobs WHERE id = $1 AND group_photo_id = $2`,
|
||||
[jobId, photoId]
|
||||
);
|
||||
const job = rows[0];
|
||||
if (!job) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
if (job.applied) return res.status(400).json({ error: 'Результат уже применён' });
|
||||
if (job.status === 'done' && job.after_path && isSafeUploadPath(job.after_path)) safeUnlink(job.after_path);
|
||||
await pool.query(
|
||||
`UPDATE photo_jobs SET status = 'rejected', error = 'Отклонено пользователем', finished_at = now()
|
||||
WHERE id = $1 AND applied = false`,
|
||||
[jobId]
|
||||
);
|
||||
await logAudit(req, 'group.photo.reject', { group_id: req.params.id, photo_id: photoId, job_id: jobId });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/reject:', e);
|
||||
res.status(500).json({ error: 'Ошибка отклонения результата' });
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/groups/:id/photos/:photoId/enhance', requireAuth, (req, res, next) => {
|
||||
if (req.is('json')) return next();
|
||||
upload.single('photo')(req, res, next);
|
||||
}, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
try {
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(photoId)) {
|
||||
if (req.file) safeUnlink(req.file.path);
|
||||
return res.status(404).json({ error: 'Фото не найдено' });
|
||||
}
|
||||
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
|
||||
if (!cur.length) {
|
||||
if (req.file) safeUnlink(req.file.path);
|
||||
return res.status(404).json({ error: 'Фото не найдено' });
|
||||
}
|
||||
const oldPath = cur[0].photo_path;
|
||||
if (!oldPath) {
|
||||
if (req.file) safeUnlink(req.file.path);
|
||||
return res.status(400).json({ error: 'У фото нет изображения' });
|
||||
}
|
||||
let newPath;
|
||||
let engine = 'client';
|
||||
if (req.is('json')) {
|
||||
if (!sharp) return res.status(503).json({ error: 'sharp недоступен на сервере' });
|
||||
const p = req.body.params || {};
|
||||
const brightness = clampEnhanceParam(p.brightness, 10, 300, 100);
|
||||
const contrast = clampEnhanceParam(p.contrast, 10, 300, 100);
|
||||
const saturate = clampEnhanceParam(p.saturate, 0, 300, 100);
|
||||
const sharpAmt = clampEnhanceParam(p.sharp, 0, 100, 0);
|
||||
const denoise = clampEnhanceParam(p.denoise, 0, 100, 0);
|
||||
const srcKey = storage.keyFromPath(oldPath);
|
||||
const srcPath = srcKey ? await storage.localize(srcKey) : null;
|
||||
if (!srcPath) return res.status(400).json({ error: 'Файл фото не найден' });
|
||||
let pipeline = sharp(srcPath).rotate();
|
||||
if (denoise > 0) pipeline = pipeline.median(denoise > 70 ? 5 : 3);
|
||||
pipeline = pipeline.modulate({ brightness: brightness / 100, saturation: saturate / 100 });
|
||||
if (contrast !== 100) {
|
||||
const a = contrast / 100;
|
||||
pipeline = pipeline.linear(a, 128 * (1 - a));
|
||||
}
|
||||
if (sharpAmt > 0) {
|
||||
pipeline = pipeline.sharpen({ sigma: 0.5 + (sharpAmt / 100) * 1.5, m1: 0, m2: 1 + sharpAmt / 50 });
|
||||
}
|
||||
const newName = crypto.randomBytes(12).toString('hex') + '.jpg';
|
||||
const outPath = path.join(UPLOADS_DIR, newName);
|
||||
await pipeline.jpeg({ quality: 92, mozjpeg: true }).toFile(outPath);
|
||||
await storage.persist(newName, outPath);
|
||||
newPath = `/uploads/${newName}`;
|
||||
engine = 'sharp';
|
||||
} else {
|
||||
if (!req.file) return res.status(400).json({ error: 'Нет файла' });
|
||||
await convertPhoto(req.file);
|
||||
newPath = `/uploads/${req.file.filename}`;
|
||||
}
|
||||
await swapGroupPhotoFiles(req, req.params.id, photoId, oldPath, newPath, { action: 'enhance' });
|
||||
res.json({ ok: true, photo_path: newPath, engine });
|
||||
} catch (e) {
|
||||
if (req.file) safeUnlink(req.file.path);
|
||||
console.error('PUT /api/groups/:id/photos/:photoId/enhance:', e);
|
||||
res.status(500).json({ error: 'Ошибка замены фото' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/groups/:id/photos/:photoId/jobs', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(photoId)) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
const { rows } = await pool.query(
|
||||
`SELECT j.id, j.action, j.status, j.applied, j.params, j.before_path, j.after_path, j.error, j.created_at, j.finished_at
|
||||
FROM photo_jobs j
|
||||
JOIN group_photos p ON p.id = j.group_photo_id
|
||||
WHERE j.group_photo_id = $1 AND p.group_id = $2
|
||||
ORDER BY j.id DESC LIMIT 50`,
|
||||
[photoId, req.params.id]
|
||||
);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/rollback', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
try {
|
||||
const jobId = parseInt(req.params.jobId, 10);
|
||||
const photoId = parseInt(req.params.photoId, 10);
|
||||
if (!Number.isFinite(jobId) || !Number.isFinite(photoId)) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
const { rows: jobRows } = await pool.query(
|
||||
`SELECT id, before_path FROM photo_jobs WHERE id = $1 AND group_photo_id = $2 AND status = 'done'`,
|
||||
[jobId, photoId]
|
||||
);
|
||||
if (!jobRows.length) return res.status(404).json({ error: 'Задание не найдено' });
|
||||
const job = jobRows[0];
|
||||
if (!job.before_path || !job.before_path.startsWith('/uploads/.originals/')) {
|
||||
return res.status(400).json({ error: 'Нет сохранённой версии для отката' });
|
||||
}
|
||||
const beforeName = path.basename(job.before_path);
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(beforeName)) return res.status(400).json({ error: 'Некорректный путь' });
|
||||
const beforeKey = `.originals/${beforeName}`;
|
||||
if (!(await storage.exists(beforeKey))) return res.status(400).json({ error: 'Файл версии не найден' });
|
||||
const { rows: cur } = await pool.query('SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, req.params.id]);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
const oldPath = cur[0].photo_path;
|
||||
if (!oldPath) return res.status(400).json({ error: 'У фото нет изображения' });
|
||||
const ext = path.extname(beforeName) || '.jpg';
|
||||
const newKey = `${crypto.randomBytes(12).toString('hex')}${ext}`;
|
||||
const newPath = `/uploads/${newKey}`;
|
||||
if (!(await storage.copyObject(beforeKey, newKey))) {
|
||||
return res.status(400).json({ error: 'Файл версии не найден' });
|
||||
}
|
||||
const oldKey = storage.keyFromPath(oldPath);
|
||||
let rollbackBefore = null;
|
||||
if (oldKey && (await storage.exists(oldKey))) {
|
||||
try {
|
||||
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
|
||||
if (await storage.copyObject(oldKey, backupKey)) {
|
||||
rollbackBefore = `/uploads/${backupKey}`;
|
||||
safeUnlink(oldKey);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('group photo rollback backup failed:', e);
|
||||
}
|
||||
}
|
||||
thumbUnlinkFor(oldPath);
|
||||
await pool.query('UPDATE group_photos SET photo_path = $1 WHERE id = $2 AND group_id = $3', [newPath, photoId, req.params.id]);
|
||||
await pool.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [newPath, req.params.id, oldPath]);
|
||||
await pool.query(
|
||||
'INSERT INTO photo_jobs (group_photo_id, action, status, before_path, after_path, finished_at) VALUES ($1, $2, $3, $4, $5, now())',
|
||||
[photoId, 'rollback', 'done', rollbackBefore, newPath]
|
||||
);
|
||||
await logAudit(req, 'group.photo.rollback', { group_id: req.params.id, photo_id: photoId, job_id: jobId, restored_path: newPath });
|
||||
invalidateShare();
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
res.json({ ok: true, photo_path: newPath });
|
||||
} catch (e) {
|
||||
console.error('POST /api/groups/:id/photos/:photoId/jobs/:jobId/rollback:', e);
|
||||
res.status(500).json({ error: 'Ошибка отката фотографии' });
|
||||
}
|
||||
});
|
||||
|
||||
// --- Modules (темы модулей) ---
|
||||
app.get('/api/modules', apiLimiter, async (req, res) => {
|
||||
const { limit, offset, search, active } = req.query;
|
||||
@@ -6321,7 +6686,7 @@ app.delete('/api/students/:id', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
||||
const gid = cur[0].group_id;
|
||||
if (gid && !(await groupBelongsToBranches(req.user, gid))) {
|
||||
if (!(await groupBelongsToBranches(req.user, gid))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
||||
}
|
||||
}
|
||||
@@ -6344,7 +6709,7 @@ app.put('/api/students/:id/restore', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
||||
const gid = cur[0].group_id;
|
||||
if (gid && !(await groupBelongsToBranches(req.user, gid))) {
|
||||
if (!(await groupBelongsToBranches(req.user, gid))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
||||
}
|
||||
}
|
||||
@@ -6367,7 +6732,7 @@ app.delete('/api/students/:id/permanent', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
||||
const gid = cur[0].group_id;
|
||||
if (gid && !(await groupBelongsToBranches(req.user, gid))) {
|
||||
if (!(await groupBelongsToBranches(req.user, gid))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
||||
}
|
||||
}
|
||||
@@ -6392,7 +6757,7 @@ app.put('/api/students/:id/unschedule', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
||||
const gid = cur[0].group_id;
|
||||
if (gid && !(await groupBelongsToBranches(req.user, gid))) {
|
||||
if (!(await groupBelongsToBranches(req.user, gid))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
||||
}
|
||||
}
|
||||
@@ -7445,7 +7810,7 @@ app.post('/api/files/:id/detach', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
const { entry_id, group_id } = rows[0];
|
||||
if (!entry_id || (group_id && !(await groupBelongsToBranches(req.user, group_id)))) {
|
||||
if (!entry_id || !(await groupBelongsToBranches(req.user, group_id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому файлу' });
|
||||
}
|
||||
}
|
||||
@@ -7467,7 +7832,7 @@ app.delete('/api/files/:id', requireAuth, async (req, res) => {
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
const { entry_id, group_id } = rows[0];
|
||||
if (!entry_id || (group_id && !(await groupBelongsToBranches(req.user, group_id)))) {
|
||||
if (!entry_id || !(await groupBelongsToBranches(req.user, group_id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому файлу' });
|
||||
}
|
||||
}
|
||||
@@ -8163,6 +8528,40 @@ async function swapEntryPhotoFiles(req, entryId, oldPath, newPath, { keepOrigina
|
||||
invalidateEntries();
|
||||
}
|
||||
|
||||
async function swapGroupPhotoFiles(req, groupId, photoId, oldPath, newPath, { keepOriginal = true, action = 'enhance' } = {}) {
|
||||
let originalPath = null;
|
||||
const { rows: prevRows } = await pool.query('SELECT photo_original_path FROM group_photos WHERE id = $1 AND group_id = $2', [photoId, groupId]);
|
||||
const prevOriginal = prevRows.length ? prevRows[0].photo_original_path : null;
|
||||
const oldKey = storage.keyFromPath(oldPath);
|
||||
if (prevOriginal) {
|
||||
originalPath = prevOriginal;
|
||||
if (oldKey) safeUnlink(oldKey);
|
||||
} else if (keepOriginal && oldKey && (await storage.exists(oldKey))) {
|
||||
try {
|
||||
const backupKey = `.originals/${crypto.randomBytes(12).toString('hex')}${path.extname(oldKey) || '.jpg'}`;
|
||||
if (await storage.copyObject(oldKey, backupKey)) {
|
||||
originalPath = `/uploads/${backupKey}`;
|
||||
safeUnlink(oldKey);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('photo original backup failed:', e);
|
||||
}
|
||||
} else if (oldKey) {
|
||||
safeUnlink(oldKey);
|
||||
}
|
||||
await pool.query('UPDATE group_photos SET photo_path = $1, photo_original_path = $2 WHERE id = $3 AND group_id = $4', [newPath, originalPath, photoId, groupId]);
|
||||
await pool.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [newPath, groupId, oldPath]);
|
||||
thumbUnlinkFor(oldPath);
|
||||
await pool.query(
|
||||
'INSERT INTO photo_jobs (group_photo_id, action, status, before_path, after_path, finished_at) VALUES ($1, $2, $3, $4, $5, now())',
|
||||
[photoId, action, 'done', originalPath, newPath]
|
||||
);
|
||||
await logAudit(req, 'group.photo.enhance', { group_id: groupId, photo_id: photoId, old_path: oldPath, new_path: newPath, original_path: originalPath });
|
||||
invalidateShare();
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
}
|
||||
|
||||
app.put('/api/entries/:id/photo/enhance', requireAuth, (req, res, next) => {
|
||||
if (req.is('json')) return next();
|
||||
upload.single('photo')(req, res, next);
|
||||
@@ -8578,7 +8977,7 @@ app.delete('/api/entries/:id', requireAuth, async (req, res) => {
|
||||
if (!acc.found) return res.status(404).json({ error: 'Not found' });
|
||||
if (!acc.allowed) return res.status(403).json({ error: 'Нет доступа к этой записи' });
|
||||
}
|
||||
await pool.query('UPDATE entries SET deleted_at = now() WHERE id = $1', [req.params.id]);
|
||||
await pool.query('UPDATE entries SET deleted_at = now(), purge_at = NULL WHERE id = $1 AND deleted_at IS NULL', [req.params.id]);
|
||||
await logAudit(req, 'entry.soft-delete', { id: req.params.id });
|
||||
invalidateEntries();
|
||||
invalidateStats();
|
||||
@@ -8590,12 +8989,10 @@ app.put('/api/entries/:id/restore', requireAuth, async (req, res) => {
|
||||
const acc = await entryAccessible(req.user, req.params.id);
|
||||
if (!acc.found) return res.status(404).json({ error: 'Not found' });
|
||||
if (!acc.allowed) {
|
||||
console.warn(`[RESTORE DENIED] User ${req.user.id} (${req.user.username}) role=${req.user.role} branches=${JSON.stringify(req.user.branch_ids)} tried to restore entry ${req.params.id} (group_id=${acc.group_id})`);
|
||||
return res.status(403).json({ error: 'Нет доступа к этой записи' });
|
||||
}
|
||||
}
|
||||
const result = await pool.query('UPDATE entries SET deleted_at = NULL, purge_at = NULL WHERE id = $1', [req.params.id]);
|
||||
console.log(`[RESTORE] User ${req.user.id} (${req.user.username}) restored entry ${req.params.id}, rowCount=${result.rowCount}`);
|
||||
const result = await pool.query('UPDATE entries SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND deleted_at IS NOT NULL', [req.params.id]);
|
||||
if (result.rowCount === 0) {
|
||||
return res.status(404).json({ error: 'Запись не найдена или уже восстановлена' });
|
||||
}
|
||||
@@ -8610,7 +9007,6 @@ app.delete('/api/entries/:id/permanent', requireAuth, async (req, res) => {
|
||||
const acc = await entryAccessible(req.user, req.params.id);
|
||||
if (!acc.found) return res.status(404).json({ error: 'Not found' });
|
||||
if (!acc.allowed) {
|
||||
console.warn(`[PERM DELETE DENIED] User ${req.user.id} (${req.user.username}) role=${req.user.role} branches=${JSON.stringify(req.user.branch_ids)} tried to perm delete entry ${req.params.id} (group_id=${acc.group_id})`);
|
||||
return res.status(403).json({ error: 'Нет доступа к этой записи' });
|
||||
}
|
||||
}
|
||||
@@ -9140,7 +9536,7 @@ async function trashData(req, mode, limit, offset) {
|
||||
const stparams = [];
|
||||
const stscoped = req.user.role !== 'admin';
|
||||
const gsco2 = stscoped
|
||||
? (bw.ids.length ? ` AND s.group_id IN (${bw.ids.map(id => `$${stparams.push(id)})`).join(',')}` : ' AND 1 = 0')
|
||||
? (bw.ids.length ? ` AND s.group_id IN (SELECT g.id FROM groups g WHERE g.branch_id = ANY($${stparams.push(bw.ids)}))` : ' AND 1 = 0')
|
||||
: '';
|
||||
const stOrder = isPending ? 's.purge_at' : 's.deleted_at';
|
||||
const { rows: stcount } = await pool.query(`SELECT count(*)::int AS n FROM students s${stWhere}${gsco2}`, stparams);
|
||||
@@ -9149,15 +9545,26 @@ async function trashData(req, mode, limit, offset) {
|
||||
}
|
||||
|
||||
app.get('/api/trash', requireAuth, async (req, res) => {
|
||||
const limit = parseInt(req.query.limit, 10);
|
||||
const offset = parseInt(req.query.offset, 10);
|
||||
res.json(await trashData(req, 'visible', limit, offset));
|
||||
try {
|
||||
const limit = parseInt(req.query.limit, 10);
|
||||
const offset = parseInt(req.query.offset, 10);
|
||||
const data = await trashData(req, 'visible', isNaN(limit) ? 100 : limit, isNaN(offset) ? 0 : offset);
|
||||
res.json(data);
|
||||
} catch (err) {
|
||||
console.error('GET /api/trash error:', err.message);
|
||||
res.status(500).json({ error: 'Ошибка загрузки корзины' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/trash/pending', requireAuth, async (req, res) => {
|
||||
const data = await trashData(req, 'pending');
|
||||
data.purge_days = await trashPurgeDays();
|
||||
res.json(data);
|
||||
try {
|
||||
const data = await trashData(req, 'pending');
|
||||
data.purge_days = await trashPurgeDays();
|
||||
res.json(data);
|
||||
} catch (err) {
|
||||
console.error('GET /api/trash/pending error:', err.message);
|
||||
res.status(500).json({ error: 'Ошибка загрузки корзины' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/trash', requireAuth, requireAdmin, async (req, res) => {
|
||||
|
||||
Reference in New Issue
Block a user