414 lines
18 KiB
JavaScript
414 lines
18 KiB
JavaScript
const PAGE_SIZE = 28;
|
||
let page = 1;
|
||
let totalPhotos = 0;
|
||
let currentPhotos = [];
|
||
let groupsLoaded = false;
|
||
let studentsLoaded = false;
|
||
let sourcesLoaded = false;
|
||
let searchTimer = null;
|
||
|
||
const FACE_CANDIDATE_MIN = 0.5;
|
||
let faceViewer = { sourceType: 'group', photoId: null, photoPath: '', faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||
let faceAssignFaceId = null;
|
||
let allStudents = [];
|
||
let allStudentsLoaded = false;
|
||
let faceScanLiveSource = null;
|
||
|
||
function humanSize(b) {
|
||
if (!b) return '';
|
||
if (b < 1024) return b + ' Б';
|
||
if (b < 1048576) return (b / 1024).toFixed(1) + ' КБ';
|
||
return (b / 1048576).toFixed(1) + ' МБ';
|
||
}
|
||
|
||
function photoLink(p) {
|
||
if (p.source_type === 'entry') return `journal.html#entry-${p.source_id}`;
|
||
if (p.source_type === 'entry_photo') return `journal.html#entry-${p.source_id}`;
|
||
if (p.source_type === 'group_photo') return 'groups.html';
|
||
if (p.source_type === 'student_photo') return 'students.html';
|
||
if (p.source_type === 'module_photo') return 'modules.html';
|
||
return '';
|
||
}
|
||
|
||
function photoThumb(p) {
|
||
if (typeof p === 'string' && p.startsWith('/uploads/.originals/')) return `${API}${p}`;
|
||
if (typeof p === 'string' && p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`;
|
||
return thumbSrc(p);
|
||
}
|
||
|
||
function photoCardHTML(p) {
|
||
const url = p.path;
|
||
const meta = [];
|
||
if (p.student_name) meta.push(esc(p.student_name));
|
||
if (p.group_name) meta.push(esc(p.group_name));
|
||
const link = photoLink(p);
|
||
const canFix = isAdmin() && p.photo_key && p.photo_id != null;
|
||
const canFaces = !!(p.face_source_type && p.face_photo_id != null);
|
||
return `
|
||
<div class="ph-card">
|
||
<img src="${esc(photoThumb(url))}" data-img="${esc(url)}" loading="lazy" decoding="async" alt="" onerror="photoImgError(this)">
|
||
${canFaces ? `<button type="button" class="btn-link ph-faces-btn" data-fv-source="${esc(p.face_source_type)}" data-fv-id="${esc(p.face_photo_id)}" data-fv-path="${esc(url)}" title="Распознанные лица"><i data-lucide="scan-face"></i></button>` : ''}
|
||
<div class="ph-body">
|
||
<span class="ph-badge">${esc(p.source_label)}</span>
|
||
<div class="ph-title">${esc(p.title || 'Без описания')}</div>
|
||
${meta.length ? `<div class="ph-meta">${meta.join(' · ')}</div>` : ''}
|
||
<div class="ph-time">${fmtFull(p.created_at)}</div>
|
||
<span class="ph-broken-tag" hidden>Файл не найден</span>
|
||
${canFix ? `<button type="button" class="btn-link danger ph-broken-btn" data-quarantine="${esc(p.photo_key)}" data-quarantine-id="${esc(p.photo_id)}" hidden>В корзину</button>` : ''}
|
||
${link ? `<a class="ph-link" href="${link}">Открыть источник →</a>` : ''}
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function renderGrid() {
|
||
const grid = document.getElementById('grid');
|
||
if (!currentPhotos.length) {
|
||
grid.innerHTML = '<div class="empty" style="grid-column:1/-1">Фотографий не найдено</div>';
|
||
return;
|
||
}
|
||
grid.innerHTML = currentPhotos.map(photoCardHTML).join('');
|
||
}
|
||
|
||
async function loadGroupOptions() {
|
||
if (groupsLoaded) return;
|
||
const sel = document.getElementById('groupFilter');
|
||
while (sel.options.length > 1) sel.remove(1);
|
||
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
|
||
const groups = await res.json();
|
||
groups.forEach(g => {
|
||
const o = document.createElement('option');
|
||
o.value = g.id; o.textContent = g.name;
|
||
sel.appendChild(o);
|
||
});
|
||
groupsLoaded = true;
|
||
}
|
||
|
||
async function loadStudentOptions() {
|
||
if (studentsLoaded) return;
|
||
const dl = document.getElementById('studentFilterList');
|
||
const fs = document.getElementById('faceStudentFilter');
|
||
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
|
||
const names = await res.json();
|
||
dl.innerHTML = names.map(n => `<option value="${esc(n)}">`).join('');
|
||
if (fs) {
|
||
try {
|
||
const r2 = await fetch(`${API}/api/students?limit=1000`, { headers: hdr() });
|
||
const data = r2.ok ? await r2.json() : null;
|
||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||
list.filter(s => !s.deleted_at).forEach(s => {
|
||
const o = document.createElement('option');
|
||
o.value = String(s.id);
|
||
o.textContent = s.name;
|
||
fs.appendChild(o);
|
||
});
|
||
} catch {}
|
||
}
|
||
studentsLoaded = true;
|
||
}
|
||
|
||
function fillSourceOptions() {
|
||
if (sourcesLoaded) return;
|
||
const sel = document.getElementById('sourceFilter');
|
||
const labels = [];
|
||
currentPhotos.forEach(p => { if (!labels.includes(p.source_label)) labels.push(p.source_label); });
|
||
const known = ['Главное фото записи', 'Фото записи', 'Фотохроника группы', 'Фото ученика', 'Тема модуля'];
|
||
known.concat(labels.filter(l => !known.includes(l))).forEach(label => {
|
||
const o = document.createElement('option');
|
||
o.value = label; o.textContent = label;
|
||
sel.appendChild(o);
|
||
});
|
||
sourcesLoaded = true;
|
||
}
|
||
|
||
async function loadPhotos() {
|
||
const p = new URLSearchParams();
|
||
const q = document.getElementById('searchInput').value;
|
||
const sn = document.getElementById('studentFilter').value;
|
||
const gid = document.getElementById('groupFilter').value;
|
||
const df = document.getElementById('dateFrom').value;
|
||
const dt = document.getElementById('dateTo').value;
|
||
if (q) p.set('search', q);
|
||
if (sn) p.set('student_name', sn);
|
||
if (gid) p.set('group_id', gid);
|
||
if (df) p.set('date_from', df);
|
||
if (dt) p.set('date_to', dt);
|
||
const fv = document.getElementById('faceStudentFilter') ? document.getElementById('faceStudentFilter').value : '';
|
||
if (fv === '__unassigned__') p.set('unassigned_faces', '1');
|
||
else if (fv) p.set('student_id', fv);
|
||
p.set('limit', PAGE_SIZE);
|
||
p.set('offset', (page - 1) * PAGE_SIZE);
|
||
const res = await fetch(`${API}/api/photos?${p}`, { headers: hdr() });
|
||
if (!res.ok) {
|
||
document.getElementById('grid').innerHTML = '<div class="empty" style="grid-column:1/-1">Не удалось загрузить фотографии</div>';
|
||
return;
|
||
}
|
||
const data = await res.json();
|
||
const srcFilter = document.getElementById('sourceFilter').value;
|
||
currentPhotos = srcFilter ? data.photos.filter(x => x.source_label === srcFilter) : data.photos;
|
||
totalPhotos = srcFilter ? currentPhotos.length : data.total;
|
||
fillSourceOptions();
|
||
renderGrid();
|
||
if (typeof renderIcons === 'function') renderIcons();
|
||
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalPhotos / PAGE_SIZE)), goPage);
|
||
}
|
||
|
||
function goPage(p) {
|
||
page = p;
|
||
loadPhotos();
|
||
}
|
||
|
||
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
|
||
|
||
async function loadFaceViewerFaces(sourceType, photoId) {
|
||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces`, { headers: hdr() });
|
||
if (!res.ok) throw new Error('faces');
|
||
const data = await res.json();
|
||
faceViewer.faces = data.faces || [];
|
||
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
|
||
faceViewer.imgWidth = Number(data.img_width) || 0;
|
||
faceViewer.imgHeight = Number(data.img_height) || 0;
|
||
faceViewer.scanned = Boolean(data.scanned);
|
||
return faceViewer;
|
||
}
|
||
|
||
function faceViewerWarn(msg) {
|
||
const el = document.getElementById('faceViewerWarn');
|
||
if (!el) return;
|
||
if (msg) { el.textContent = msg; el.hidden = false; }
|
||
else { el.textContent = ''; el.hidden = true; }
|
||
}
|
||
|
||
function checkFaceViewerSync(nw, nh) {
|
||
if (!faceViewer.imgWidth || !faceViewer.imgHeight) return;
|
||
if (faceViewer.imgWidth === nw && faceViewer.imgHeight === nh) { faceViewerWarn(''); return; }
|
||
faceViewerWarn(`Рамки рассчитаны для ${faceViewer.imgWidth}×${faceViewer.imgHeight}px, а текущее фото ${nw}×${nh}px. Нажмите «Переиндексировать», чтобы пересчитать.`);
|
||
}
|
||
|
||
function faceBoxesHTML(nw, nh) {
|
||
return faceViewer.faces.map(f => {
|
||
const left = (f.x / nw) * 100;
|
||
const top = (f.y / nh) * 100;
|
||
const width = (f.w / nw) * 100;
|
||
const height = (f.h / nh) * 100;
|
||
let cls = 'face-box--unassigned';
|
||
let label = 'Не опознано';
|
||
if (f.student_id) {
|
||
cls = 'face-box--matched';
|
||
label = f.manual ? `${esc(f.student_name || '')} · вручную` : `${esc(f.student_name || '')} · ${Math.round((f.confidence || 0) * 100)}%`;
|
||
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
|
||
cls = 'face-box--candidate';
|
||
label = `Похож: ${esc(f.best_student_name || '')} · ${Math.round((f.best_score || 0) * 100)}%`;
|
||
}
|
||
return `<button type="button" class="face-box ${cls}" data-face-box="${f.id}" style="left:${left}%;top:${top}%;width:${width}%;height:${height}%" title="${esc(label)}"><span class="face-box-label">${label}</span></button>`;
|
||
}).join('');
|
||
}
|
||
|
||
function renderFaceViewer(photoPath) {
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
const body = document.getElementById('faceViewerBody');
|
||
if (!body) return;
|
||
body.innerHTML = `<div class="face-stage"><img id="faceStageImg" src="${esc(API + photoPath)}" data-img="${esc(photoPath)}" alt=""><div class="face-overlay" id="faceOverlay"></div></div>`;
|
||
const img = document.getElementById('faceStageImg');
|
||
const overlay = document.getElementById('faceOverlay');
|
||
const stage = img.parentElement;
|
||
const layout = () => {
|
||
const nw = img.naturalWidth || 0;
|
||
const nh = img.naturalHeight || 0;
|
||
if (!nw || !nh) return;
|
||
overlay.style.width = img.clientWidth + 'px';
|
||
overlay.style.height = img.clientHeight + 'px';
|
||
overlay.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : '<div class="empty">Лиц не найдено</div>';
|
||
checkFaceViewerSync(nw, nh);
|
||
if (typeof renderIcons === 'function') renderIcons();
|
||
};
|
||
faceViewer.layout = layout;
|
||
window.addEventListener('resize', layout);
|
||
img.addEventListener('load', layout);
|
||
if (img.complete) layout();
|
||
}
|
||
|
||
async function refreshOpenFaceViewer() {
|
||
const photoId = faceViewer.photoId;
|
||
if (!photoId) return;
|
||
try {
|
||
await loadFaceViewerFaces(faceViewer.sourceType, photoId);
|
||
renderFaceViewer(faceViewer.photoPath);
|
||
} catch { /* ignore */ }
|
||
}
|
||
|
||
function closeFaceViewer() {
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
faceViewer.layout = null;
|
||
faceViewer.photoId = null;
|
||
faceViewer.photoPath = '';
|
||
const m = document.getElementById('faceViewerModal');
|
||
if (m) m.classList.remove('open');
|
||
}
|
||
|
||
async function openFaceViewer(sourceType, photoId, photoPath) {
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
faceViewer = { sourceType, photoId, photoPath, faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||
const body = document.getElementById('faceViewerBody');
|
||
if (body) body.innerHTML = '<div class="empty">Загрузка...</div>';
|
||
faceViewerWarn('');
|
||
document.getElementById('faceViewerModal').classList.add('open');
|
||
try {
|
||
await loadFaceViewerFaces(sourceType, photoId);
|
||
renderFaceViewer(photoPath);
|
||
} catch (e) {
|
||
if (body) body.innerHTML = `<div class="empty">${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}</div>`;
|
||
}
|
||
}
|
||
|
||
async function loadAllStudents() {
|
||
if (allStudentsLoaded) return;
|
||
try {
|
||
const res = await fetch(`${API}/api/students?limit=10000`, { headers: hdr() });
|
||
const data = res.ok ? await res.json() : [];
|
||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||
allStudents = list.filter(s => !s.deleted_at).map(s => ({ id: s.id, name: s.name, group_id: s.group_id, group_name: s.group_name || s.group }));
|
||
allStudentsLoaded = true;
|
||
} catch { allStudents = []; }
|
||
}
|
||
|
||
function renderFaceAssignList(q) {
|
||
const list = document.getElementById('faceAssignList');
|
||
if (!list) return;
|
||
const query = (q || '').trim().toLowerCase();
|
||
const filtered = allStudents.filter(s => {
|
||
if (!query) return true;
|
||
return (s.name || '').toLowerCase().includes(query) || (s.group_name || '').toLowerCase().includes(query);
|
||
}).sort((a, b) => {
|
||
// photos page has no "current group" concept; keep id order
|
||
return String(a.name).localeCompare(String(b.name), 'ru');
|
||
});
|
||
list.innerHTML = filtered.map(s => `
|
||
<button type="button" class="attach-item" data-face-pick="${s.id}">
|
||
<span class="attach-name">${esc(s.name)}</span>
|
||
<span class="attach-sub">${esc(s.group_name || '')}</span>
|
||
</button>
|
||
`).join('');
|
||
if (typeof renderIcons === 'function') renderIcons();
|
||
}
|
||
|
||
function openFaceAssign(faceId) {
|
||
faceAssignFaceId = faceId;
|
||
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
|
||
const inp = document.getElementById('faceAssignSearch');
|
||
if (inp) inp.value = (face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()) ? (face.best_student_name || '') : '';
|
||
loadAllStudents().then(() => renderFaceAssignList(inp ? inp.value : ''));
|
||
document.getElementById('faceAssignModal').classList.add('open');
|
||
}
|
||
|
||
async function assignFace(studentId) {
|
||
if (!faceAssignFaceId) return;
|
||
try {
|
||
const res = await fetch(`${API}/api/photo-faces/${faceAssignFaceId}/assign`, {
|
||
method: 'PUT',
|
||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ student_id: studentId || 0 })
|
||
});
|
||
if (!res.ok) throw new Error('assign');
|
||
document.getElementById('faceAssignModal').classList.remove('open');
|
||
faceAssignFaceId = null;
|
||
await refreshOpenFaceViewer();
|
||
loadPhotos();
|
||
} catch { showToast('Не удалось привязать лицо'); }
|
||
}
|
||
|
||
async function rescanFaceViewerPhoto() {
|
||
const photoId = faceViewer.photoId;
|
||
const sourceType = faceViewer.sourceType;
|
||
if (!photoId || !sourceType) return;
|
||
const btn = document.getElementById('faceViewerRescanBtn');
|
||
if (btn) { btn.disabled = true; btn.textContent = 'В очередь...'; }
|
||
try {
|
||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces/rescan`, {
|
||
method: 'POST',
|
||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({})
|
||
});
|
||
if (!res.ok) throw new Error('rescan');
|
||
showToast('Фото поставлено в очередь проверки — рамки обновятся автоматически');
|
||
loadPhotos();
|
||
} catch { showToast('Не удалось поставить в очередь'); }
|
||
finally {
|
||
if (btn) { btn.disabled = false; btn.textContent = 'Переиндексировать'; }
|
||
}
|
||
}
|
||
|
||
function connectFaceScanLive() {
|
||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||
const connect = () => {
|
||
const t = sessionStorage.getItem('authToken');
|
||
if (!t) return;
|
||
faceScanLiveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
|
||
faceScanLiveSource.addEventListener('face_scan_status', ev => {
|
||
let p = null;
|
||
try { p = JSON.parse(ev.data); } catch { return; }
|
||
if (!p || p.status === 'processing' || p.status === 'pending') return;
|
||
if (Number(p.source_id) === Number(faceViewer.photoId) && faceViewer.photoId) {
|
||
refreshOpenFaceViewer();
|
||
loadPhotos();
|
||
}
|
||
});
|
||
faceScanLiveSource.onerror = () => {
|
||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||
setTimeout(connect, 5000);
|
||
};
|
||
};
|
||
connect();
|
||
window.addEventListener('beforeunload', () => { if (faceScanLiveSource) faceScanLiveSource.close(); });
|
||
}
|
||
|
||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('sourceFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('faceStudentFilter')?.addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||
document.getElementById('searchInput').addEventListener('input', () => {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => { page = 1; loadPhotos(); }, 300);
|
||
});
|
||
|
||
document.getElementById('imgModal').addEventListener('click', e => e.currentTarget.classList.remove('open'));
|
||
|
||
document.getElementById('faceViewerCloseBtn')?.addEventListener('click', closeFaceViewer);
|
||
document.getElementById('faceViewerRescanBtn')?.addEventListener('click', rescanFaceViewerPhoto);
|
||
document.getElementById('faceViewerModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeFaceViewer(); });
|
||
document.getElementById('faceViewerBody')?.addEventListener('click', e => {
|
||
const box = e.target.closest('[data-face-box]');
|
||
if (box) openFaceAssign(box.dataset.faceBox);
|
||
});
|
||
document.getElementById('faceAssignCancelBtn')?.addEventListener('click', () => document.getElementById('faceAssignModal').classList.remove('open'));
|
||
document.getElementById('faceAssignModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) e.currentTarget.classList.remove('open'); });
|
||
document.getElementById('faceAssignList')?.addEventListener('click', e => {
|
||
const pick = e.target.closest('[data-face-pick]');
|
||
if (pick) assignFace(parseInt(pick.dataset.facePick, 10));
|
||
});
|
||
document.getElementById('faceUnassignBtn')?.addEventListener('click', () => assignFace(0));
|
||
document.getElementById('faceAssignSearch')?.addEventListener('input', e => renderFaceAssignList(e.target.value));
|
||
|
||
document.getElementById('grid').addEventListener('click', async e => {
|
||
const facesBtn = e.target.closest('[data-fv-source]');
|
||
if (facesBtn) {
|
||
openFaceViewer(facesBtn.dataset.fvSource, parseInt(facesBtn.dataset.fvId, 10), facesBtn.dataset.fvPath);
|
||
return;
|
||
}
|
||
const btn = e.target.closest('[data-quarantine]');
|
||
if (!btn) return;
|
||
if (await quarantineBrokenPhoto(btn.dataset.quarantine, btn.dataset.quarantineId)) loadPhotos();
|
||
});
|
||
|
||
(async () => {
|
||
if (await checkAuth()) {
|
||
buildSidebar('photos');
|
||
await loadGroupOptions();
|
||
await loadStudentOptions();
|
||
loadPhotos();
|
||
connectFaceScanLive();
|
||
}
|
||
})();
|