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

- 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
+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');