Фоновый мониторинг битых ссылок на фото лиц с уведомлениями админа

- lib/photo-cleanup.js: scanAllBrokenFaceRefs / cleanupAllBrokenFaceRefs
  сканируют student_face_refs и photo_faces на отсутствующие файлы
- server.js: тип уведомления photo.broken_link, настройки
  faces_broken_scan_enabled / faces_broken_scan_interval_hours,
  фоновый таймер (раз в 6 часов), админ-роуты
  GET /api/faces/broken/all, POST /api/faces/broken/scan,
  POST /api/faces/broken/cleanup-all
- public/settings.html + public/js/settings.js: карточка
  мониторинга в настройках (вкл/выкл, интервал, проверить сейчас,
  удалить все, статус)
- public/js/student.js: битые ссылки во вкладке «Лица» ученика с
  удалением по одной и пакетной очисткой для админа
- db/init.sql + db/migration.sql: сиды новых настроек
This commit is contained in:
dev
2026-11-05 17:20:45 +03:00
parent cdb364b34b
commit 2c8a6a29dd
6 changed files with 249 additions and 3 deletions
+104 -1
View File
@@ -67,7 +67,7 @@ const { lessonReportWriteBlocked } = require('./lib/lesson-reports');
const { groupOwnedBy } = require('./lib/groups');
const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
const { resolveImgbbEndpoint, friendlyApiError } = require('./lib/feedback-imgbb');
const { findBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup');
const { findBrokenFaceRefs, scanAllBrokenFaceRefs, cleanupAllBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup');
const {
ensureDocsTables,
docsTree,
@@ -368,6 +368,7 @@ const NOTIFY_TYPES = {
'face.scan.done': { label: 'Найдены лица на фото', hint: 'Фоновая проверка нашла лица на загруженном фото. Сколько именно — в тексте уведомления', icon: 'scan-face', level: 'info', enabled: false, admin: false },
'face.recognized': { label: 'Ученики распознаны на фото', hint: 'Фоновая проверка сопоставила лица с эталонами и назвала учеников', icon: 'user-round-check', level: 'info', enabled: true, admin: false },
'face.scan.error': { label: 'Ошибка проверки лиц', hint: 'Сервис face-id недоступен или очередь проверки исчерпала попытки', icon: 'scan-search', level: 'warning', enabled: true, admin: false },
'photo.broken_link': { label: 'Битые ссылки на фото лиц', hint: 'В базе остались ссылки на фото, файлы которых удалены. Требуется очистка ссылок', icon: 'image-off', level: 'warning', enabled: true, admin: true },
'chat.message': { label: 'Новое сообщение в чате', hint: 'Тьютор написал в личный чат администрации', icon: 'bell', level: 'info', enabled: true, admin: true },
'digest.published': { label: 'Новый дайджест', hint: 'Опубликован новый дайджест с важными сообщениями', icon: 'newspaper', level: 'info', enabled: true, admin: false },
};
@@ -11861,6 +11862,64 @@ app.post('/api/faces/cleanup', requireAuth, requireAdmin, async (req, res) => {
res.json({ deleted, total: broken.length, errors });
});
app.get('/api/faces/broken/all', requireAuth, requireAdmin, async (req, res) => {
const limit = Math.min(5000, Math.max(1, safeId(req.query.limit) || 500));
const broken = await scanAllBrokenFaceRefs(pool, storage, { limit });
const studentIds = broken.map(b => b.student_id).filter(Boolean);
let names = {};
if (studentIds.length) {
const { rows } = await pool.query('SELECT id, name FROM students WHERE id = ANY($1::int[])', [studentIds]);
for (const r of rows) names[r.id] = r.name;
}
res.json({
broken: broken.map(b => ({ ...b, student_name: names[b.student_id] || null })),
total: broken.length,
});
});
app.post('/api/faces/broken/scan', requireAuth, requireAdmin, async (req, res) => {
const broken = await scanAllBrokenFaceRefs(pool, storage, { limit: 5000 });
let notified = false;
if (broken.length > 0) {
const byStudent = {};
for (const item of broken) {
const sid = item.student_id || 0;
if (!byStudent[sid]) byStudent[sid] = [];
byStudent[sid].push(item);
}
const studentIds = Object.keys(byStudent).map(Number).filter(Boolean);
let studentNames = {};
if (studentIds.length) {
const { rows } = await pool.query('SELECT id, name FROM students WHERE id = ANY($1::int[])', [studentIds]);
for (const r of rows) studentNames[r.id] = r.name;
}
const details = [];
let total = 0;
for (const sid of studentIds) {
const items = byStudent[sid] || [];
total += items.length;
details.push(`"${studentNames[sid] || 'удалённый ученик'} (#${sid})": ${items.length} ссыл(ок/а)`);
}
await pushNotification({
type: 'photo.broken_link',
title: 'Битые ссылки на фото лиц',
body: `Проверка вручную: найдено битых ссылок ${total}. ${details.slice(0, 5).join('; ')}${details.length > 5 ? ` и ещё ${details.length - 5}` : ''}.`,
level: 'warning',
adminOnly: true,
});
notified = true;
}
await logAudit(req, 'faces.broken_link.scan_manual', { broken: broken.length, notified });
res.json({ broken: broken.length, notified });
});
app.post('/api/faces/broken/cleanup-all', requireAuth, requireAdmin, async (req, res) => {
const limit = Math.min(10000, Math.max(1, safeId(req.body.limit) || 1000));
const result = await cleanupAllBrokenFaceRefs(pool, storage, { limit });
await logAudit(req, 'faces.broken_link.cleanup_all', { deleted: result.deleted, total: result.total, errors: result.errors.length });
res.json(result);
});
app.post('/api/faces/scan-unscanned', requireAuth, requireAdmin, async (req, res) => {
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
const limit = Math.min(500, Math.max(1, safeId(req.body.limit) || 50));
@@ -15147,6 +15206,8 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
setInterval(() => { purgeOldChat().catch(err => console.error('Chat purge:', err)); }, 24 * 60 * 60 * 1000).unref();
try { await pool.query(`INSERT INTO settings (key, value) VALUES ('camera_enabled', 'true') ON CONFLICT (key) DO NOTHING`); } catch (err) { console.error('Camera setting:', err); }
try { await pool.query(`INSERT INTO settings (key, value) VALUES ('trash_purge_days', '30') ON CONFLICT (key) DO NOTHING`); } catch (err) { console.error('Trash purge days setting:', err); }
try { await pool.query(`INSERT INTO settings (key, value) VALUES ('faces_broken_scan_enabled', 'true') ON CONFLICT (key) DO NOTHING`); } catch (err) { console.error('Faces broken scan setting:', err); }
try { await pool.query(`INSERT INTO settings (key, value) VALUES ('faces_broken_scan_interval_hours', '6') ON CONFLICT (key) DO NOTHING`); } catch (err) { console.error('Faces broken scan interval setting:', err); }
try { await sweepOrphanedUploads(); } catch (err) { console.error('Upload sweep:', err); }
if (storage.isRemote()) {
try {
@@ -15162,6 +15223,48 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
setInterval(() => {
try { storage.pruneCache(); } catch (err) { console.error('Cache prune:', err); }
}, 60 * 60 * 1000).unref();
async function scanBrokenFaceLinks() {
try {
const enabled = await getSetting('faces_broken_scan_enabled');
if (enabled !== 'true') return;
const broken = await scanAllBrokenFaceRefs(pool, storage, { limit: 2000 });
if (broken.length > 0) {
const byStudent = {};
for (const item of broken) {
const sid = item.student_id || 0;
if (!byStudent[sid]) byStudent[sid] = [];
byStudent[sid].push(item);
}
const studentIds = Object.keys(byStudent).map(Number).filter(Boolean);
let studentNames = {};
if (studentIds.length) {
const { rows } = await pool.query('SELECT id, name FROM students WHERE id = ANY($1::int[])', [studentIds]);
for (const r of rows) studentNames[r.id] = r.name;
}
let total = 0;
const details = [];
for (const sid of studentIds) {
const items = byStudent[sid] || [];
total += items.length;
details.push(`"${studentNames[sid] || 'удалённый ученик'} (#${sid})": ${items.length} ссыл(ок/а)`);
}
await pushNotification({
type: 'photo.broken_link',
title: 'Битые ссылки на фото лиц',
body: `Найдено битых ссылок: ${total}. ${details.slice(0, 5).join('; ')}${details.length > 5 ? ` и ещё ${details.length - 5}` : ''}.`,
level: 'warning',
adminOnly: true,
});
await logAudit({ ip: 'system', user: { id: null } }, 'faces.broken_link.scan', { broken: total, students: Object.keys(byStudent).length });
}
} catch (err) {
console.error('Broken face links scan:', err.message);
}
}
try { await scanBrokenFaceLinks(); } catch (err) { console.error('Initial broken face links scan:', err.message); }
setInterval(() => { scanBrokenFaceLinks().catch(err => console.error('Broken face links scan:', err.message)); }, 6 * 60 * 60 * 1000).unref();
entryAutoChecker = createEntryAutoChecker({ pool, getSetting, logAudit, aiUrl: AI_URL, defaultPrompt: AI_DEFAULT_PROMPT, bus: createWorkerBus(AI_WAKE_CHANNEL) });
entryAutoChecker.start();
console.log('AI auto-check worker started');