const API = location.origin; const form = document.getElementById('form'); const preview = document.getElementById('preview'); const placeholderSrc = preview.src; const removePhotoBtn = document.getElementById('removePhotoBtn'); const groupInput = document.getElementById('groupInput'); const moduleInput = document.getElementById('moduleInput'); const moduleInputList = document.getElementById('moduleInputList'); const moduleField = document.getElementById('moduleField'); const moduleNames = new Map(); const moduleAttachments = new Map(); let moduleSearchTimer = null; const toast = document.getElementById('toast'); const camVideo = document.getElementById('camVideo'); const camCanvas = document.getElementById('camCanvas'); const camModal = document.getElementById('camModal'); let capturedBlob = null; let stream = null; let camOpening = false; const descInput = document.getElementById('descInput'); const filesInput = document.getElementById('filesInput'); const filesList = document.getElementById('filesList'); const filesClearBtn = document.getElementById('filesClearBtn'); const filesAttachHint = document.getElementById('filesAttachHint'); let selectedFiles = []; const sentPanel = document.getElementById('sentPanel'); const sentTitle = document.getElementById('sentTitle'); const sentText = document.getElementById('sentText'); const sentTimer = document.getElementById('sentTimer'); const SENT_KEY = 'whatido_entry_sent_at'; let entryCooldownMin = 30; let captureWidth = 640; let captureHeight = 480; let captureQuality = 0.92; let sentTimerId = null; function unlockForm() { clearInterval(sentTimerId); sentTimerId = null; localStorage.removeItem(SENT_KEY); sentPanel.style.display = 'none'; form.style.display = 'grid'; toast.textContent = 'Можно отправить новую запись'; toast.classList.add('show'); setTimeout(() => toast.classList.remove('show'), 2500); } function tickSentTimer(unlockTime) { const remain = Math.max(0, unlockTime - Date.now()); if (remain <= 0) { sentTimer.textContent = ''; unlockForm(); return; } const m = Math.floor(remain / 60000); const s = Math.floor((remain % 60000) / 1000); sentTimer.textContent = 'Новую запись можно отправить через ' + m + ' мин ' + s + ' сек'; } function showSent(title, text, unlockTime) { form.style.display = 'none'; sentPanel.style.display = 'flex'; sentTitle.textContent = title; sentText.textContent = text; tickSentTimer(unlockTime); clearInterval(sentTimerId); sentTimerId = setInterval(() => tickSentTimer(unlockTime), 1000); } function cooldownMs() { return entryCooldownMin * 60 * 1000; } function checkPreviousSend() { const raw = localStorage.getItem(SENT_KEY); if (!raw) return; const sentAt = parseInt(raw, 10); if (!Number.isFinite(sentAt)) { localStorage.removeItem(SENT_KEY); return; } const unlockTime = sentAt + cooldownMs(); if (Date.now() < unlockTime) { showSent('Запись уже отправлена', 'Ты уже отправил(а) запись сегодня. Дождись окончания отсчёта, чтобы отправить новую.', unlockTime); } else { localStorage.removeItem(SENT_KEY); } } function humanSize(b) { if (b < 1024) return b + ' Б'; if (b < 1048576) return (b / 1024).toFixed(1) + ' КБ'; return (b / 1048576).toFixed(1) + ' МБ'; } function renderFiles() { filesList.innerHTML = ''; selectedFiles.forEach((f, i) => { const row = document.createElement('div'); row.className = 'file-row'; const name = document.createElement('span'); name.className = 'f-name'; name.textContent = f.name; name.title = f.name; const size = document.createElement('span'); size.className = 'f-size'; size.textContent = humanSize(f.size); const del = document.createElement('button'); del.type = 'button'; del.textContent = '✕'; del.addEventListener('click', () => removeFile(i)); row.append(name, size, del); filesList.appendChild(row); }); filesClearBtn.classList.toggle('show', selectedFiles.length > 0); } function removeFile(i) { selectedFiles.splice(i, 1); renderFiles(); } function clearFiles() { selectedFiles = []; filesInput.value = ''; renderFiles(); } const MAX_FILES = 10; const DEFAULT_FILE_LIMIT_MB = 50; const DEFAULT_TOTAL_LIMIT_MB = 200; let MAX_FILE_BYTES = DEFAULT_FILE_LIMIT_MB * 1024 * 1024; let MAX_TOTAL_BYTES = DEFAULT_TOTAL_LIMIT_MB * 1024 * 1024; const BLOCKED_FILE_EXT = /\.(?:html?|js|mjs|cjs|svg|xml|json|map|wasm|php\d?|phtml|asp|aspx|jsp|sh|bat|cmd|cgi|exe|dll|com|msi|scr|hta|vbs|py|r|rb|htaccess)$/i; const MIME_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/jpg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp', 'image/bmp': '.bmp', 'image/avif': '.avif', 'image/heic': '.heic', 'image/heif': '.heif', 'image/svg+xml': '.svg', 'application/pdf': '.pdf', 'application/zip': '.zip', 'application/x-zip-compressed': '.zip', 'application/msword': '.doc', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx', 'application/vnd.ms-excel': '.xls', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx', 'application/vnd.ms-powerpoint': '.ppt', 'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx', 'text/plain': '.txt', 'text/csv': '.csv', 'application/rtf': '.rtf', 'application/x-rar-compressed': '.rar', 'application/vnd.rar': '.rar', 'application/x-7z-compressed': '.7z' }; let notifyTimer = null; function notify(text, isError) { toast.textContent = text; toast.classList.add('show'); toast.classList.toggle('error', !!isError); clearTimeout(notifyTimer); notifyTimer = setTimeout(() => toast.classList.remove('show', 'error'), 3200); } function extOf(name) { const s = String(name || ''); const i = s.lastIndexOf('.'); return i > 0 ? s.slice(i).toLowerCase() : ''; } function extFromFile(file) { const named = extOf(file.name); if (/^\.[a-z0-9]{1,8}$/i.test(named)) return named; const byMime = MIME_EXT[String(file.type || '').toLowerCase()]; if (byMime) return byMime; const sub = String(file.type || '').split('/')[1] || ''; return /^[a-z0-9]{1,8}$/i.test(sub) ? '.' + sub : ''; } function pasteFileName(file) { const base = String(file.name || '').trim(); const stem = base.replace(/\.[a-z0-9]{1,8}$/i, ''); if (base && !/^(image|photo|picture|blob|file|screenshot|снимок|скриншот|изображение|файл)$/i.test(stem)) return base; const d = new Date(); const pad = n => String(n).padStart(2, '0'); const stamp = `${todayIso()} ${nowHm().replace(':', '-')}-${pad(d.getSeconds())}`; return `Вставка ${stamp}${extFromFile(file)}`; } function totalUploadBytes() { return (capturedBlob ? capturedBlob.size : 0) + selectedFiles.reduce((sum, f) => sum + f.size, 0); } function applyUploadLimits(fileMb, totalMb) { const f = parseInt(fileMb, 10); const t = parseInt(totalMb, 10); const fileLimit = Number.isFinite(f) && f >= 1 ? f : DEFAULT_FILE_LIMIT_MB; const totalLimit = Number.isFinite(t) && t >= fileLimit ? t : Math.max(DEFAULT_TOTAL_LIMIT_MB, fileLimit); MAX_FILE_BYTES = fileLimit * 1024 * 1024; MAX_TOTAL_BYTES = totalLimit * 1024 * 1024; } function addFiles(list) { const added = []; const skipped = []; const fileLimitMb = Math.round(MAX_FILE_BYTES / 1024 / 1024); const totalLimitMb = Math.round(MAX_TOTAL_BYTES / 1024 / 1024); for (const file of list) { if (selectedFiles.length >= MAX_FILES) { skipped.push(`Можно прикрепить не более ${MAX_FILES} файлов`); break; } if (file.size > MAX_FILE_BYTES) { skipped.push(`«${file.name}» больше ${fileLimitMb} МБ`); continue; } if (BLOCKED_FILE_EXT.test(extOf(file.name))) { skipped.push(`«${file.name}»: недопустимый тип файла`); continue; } if (totalUploadBytes() + file.size > MAX_TOTAL_BYTES) { skipped.push(`Суммарный размер файлов — не более ${totalLimitMb} МБ`); break; } selectedFiles.push(file); added.push(file.name); } if (added.length) renderFiles(); return { added, skipped }; } filesInput.addEventListener('change', () => { const res = addFiles([...filesInput.files]); filesInput.value = ''; if (res.skipped.length) alert(res.skipped[0]); }); document.addEventListener('paste', (e) => { if (form.style.display === 'none') return; const clip = e.clipboardData; if (!clip) return; const pasted = []; for (const item of Array.from(clip.items || [])) { if (item.kind !== 'file') continue; const file = item.getAsFile(); if (file) pasted.push(file); } if (!pasted.length && clip.files && clip.files.length) pasted.push(...Array.from(clip.files)); if (!pasted.length) return; e.preventDefault(); let filesAdded = 0; const skipped = []; for (const raw of pasted) { const name = pasteFileName(raw); const file = raw.name === name ? raw : new File([raw], name, { type: raw.type || 'application/octet-stream', lastModified: raw.lastModified }); const res = addFiles([file]); filesAdded += res.added.length; skipped.push(...res.skipped); } if (!filesAdded) { if (skipped.length) notify(skipped[0], true); return; } const summary = filesAdded === 1 ? 'Файл добавлен' : `Файлов добавлено: ${filesAdded}`; notify(summary + (skipped.length ? '. ' + skipped[0] : ''), skipped.length > 0); }); const params = new URLSearchParams(location.search); let studentName = ''; function escName(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; } if (params.get('nameInput')) { studentName = params.get('nameInput'); document.getElementById('nameInput').value = studentName; const field = document.getElementById('nameField'); field.innerHTML = `
${escName(studentName)}
`; } function renderModuleOptions(list) { list.forEach(m => { moduleNames.set(m.name, m.id); moduleAttachments.set(m.name.toLowerCase(), m.has_attachments === true); }); moduleInputList.innerHTML = ''; list.forEach(m => { const opt = document.createElement('option'); opt.value = m.name; moduleInputList.appendChild(opt); }); } function updateAttachHint() { const name = (moduleInput.value || '').trim().toLowerCase(); filesAttachHint.style.display = name && moduleAttachments.get(name) === true ? '' : 'none'; } const MODULE_LIST_LIMIT = 1000; function findModuleId(name) { const lower = (name || '').trim().toLowerCase(); if (!lower) return null; for (const [key, id] of moduleNames) { if (key.toLowerCase() === lower) return id; } return null; } async function fetchModules(q, limit, attempts = 2) { const p = new URLSearchParams(); if (q) p.set('search', q); p.set('limit', String(limit)); p.set('active', '1'); for (let i = 0; i < attempts; i++) { try { const res = await fetch(`${API}/api/modules?${p}`); if (!res.ok) return null; const data = await res.json(); return data.modules || []; } catch (e) { if (i < attempts - 1) await new Promise(r => setTimeout(r, 600)); } } return null; } async function resolveModuleId(name) { const n = (name || '').trim(); if (!n) return null; const cached = findModuleId(n); if (cached) return cached; const list = await fetchModules(n, 5); if (list) renderModuleOptions(list); const lower = n.toLowerCase(); const exact = (list || []).find(m => m.name.toLowerCase() === lower); return exact ? exact.id : null; } (async () => { await initDateTime(); try { const list = await fetchModules('', MODULE_LIST_LIMIT); if (list) { renderModuleOptions(list); if (list.length) { moduleInput.required = true; moduleField.style.display = ''; } } } catch (e) { /* ignore */ } const res = await fetch(`${API}/api/students`); const students = await res.json(); const me = studentName ? students.find(s => s.name === studentName) : null; if (me && me.group_id) { groupInput.innerHTML = ``; groupInput.value = String(me.group_id); } else { const groupsRes = await fetch(`${API}/api/groups/active`); const groups = await groupsRes.json(); groups.forEach(g => { const opt = document.createElement('option'); opt.value = g.id; opt.textContent = g.name; groupInput.appendChild(opt); }); if (!groups.length) { groupInput.innerHTML = ''; } } try { const fRes = await fetch(`${API}/api/public-settings`); const f = await fRes.json(); const title = document.getElementById('title'); if (title && (f.system_name || '').trim()) { title.textContent = f.system_name; document.title = f.system_name; } const brandLogo = document.getElementById('brandLogo'); if (brandLogo && f.system_logo) { brandLogo.src = f.system_logo; brandLogo.hidden = false; brandLogo.alt = f.system_name || ''; } if (f.footer_left) document.getElementById('footerLeft').textContent = f.footer_left; if (f.footer_right) document.getElementById('footerRight').textContent = f.footer_right; const c = parseInt(f.spam_interval_min, 10); if (Number.isFinite(c) && c >= 1) entryCooldownMin = c; const w = parseInt(f.photo_capture_width, 10); const h = parseInt(f.photo_capture_height, 10); if (Number.isFinite(w) && w >= 160 && w <= 4096) captureWidth = w; if (Number.isFinite(h) && h >= 120 && h <= 4096) captureHeight = h; const q = parseFloat(f.photo_capture_quality); if (Number.isFinite(q) && q >= 0.5 && q <= 1) captureQuality = q; applyUploadLimits(f.upload_file_limit_mb, f.upload_total_limit_mb); if (f.camera_enabled === 'false') { const camBtns = document.getElementById('camBtns'); if (camBtns) camBtns.style.display = 'none'; } } catch (e) { /* ignore */ } checkPreviousSend(); })(); function showPreview(src) { preview.src = src; preview.classList.add('has-photo'); removePhotoBtn.classList.add('show'); } function removePhoto() { preview.src = placeholderSrc; preview.classList.remove('has-photo'); removePhotoBtn.classList.remove('show'); capturedBlob = null; } async function openCam() { if (camOpening) return; if (stream && camModal.classList.contains('open')) return; camOpening = true; try { const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: { ideal: captureWidth }, height: { ideal: captureHeight } } }); if (camModal.classList.contains('open')) { s.getTracks().forEach(t => t.stop()); return; } stream = s; camVideo.srcObject = stream; camModal.classList.add('open'); } catch (e) { alert('Не удалось открыть камеру: ' + e.message); } finally { camOpening = false; } } function closeCam() { camModal.classList.remove('open'); if (stream) { stream.getTracks().forEach(t => t.stop()); stream = null; } } function capture() { if (!camVideo.videoWidth || !camVideo.videoHeight) { notify('Камера ещё не готова, попробуйте через секунду', true); return; } camCanvas.width = camVideo.videoWidth; camCanvas.height = camVideo.videoHeight; const ctx = camCanvas.getContext('2d'); ctx.translate(camCanvas.width, 0); ctx.scale(-1, 1); ctx.drawImage(camVideo, 0, 0); camCanvas.toBlob(blob => { capturedBlob = blob; showPreview(URL.createObjectURL(blob)); closeCam(); }, 'image/jpeg', captureQuality); } const ENTRY_SUBMIT_TIMEOUT_MS = 180000; const ENTRY_RETRY_STATUS = new Set([502, 503, 504]); async function postEntryOnce(fd) { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), ENTRY_SUBMIT_TIMEOUT_MS); try { return await fetch(`${API}/api/entries`, { method: 'POST', body: fd, signal: ctrl.signal }); } finally { clearTimeout(timer); } } async function postEntry(fd) { try { const res = await postEntryOnce(fd); if (ENTRY_RETRY_STATUS.has(res.status)) { await new Promise(r => setTimeout(r, 1500)); return { res: await postEntryOnce(fd), retried: true }; } return { res, retried: false }; } catch (err) { await new Promise(r => setTimeout(r, 1500)); return { res: await postEntryOnce(fd), retried: true }; } } form.addEventListener('submit', async (e) => { e.preventDefault(); if (!capturedBlob) { toast.textContent = 'Сначала сделайте фотографию'; toast.classList.add('show', 'error'); setTimeout(() => toast.classList.remove('show', 'error'), 3200); return; } let moduleId = ''; if (moduleField.style.display !== 'none') { moduleId = await resolveModuleId(moduleInput.value); if (!moduleId) { toast.textContent = 'Выберите тему модуля из списка подсказок'; toast.classList.add('show', 'error'); setTimeout(() => toast.classList.remove('show', 'error'), 3200); return; } } // Проверка: если модуль требует вложений, то файлы должны быть прикреплены const moduleAttachmentEnabled = moduleAttachments.get(moduleId) === true; if (moduleAttachmentEnabled && selectedFiles.length === 0) { toast.textContent = 'Для этой темы необходимо прикрепить файлы'; toast.classList.add('show', 'error'); setTimeout(() => toast.classList.remove('show', 'error'), 3000); return; } const btn = document.getElementById('submitBtn'); btn.disabled = true; btn.textContent = 'Отправка...'; const fd = new FormData(); fd.append('photo', capturedBlob, 'photo.jpg'); selectedFiles.forEach(f => fd.append('files', f, f.name)); fd.append('student_name', studentName || document.getElementById('nameInput').value); fd.append('group_id', groupInput.value); fd.append('module_id', moduleId || ''); fd.append('description', document.getElementById('descInput').value); fd.append('website', document.getElementById('hpWebsite').value); try { const { res, retried } = await postEntry(fd); if (res.status === 429) { if (retried) { form.reset(); removePhoto(); clearFiles(); updateAttachHint(); localStorage.setItem(SENT_KEY, String(Date.now())); showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs()); return; } const e = await res.json().catch(() => ({})); toast.textContent = e.error || 'Уже ответили: подождите'; toast.classList.add('show', 'error'); setTimeout(() => toast.classList.remove('show', 'error'), 3200); return; } if (!res.ok) { let msg = 'Не удалось отправить запись. Попробуй ещё раз.'; try { const e = await res.json(); if (e && e.error) msg = e.error; } catch (e) { /* not JSON */ } notify(msg, true); return; } form.reset(); removePhoto(); clearFiles(); updateAttachHint(); localStorage.setItem(SENT_KEY, String(Date.now())); showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs()); } catch (err) { notify('Не удалось отправить запись. Проверь интернет и попробуй ещё раз.', true); } finally { btn.disabled = false; btn.textContent = 'Отправить'; } }); removePhotoBtn.addEventListener('click', removePhoto); document.getElementById('openCamBtn').addEventListener('click', openCam); preview.addEventListener('click', openCam); preview.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openCam(); } }); filesClearBtn.addEventListener('click', clearFiles); document.getElementById('filesBtn').addEventListener('click', () => document.getElementById('filesInput').click()); document.getElementById('cancelCamBtn').addEventListener('click', closeCam); document.getElementById('captureBtn').addEventListener('click', capture); moduleInput.addEventListener('input', () => { updateAttachHint(); clearTimeout(moduleSearchTimer); const q = moduleInput.value.trim(); moduleSearchTimer = setTimeout(async () => { const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT); if (list) renderModuleOptions(list); updateAttachHint(); }, 250); }); moduleInput.addEventListener('focus', async () => { if (!moduleInput.value.trim()) { const list = await fetchModules('', MODULE_LIST_LIMIT); if (list) renderModuleOptions(list); } }); (async () => { const fab = document.getElementById('bmFab'); const btn = document.getElementById('bmBtn'); const modal = document.getElementById('bmModal'); const body = document.getElementById('bmModalBody'); const closeBtn = document.getElementById('bmClose'); if (!fab || !btn || !modal || !body || !closeBtn) return; const authToken = sessionStorage.getItem('authToken'); if (!authToken) return; let items = []; try { const res = await fetch(`${API}/api/bookmarks`, { headers: { 'X-Auth-Token': authToken } }); if (!res.ok) return; const data = await res.json(); items = Array.isArray(data.items) ? data.items : []; } catch (e) { return; } if (!items.length) return; function fullSrc(p) { if (!p) return p; if (/^https?:\/\//i.test(p)) return p; return API + p; } function logoSrc(p) { if (!p) return p; if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`; if (p.includes('/api/files/')) return p + (p.includes('?') ? '&' : '?') + 'thumb=1'; return p; } function hostOf(url) { try { return new URL(url, location.origin).host; } catch (e) { return ''; } } function linkFor(b) { const a = document.createElement('a'); a.href = b.url; if (b.open_new_tab) { a.target = '_blank'; a.rel = 'noopener noreferrer'; } return a; } function nameEl(b, cls) { const n = document.createElement('span'); n.className = cls; n.textContent = b.title || b.url; return n; } const covers = items.filter(b => b.image_mode === 'cover'); const logos = items.filter(b => b.image_mode !== 'cover'); if (covers.length) { const section = document.createElement('div'); section.className = 'bm-section'; const grid = document.createElement('div'); grid.className = 'bm-covers'; covers.forEach(b => { const a = linkFor(b); a.className = 'bm-cover-card'; if (b.photo_path) { const img = document.createElement('img'); img.className = 'bm-cover-img'; img.src = fullSrc(b.photo_path); img.alt = ''; img.loading = 'lazy'; a.appendChild(img); } const info = document.createElement('div'); info.className = 'bm-cover-body'; info.appendChild(nameEl(b, 'bm-cover-name')); const host = hostOf(b.url); if (host) { const h = document.createElement('span'); h.className = 'bm-host'; h.textContent = host; info.appendChild(h); } a.appendChild(info); grid.appendChild(a); }); section.append(grid); body.appendChild(section); } if (logos.length) { const section = document.createElement('div'); section.className = 'bm-section'; const row = document.createElement('div'); row.className = 'bm-logos'; logos.forEach(b => { const a = linkFor(b); a.className = 'bm-logo-card'; if (b.photo_path) { const img = document.createElement('img'); img.className = 'bm-logo-img'; img.src = logoSrc(b.photo_path); img.alt = ''; img.loading = 'lazy'; a.appendChild(img); } else { const ph = document.createElement('span'); ph.className = 'bm-logo-ph'; ph.innerHTML = ''; a.appendChild(ph); } a.appendChild(nameEl(b, 'bm-logo-name')); row.appendChild(a); }); section.append(row); body.appendChild(section); } fab.hidden = false; function setOpen(open) { modal.classList.toggle('open', open); modal.setAttribute('aria-hidden', open ? 'false' : 'true'); btn.setAttribute('aria-expanded', open ? 'true' : 'false'); } btn.addEventListener('click', () => setOpen(!modal.classList.contains('open'))); closeBtn.addEventListener('click', () => setOpen(false)); modal.addEventListener('click', (e) => { if (e.target === modal) setOpen(false); }); document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && modal.classList.contains('open')) setOpen(false); }); })();