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

- 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
+3
View File
@@ -733,6 +733,9 @@ INSERT INTO settings (key, value) VALUES ('notify_face_scan_done', 'false') ON C
INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_chat_message', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_photo_broken_link', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('faces_broken_scan_enabled', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('faces_broken_scan_interval_hours', '6') ON CONFLICT (key) DO NOTHING;
CREATE TABLE IF NOT EXISTS achievement_types (
id SERIAL PRIMARY KEY,
+3
View File
@@ -919,6 +919,9 @@ INSERT INTO settings (key, value) VALUES ('notify_face_scan_done', 'false') ON C
INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_chat_message', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('notify_photo_broken_link', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('faces_broken_scan_enabled', 'true') ON CONFLICT (key) DO NOTHING;
INSERT INTO settings (key, value) VALUES ('faces_broken_scan_interval_hours', '6') ON CONFLICT (key) DO NOTHING;
CREATE TABLE IF NOT EXISTS broken_images (
id SERIAL PRIMARY KEY,
+45
View File
@@ -42,6 +42,49 @@ async function findBrokenFaceRefs(pool, storage, { studentId, limit } = {}) {
return results;
}
async function scanAllBrokenFaceRefs(pool, storage, { limit } = {}) {
const results = [];
for (const table of FACE_REF_TABLES) {
let sql;
const params = [];
if (table === 'student_face_refs') {
sql = `SELECT id, photo_path, student_id FROM student_face_refs WHERE photo_path IS NOT NULL AND photo_path <> ''`;
} else {
sql = `SELECT id, photo_path, student_id FROM photo_faces WHERE photo_path IS NOT NULL AND photo_path <> ''`;
}
sql += ` ORDER BY id`;
if (limit) {
sql += ` LIMIT $${params.length + 1}`;
params.push(limit);
}
const { rows } = await pool.query(sql, params);
for (const row of rows) {
const key = storage.keyFromPath(row.photo_path);
if (!key) continue;
const exists = await storage.exists(key);
if (!exists) {
results.push({ table, id: row.id, photo_path: row.photo_path, student_id: row.student_id });
}
}
}
return results;
}
async function cleanupAllBrokenFaceRefs(pool, storage, { limit } = {}) {
const broken = await scanAllBrokenFaceRefs(pool, storage, { limit });
let deleted = 0;
const errors = [];
for (const item of broken) {
try {
await deleteFaceRef(pool, storage, { table: item.table, id: item.id });
deleted++;
} catch (e) {
errors.push({ table: item.table, id: item.id, error: e.message });
}
}
return { broken, deleted, total: broken.length, errors };
}
async function deleteFaceRef(pool, storage, { table, id }) {
if (!isFaceTable(table)) {
throw new Error('Недопустимая таблица');
@@ -55,6 +98,8 @@ async function deleteFaceRef(pool, storage, { table, id }) {
module.exports = {
findBrokenFaceRefs,
scanAllBrokenFaceRefs,
cleanupAllBrokenFaceRefs,
deleteFaceRef,
FACE_REF_TABLES,
};
+67 -2
View File
@@ -1,6 +1,6 @@
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey'];
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey', 'facesBrokenScanEnabled', 'facesBrokenScanInterval'];
const NOTIFY_IDS = [];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans'];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans', 'sec-face-broken'];
const SPAM_MAX = 10080;
const BAN_REASONS = {
'honeypot': 'Антиспам-поле',
@@ -332,6 +332,10 @@ async function loadSettings() {
document.getElementById('camEnabled').checked = s.camera_enabled !== 'false';
document.getElementById('imgbbUrl').value = s.feedback_imgbb_url || '';
document.getElementById('imgbbKey').value = s.feedback_imgbb_key || '';
const fbe = document.getElementById('facesBrokenScanEnabled');
const fbi = document.getElementById('facesBrokenScanInterval');
if (fbe) fbe.checked = s.faces_broken_scan_enabled !== 'false';
if (fbi) fbi.value = s.faces_broken_scan_interval || '6';
await renderNotifyTypes(s);
snapshotDirty();
updateSpamUi();
@@ -340,6 +344,7 @@ async function loadSettings() {
renderStats(stRes);
loadSystemInfo();
loadPhotoAiStatus();
loadFaceBrokenStatus();
}
async function renderStats(res) {
@@ -908,6 +913,12 @@ async function saveSettings() {
showError('Проверьте поле «Хранение уведомлений» (от 1 до 365 дней)');
return;
}
const fbInterval = document.getElementById('facesBrokenScanInterval').value;
const fbIntervalHours = Math.round(Number(fbInterval));
if (fbInterval === '' || !Number.isFinite(fbIntervalHours) || fbIntervalHours < 1 || fbIntervalHours > 168) {
showError('Проверьте поле «Интервал проверки битых ссылок» (от 1 до 168 часов)');
return;
}
const btn = document.getElementById('saveBtn');
btn.dataset.loadingText = 'Сохранение...';
setBtnLoading(btn, true);
@@ -943,6 +954,8 @@ async function saveSettings() {
photo_ai_device_pref: document.getElementById('photoAiDevicePref').value,
camera_enabled: document.getElementById('camEnabled').checked ? 'true' : 'false',
trash_purge_days: String(trashDays),
faces_broken_scan_enabled: (document.getElementById('facesBrokenScanEnabled') || {}).checked ? 'true' : 'false',
faces_broken_scan_interval: String((document.getElementById('facesBrokenScanInterval') || {}).value || '6'),
feedback_imgbb_url: document.getElementById('imgbbUrl').value.trim(),
feedback_imgbb_key: document.getElementById('imgbbKey').value.trim(),
...notifySettingsPayload(notifyRetentionDays),
@@ -1439,6 +1452,58 @@ if (faceRematchBtn) faceRematchBtn.addEventListener('click', async () => {
}
});
const faceBrokenScanBtn = document.getElementById('faceBrokenScanBtn');
const faceBrokenCleanupBtn = document.getElementById('faceBrokenCleanupBtn');
const faceBrokenStatus = document.getElementById('faceBrokenStatus');
const faceBrokenHint = document.getElementById('faceBrokenHint');
async function loadFaceBrokenStatus() {
if (!faceBrokenStatus) return;
faceBrokenStatus.textContent = 'Проверка: загрузка...';
try {
const res = await fetch(`${API}/api/faces/broken/all?limit=200`, { headers: hdr() });
if (!res.ok) throw new Error('load failed');
const d = await res.json();
faceBrokenStatus.textContent = `Битых ссылок: ${d.total || 0}`;
if (faceBrokenHint) faceBrokenHint.textContent = `Битые ссылки можно также удалять по одной на странице ученика во вкладке «Лица»`;
} catch {
faceBrokenStatus.textContent = 'Проверка: ошибка загрузки';
}
}
if (faceBrokenScanBtn) faceBrokenScanBtn.addEventListener('click', async () => {
faceBrokenScanBtn.disabled = true;
if (faceBrokenStatus) faceBrokenStatus.textContent = 'Проверка: сканирую...';
try {
const res = await fetch(`${API}/api/faces/broken/scan`, { method: 'POST', headers: hdr() });
const d = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(d.error || 'scan failed');
showToast(`Проверка завершена: битых ссылок ${d.broken || 0}`);
loadFaceBrokenStatus();
} catch {
showError('Не удалось запустить проверку битых ссылок');
} finally {
faceBrokenScanBtn.disabled = false;
}
});
if (faceBrokenCleanupBtn) faceBrokenCleanupBtn.addEventListener('click', async () => {
if (!confirm('Удалить все битые ссылки на фото лиц (эталоны и найденные лица) из базы? Файлы уже удалены, ссылки остаются мёртвыми.')) return;
faceBrokenCleanupBtn.disabled = true;
if (faceBrokenStatus) faceBrokenStatus.textContent = 'Очистка...';
try {
const res = await fetch(`${API}/api/faces/broken/cleanup-all`, { method: 'POST', headers: hdrJson() });
const d = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(d.error || 'cleanup failed');
showToast(`Удалено битых ссылок: ${d.deleted || 0} из ${d.total || 0}`);
loadFaceBrokenStatus();
} catch {
showError('Не удалось удалить битые ссылки');
} finally {
faceBrokenCleanupBtn.disabled = false;
}
});
const faceQueueHint = document.getElementById('faceQueueHint');
const faceQueueRetryBtn = document.getElementById('faceQueueRetryBtn');
const faceQueueRefreshBtn = document.getElementById('faceQueueRefreshBtn');
+27
View File
@@ -302,6 +302,33 @@
</div>
</div>
<div class="settings-card" id="sec-face-broken">
<div class="card-head">
<div class="ic"><i data-lucide="image-off"></i></div>
<h3>Мониторинг битых ссылок на фото лиц</h3>
</div>
<p class="hint">Фоновая проверка ищет ссылки на фото лиц (эталоны и найденные лица на фото групп/записей), файлы которых удалены с диска или из хранилища. Битые ссылки не приносят пользы, но занимают место в базе. При обнаружении приходит уведомление администратору.</p>
<label class="toggle">
<input type="checkbox" id="facesBrokenScanEnabled">
<span class="toggle-track"><span class="toggle-thumb"></span></span>
<span class="toggle-text"><b>Фоновая проверка битых ссылок</b><small>Раз в 6 часов сканирует все ссылки на фото лиц и уведомляет админа, если файлы пропали</small></span>
</label>
<div class="settings-field">
<label for="facesBrokenScanInterval">Интервал проверки (часы)</label>
<input type="number" id="facesBrokenScanInterval" class="settings-input" min="1" max="168" value="6">
<span class="hint">Минимум 1 час, максимум 7 дней (168 ч)</span>
</div>
<div class="settings-field">
<label>Состояние</label>
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
<span class="hint" id="faceBrokenStatus">Проверка: загрузка...</span>
<button type="button" class="btn-primary ghost" id="faceBrokenScanBtn"><i data-lucide="scan"></i> Проверить сейчас</button>
<button type="button" class="btn-danger ghost" id="faceBrokenCleanupBtn"><i data-lucide="trash-2"></i> Удалить все битые ссылки</button>
</div>
<span class="hint" id="faceBrokenHint">Битые ссылки можно также удалять по одной на странице ученика во вкладке «Лица»</span>
</div>
</div>
<div class="settings-card" id="sec-achievements">
<div class="card-head">
<div class="ic"><i data-lucide="trophy"></i></div>
+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');