diff --git a/db/init.sql b/db/init.sql index 9b00ba7..34af077 100644 --- a/db/init.sql +++ b/db/init.sql @@ -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, diff --git a/db/migration.sql b/db/migration.sql index de64719..4256135 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -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, diff --git a/lib/photo-cleanup.js b/lib/photo-cleanup.js index 891ab04..1b4ef73 100644 --- a/lib/photo-cleanup.js +++ b/lib/photo-cleanup.js @@ -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, }; diff --git a/public/js/settings.js b/public/js/settings.js index 7c10f75..d0e0184 100644 --- a/public/js/settings.js +++ b/public/js/settings.js @@ -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'); diff --git a/public/settings.html b/public/settings.html index 3c5d00a..7048132 100644 --- a/public/settings.html +++ b/public/settings.html @@ -302,6 +302,33 @@ +
Фоновая проверка ищет ссылки на фото лиц (эталоны и найденные лица на фото групп/записей), файлы которых удалены с диска или из хранилища. Битые ссылки не приносят пользы, но занимают место в базе. При обнаружении приходит уведомление администратору.
+ +