feat(settings): Настраиваемый system favicon
Роут /favicon.ico берёт путь из настройки system_favicon; настройка входит в /api/public-settings, PUT /api/settings валидируется через isSafeUploadPath и удаляет файл и thumb при смене/очистке; sweepOrphanedUploads и BROKEN_IMAGE_SOURCES учитывают favicon; UI раздела настроек
This commit is contained in:
+78
-1
@@ -10,7 +10,9 @@ const BAN_REASONS = {
|
||||
};
|
||||
|
||||
let currentLogo = '';
|
||||
let logoOriginal = '';
|
||||
|
||||
let currentFavicon = '';
|
||||
let faviconOriginal = '';
|
||||
let currentSystemName = '';
|
||||
let photoAiService = null;
|
||||
|
||||
@@ -87,6 +89,18 @@ function renderLogoPreview() {
|
||||
rm.hidden = !hasLogo;
|
||||
}
|
||||
|
||||
function renderFaviconPreview() {
|
||||
const img = document.getElementById('faviconPreviewImg');
|
||||
const fb = document.getElementById('faviconPreviewFallback');
|
||||
const rm = document.getElementById('faviconRemoveBtn');
|
||||
if (!img || !fb || !rm) return;
|
||||
const has = !!currentFavicon;
|
||||
img.style.display = has ? 'block' : 'none';
|
||||
fb.style.display = has ? 'none' : '';
|
||||
if (has) img.src = currentFavicon;
|
||||
rm.hidden = !has;
|
||||
}
|
||||
|
||||
function fieldValue(el) {
|
||||
return el.type === 'checkbox' ? String(el.checked) : el.value;
|
||||
}
|
||||
@@ -191,6 +205,8 @@ function revertChanges() {
|
||||
});
|
||||
currentLogo = logoOriginal;
|
||||
renderLogoPreview();
|
||||
currentFavicon = faviconOriginal;
|
||||
renderFaviconPreview();
|
||||
clearFieldError('spamInterval');
|
||||
updateSpamUi();
|
||||
renderTimePreview();
|
||||
@@ -272,6 +288,9 @@ async function loadSettings() {
|
||||
currentLogo = s.system_logo || '';
|
||||
logoOriginal = currentLogo;
|
||||
renderLogoPreview();
|
||||
currentFavicon = s.system_favicon || '';
|
||||
faviconOriginal = currentFavicon;
|
||||
renderFaviconPreview();
|
||||
if (s.spam_interval_min !== undefined) document.getElementById('spamInterval').value = s.spam_interval_min;
|
||||
document.getElementById('trashPurgeDays').value = s.trash_purge_days !== undefined ? s.trash_purge_days : '30';
|
||||
const tzSel = document.getElementById('timezone');
|
||||
@@ -1386,6 +1405,64 @@ document.getElementById('logoRemoveBtn').addEventListener('click', async () => {
|
||||
}
|
||||
});
|
||||
|
||||
function faviconStatusText(html) {
|
||||
const st = document.getElementById('faviconUploadStatus');
|
||||
if (st) st.innerHTML = html;
|
||||
}
|
||||
|
||||
document.getElementById('faviconUploadBtn').addEventListener('click', () => document.getElementById('faviconInput').click());
|
||||
|
||||
document.getElementById('faviconInput').addEventListener('change', async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
const btn = document.getElementById('faviconUploadBtn');
|
||||
if (file.size > 512 * 1024) {
|
||||
e.target.value = '';
|
||||
showError('Favicon не должен превышать 512 КБ');
|
||||
return;
|
||||
}
|
||||
btn.disabled = true;
|
||||
faviconStatusText('<span class="spinner dark"></span> Загрузка...');
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append('favicon', file);
|
||||
const res = await fetch(`${API}/api/settings/favicon`, { method: 'POST', headers: hdr(), body: fd });
|
||||
const d = await res.json().catch(() => ({}));
|
||||
if (res.ok) {
|
||||
currentFavicon = d.system_favicon || '';
|
||||
renderFaviconPreview();
|
||||
faviconStatusText('');
|
||||
showToast('Favicon обновлён');
|
||||
} else {
|
||||
faviconStatusText(`<span class="fail">${esc(d.error || 'Ошибка загрузки')}</span>`);
|
||||
}
|
||||
} catch {
|
||||
faviconStatusText('<span class="fail">Ошибка сети</span>');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
e.target.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('faviconRemoveBtn').addEventListener('click', async () => {
|
||||
if (!confirm('Удалить favicon?')) return;
|
||||
faviconStatusText('<span class="spinner dark"></span> Удаление...');
|
||||
try {
|
||||
const res = await fetch(`${API}/api/settings/favicon`, { method: 'DELETE', headers: hdr() });
|
||||
if (res.ok) {
|
||||
currentFavicon = '';
|
||||
faviconOriginal = '';
|
||||
renderFaviconPreview();
|
||||
faviconStatusText('');
|
||||
showToast('Favicon удалён');
|
||||
} else {
|
||||
faviconStatusText('<span class="fail">Ошибка удаления</span>');
|
||||
}
|
||||
} catch {
|
||||
faviconStatusText('<span class="fail">Ошибка сети</span>');
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', e => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
|
||||
e.preventDefault();
|
||||
|
||||
+19
-1
@@ -70,7 +70,7 @@
|
||||
<div class="ic"><i data-lucide="palette"></i></div>
|
||||
<h3>Брендинг</h3>
|
||||
</div>
|
||||
<p class="hint">Название и логотип отображаются в админ-панели, на форме ответа ученика, странице входа и в отчёте.</p>
|
||||
<p class="hint">Название, логотип и favicon отображаются в админ-панели, на форме ответа ученика, странице входа и в отчёте.</p>
|
||||
<div class="settings-field">
|
||||
<label for="systemName">Название системы</label>
|
||||
<input type="text" id="systemName" class="settings-input" maxlength="60" placeholder="WhatIDo">
|
||||
@@ -93,6 +93,24 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label>Favicon</label>
|
||||
<div class="logo-picker">
|
||||
<div class="logo-preview" id="faviconPreview">
|
||||
<span id="faviconPreviewFallback">—</span>
|
||||
<img id="faviconPreviewImg" alt="Favicon">
|
||||
</div>
|
||||
<div class="logo-picker-actions">
|
||||
<div class="logo-picker-btns">
|
||||
<button class="btn-primary ghost" id="faviconUploadBtn" type="button"><i data-lucide="upload"></i> Загрузить favicon</button>
|
||||
<button class="btn-primary danger-ghost" id="faviconRemoveBtn" type="button" hidden><i data-lucide="trash-2"></i> Удалить</button>
|
||||
</div>
|
||||
<input type="file" id="faviconInput" accept=".ico,.png,.jpg,.jpeg,.gif,.webp,image/*" style="display:none">
|
||||
<div class="logo-upload-status" id="faviconUploadStatus"></div>
|
||||
<span class="hint">Квадратный значок браузера (.ico или .png), 32–128 px, не более 512 КБ</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-datetime">
|
||||
|
||||
@@ -878,6 +878,22 @@ app.get('/uploads/*', async (req, res) => {
|
||||
if (!res.headersSent) res.status(404).end();
|
||||
}
|
||||
});
|
||||
app.get('/favicon.ico', async (req, res) => {
|
||||
const p = await getSetting('system_favicon', '');
|
||||
const key = p && isSafeUploadPath(p) ? storage.keyFromPath(p) : null;
|
||||
if (!key) return res.status(404).end();
|
||||
try {
|
||||
const buf = await storage.getBuffer(key);
|
||||
if (!buf) return res.status(404).end();
|
||||
res.type(FAVICON_MIME[(path.extname(p) || '').toLowerCase()] || 'image/x-icon');
|
||||
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||
res.send(buf);
|
||||
} catch (e) {
|
||||
console.error('Favicon serve failed:', key, e.message);
|
||||
if (!res.headersSent) res.status(404).end();
|
||||
}
|
||||
});
|
||||
|
||||
app.use('/vendor', express.static(path.join(__dirname, 'public', 'vendor'), { maxAge: '30d' }));
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
@@ -1705,7 +1721,7 @@ async function sweepOrphanedUploads() {
|
||||
pool.query(`SELECT after_path AS p FROM photo_jobs WHERE status = 'done' AND applied = false AND after_path IS NOT NULL`),
|
||||
pool.query('SELECT photo_path AS p FROM modules WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT photo_path AS p FROM student_photos'),
|
||||
pool.query(`SELECT value AS p FROM settings WHERE key = 'system_logo' AND value IS NOT NULL AND value <> ''`),
|
||||
pool.query(`SELECT value AS p FROM settings WHERE key IN ('system_logo', 'system_favicon') AND value IS NOT NULL AND value <> ''`),
|
||||
pool.query('SELECT photo_path AS p FROM students WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT avatar AS p FROM users WHERE avatar IS NOT NULL'),
|
||||
pool.query('SELECT cover_path AS p FROM groups WHERE cover_path IS NOT NULL'),
|
||||
@@ -1760,6 +1776,7 @@ const BROKEN_IMAGE_SOURCES = [
|
||||
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
|
||||
{ key: 'photo_jobs.after_path', table: 'photo_jobs', column: 'after_path', idColumn: 'id', kind: 'column', label: 'Фото после обработки' },
|
||||
{ key: 'settings.system_logo', table: 'settings', column: 'value', idColumn: null, kind: 'setting', label: 'Логотип системы', where: `key = 'system_logo'` },
|
||||
{ key: 'settings.system_favicon', table: 'settings', column: 'value', idColumn: null, kind: 'setting', label: 'Favicon системы', where: `key = 'system_favicon'` },
|
||||
];
|
||||
|
||||
function brokenImageSource(key) {
|
||||
@@ -5524,8 +5541,8 @@ app.get('/api/settings', requireAdmin, async (_, res) => {
|
||||
|
||||
app.get('/api/public-settings', apiLimiter, async (_, res) => {
|
||||
const out = await cacheWrap('public-settings', PUBLIC_TTL_MS, async () => {
|
||||
const keys = ['system_name', 'system_logo', 'footer_left', 'footer_right', 'share_show_student_message', 'share_show_entry_date', 'share_show_student_names', 'share_show_group_photos', 'cookie_notice_text', 'spam_interval_min', 'photo_capture_resolution', 'photo_capture_quality', 'photo_enhance_engine', 'camera_enabled', 'photo_ai_face_mode', 'photo_ai_face_model', 'photo_ai_device_pref', 'timezone', 'time_format'];
|
||||
const defaults = { system_name: 'WhatIDo', system_logo: '', spam_interval_min: '30', photo_capture_resolution: '640x480', photo_capture_quality: '0.92', photo_enhance_engine: 'auto', camera_enabled: 'true', photo_ai_face_mode: PHOTO_AI_DEFAULT_FACE_MODE, photo_ai_face_model: PHOTO_AI_FACE_MODEL, photo_ai_device_pref: 'auto', timezone: DEFAULT_TIMEZONE, time_format: '24h' };
|
||||
const keys = ['system_name', 'system_logo', 'system_favicon', 'footer_left', 'footer_right', 'share_show_student_message', 'share_show_entry_date', 'share_show_student_names', 'share_show_group_photos', 'cookie_notice_text', 'spam_interval_min', 'photo_capture_resolution', 'photo_capture_quality', 'photo_enhance_engine', 'camera_enabled', 'photo_ai_face_mode', 'photo_ai_face_model', 'photo_ai_device_pref', 'timezone', 'time_format'];
|
||||
const defaults = { system_name: 'WhatIDo', system_logo: '', system_favicon: '', spam_interval_min: '30', photo_capture_resolution: '640x480', photo_capture_quality: '0.92', photo_enhance_engine: 'auto', camera_enabled: 'true', photo_ai_face_mode: PHOTO_AI_DEFAULT_FACE_MODE, photo_ai_face_model: PHOTO_AI_FACE_MODEL, photo_ai_device_pref: 'auto', timezone: DEFAULT_TIMEZONE, time_format: '24h' };
|
||||
const result = {};
|
||||
for (const k of keys) result[k] = await getSetting(k, defaults[k] || '');
|
||||
const rm = /^(\d{2,5})x(\d{2,5})$/.exec(result.photo_capture_resolution);
|
||||
@@ -5592,6 +5609,9 @@ app.put('/api/settings', requireAdmin, async (req, res) => {
|
||||
if (key === 'system_logo' && String(value) !== '' && !isSafeUploadPath(String(value))) {
|
||||
return res.status(400).json({ error: 'system_logo — некорректный путь' });
|
||||
}
|
||||
if (key === 'system_favicon' && String(value) !== '' && !isSafeUploadPath(String(value))) {
|
||||
return res.status(400).json({ error: 'system_favicon — некорректный путь' });
|
||||
}
|
||||
if (key === 'notify_retention_days') {
|
||||
const n = parseInt(String(value), 10);
|
||||
if (!Number.isFinite(n) || n < 1 || n > 365) {
|
||||
@@ -5855,6 +5875,55 @@ app.delete('/api/settings/logo', requireAdmin, async (req, res) => {
|
||||
res.json({ ok: true, system_logo: '' });
|
||||
});
|
||||
|
||||
const FAVICON_MIME = { '.ico': 'image/x-icon', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.bmp': 'image/bmp', '.avif': 'image/avif' };
|
||||
const faviconUpload = upload.single('favicon');
|
||||
app.post('/api/settings/favicon', requireAdmin, (req, res, next) => {
|
||||
faviconUpload(req, res, (err) => {
|
||||
if (err) {
|
||||
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
|
||||
if (err.message === 'Only images') return res.status(400).json({ error: 'Favicon: допустимы только изображения (ico, png, jpg, gif, webp, bmp, avif, heic, heif)' });
|
||||
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
|
||||
return res.status(400).json({ error: 'Недопустимый файл' });
|
||||
}
|
||||
next();
|
||||
});
|
||||
}, async (req, res) => {
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
const ext = (path.extname(req.file.originalname || '') || '').toLowerCase();
|
||||
if (!ALLOWED_IMAGE_EXT.has(ext)) {
|
||||
removeUpload(req.file);
|
||||
return res.status(400).json({ error: 'Favicon: допустимы только изображения (ico, png, jpg, gif, webp, bmp, avif, heic, heif, jfif)' });
|
||||
}
|
||||
try {
|
||||
if (['.heic', '.heif', '.jfif'].includes(ext)) await convertPhoto(req.file);
|
||||
const finalPath = `/uploads/${req.file.filename}`;
|
||||
const old = await getSetting('system_favicon', '');
|
||||
if (old && isSafeUploadPath(old) && old !== finalPath) safeUnlink(old);
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ('system_favicon', $1)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
|
||||
[finalPath]
|
||||
);
|
||||
await logAudit(req, 'settings.favicon.upload', { path: finalPath });
|
||||
invalidateSettings();
|
||||
res.json({ system_favicon: finalPath });
|
||||
} catch (e) {
|
||||
removeUpload(req.file);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/settings/favicon', requireAdmin, async (req, res) => {
|
||||
const old = await getSetting('system_favicon', '');
|
||||
if (old) {
|
||||
await pool.query(`UPDATE settings SET value = '' WHERE key = 'system_favicon'`);
|
||||
if (isSafeUploadPath(old)) safeUnlink(old);
|
||||
}
|
||||
await logAudit(req, 'settings.favicon.remove', {});
|
||||
invalidateSettings();
|
||||
res.json({ ok: true, system_favicon: '' });
|
||||
});
|
||||
|
||||
app.get('/api/audit', requireAdmin, async (req, res) => {
|
||||
const limit = Math.min(parseInt(req.query.limit, 10) || 100, 1000);
|
||||
const offset = Math.max(parseInt(req.query.offset, 10) || 0, 0);
|
||||
|
||||
Reference in New Issue
Block a user