feat: add admin page with notices and stats tabs

This commit is contained in:
2026-11-13 18:10:41 +01:00
parent d161e26cd7
commit 1cc93c5250
@@ -0,0 +1,640 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Herald</title>
</head>
<body>
<div id="HeraldConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox,emby-textarea">
<style>
#HeraldConfigPage .heraldTabs { display: flex; margin: 0 0 1.5em; border-bottom: 1px solid rgba(128, 128, 128, .35); }
#HeraldConfigPage .heraldTab { padding: .9em 1.4em; margin: 0 0 -1px; border: 0; border-bottom: .2em solid transparent; background: none; font: inherit; font-weight: 600; cursor: pointer; }
#HeraldConfigPage .heraldTab.emby-tab-button-active { border-bottom-color: #00a4dc !important; }
#HeraldConfigPage .heraldBar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5em 1em; margin-bottom: 1em; }
#HeraldConfigPage .heraldBar h2 { margin: 0; }
#HeraldConfigPage .heraldBar button { margin: 0; }
#HeraldConfigPage .heraldEmpty { padding: 1.5em 0; opacity: .75; }
#HeraldConfigPage .heraldOff { opacity: .55; }
#HeraldConfigPage .heraldRowActions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; flex-shrink: 0; }
#HeraldConfigPage .heraldRowActions .checkboxContainer { margin: 0 .6em 0 0; }
#HeraldConfigPage .heraldPanel { margin: 1.5em 0 0; }
#HeraldConfigPage .heraldPanel h3 { margin: 1.4em 0 .5em; }
#HeraldConfigPage .heraldUsers { max-height: 20em; overflow-y: auto; padding: .4em 1em; margin-bottom: 1.8em; }
#HeraldConfigPage .heraldUsers .emby-checkbox-label { display: flex; margin: .5em 0; }
#HeraldConfigPage .heraldFormButtons { display: flex; flex-wrap: wrap; gap: .5em 1em; }
#HeraldConfigPage .heraldFormButtons button { flex: 1 1 12em; margin: 0; justify-content: center; }
#HeraldConfigPage #heraldBody { font-family: inherit; line-height: 1.5; padding: .6em; box-sizing: border-box; }
#HeraldConfigPage .heraldTableWrap { overflow-x: auto; }
#HeraldConfigPage .heraldTable th, #HeraldConfigPage .heraldTable td { padding: .65em .8em; white-space: nowrap; }
#HeraldConfigPage .heraldTable tbody tr { border-top: 1px solid rgba(128, 128, 128, .25); }
#HeraldConfigPage .heraldTable .heraldNum { text-align: right; font-variant-numeric: tabular-nums; }
#HeraldConfigPage .heraldSort { padding: 0; border: 0; background: none; color: inherit; font: inherit; font-weight: 700; cursor: pointer; }
#HeraldConfigPage .heraldSort[data-dir="asc"]::after { content: " \25B4"; }
#HeraldConfigPage .heraldSort[data-dir="desc"]::after { content: " \25BE"; }
#HeraldConfigPage .heraldShare { display: block; height: .18em; margin-top: .3em; margin-left: auto; background: currentColor; opacity: .45; }
#HeraldConfigPage .heraldGone { font-style: italic; opacity: .7; }
</style>
<div data-role="content">
<div class="content-primary">
<div class="heraldTabs" role="tablist">
<button type="button" class="heraldTab emby-tab-button emby-tab-button-active" role="tab" aria-selected="true" data-tab="notices">Notices</button>
<button type="button" class="heraldTab emby-tab-button" role="tab" aria-selected="false" data-tab="stats">Stats</button>
</div>
<div id="heraldNoticesTab" role="tabpanel">
<div class="heraldBar">
<h2 class="sectionTitle">Notices</h2>
<button is="emby-button" type="button" id="heraldNewNotice" class="raised button-submit emby-button">
<span>New notice</span>
</button>
</div>
<div class="fieldDescription">Each notice pops up once per user in the web client. It does not show in native apps (Android TV, Swiftfin, Kodi and the like).</div>
<div id="heraldNoticeList" class="paperList" style="margin-top: 1em;"></div>
<div id="heraldNoticeEmpty" class="heraldEmpty hide">No notices yet.</div>
<form id="heraldNoticeForm" class="heraldPanel hide">
<h2 class="sectionTitle" id="heraldFormTitle">New notice</h2>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="heraldTitle">Title</label>
<input id="heraldTitle" type="text" is="emby-input" maxlength="200" required />
</div>
<div class="inputContainer">
<label class="textareaLabel" for="heraldBody">Message</label>
<textarea id="heraldBody" is="emby-textarea" class="emby-textarea" rows="8" maxlength="20000" style="width: 100%;"></textarea>
<div class="fieldDescription">Plain text. Line breaks are kept. Also understood: **bold**, *italic*, [link text](https://example.org), and lines starting with "- " or "1. " as lists. HTML is shown as text.</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="heraldRequireAccept" type="checkbox" is="emby-checkbox" />
<span>Require users to accept</span>
</label>
<div class="fieldDescription checkboxFieldDescription">The notice can only be closed with an "Accept" button.</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label">
<input id="heraldEnabled" type="checkbox" is="emby-checkbox" checked />
<span>Enabled</span>
</label>
<div class="fieldDescription checkboxFieldDescription">Disabled notices are kept but not shown to anyone.</div>
</div>
<div class="selectContainer">
<label class="selectLabel" for="heraldTarget">Show to</label>
<select is="emby-select" id="heraldTarget" class="emby-select-withcolor emby-select">
<option value="all">All users</option>
<option value="selected">Selected users</option>
</select>
</div>
<div id="heraldUsers" class="heraldUsers paperList hide"></div>
<div class="heraldFormButtons">
<button is="emby-button" type="submit" class="raised button-submit emby-button">
<span>Save</span>
</button>
<button is="emby-button" type="button" id="heraldCancel" class="raised button-cancel emby-button">
<span>Cancel</span>
</button>
</div>
</form>
<div id="heraldAcks" class="heraldPanel hide">
<div class="heraldBar">
<h2 class="sectionTitle" id="heraldAcksTitle">Responses</h2>
<button is="emby-button" type="button" id="heraldAcksClose" class="raised button-cancel emby-button">
<span>Close</span>
</button>
</div>
<div class="fieldDescription" id="heraldAcksNote"></div>
<h3>Responded</h3>
<div class="heraldTableWrap">
<table class="detailTable heraldTable">
<thead>
<tr>
<th class="detailTableHeaderCell">User</th>
<th class="detailTableHeaderCell">Response</th>
<th class="detailTableHeaderCell">When</th>
</tr>
</thead>
<tbody id="heraldAcksRows"></tbody>
</table>
</div>
<h3>Not yet</h3>
<div id="heraldAcksPending"></div>
</div>
</div>
<div id="heraldStatsTab" role="tabpanel" class="hide">
<div class="heraldBar">
<h2 class="sectionTitle">Watch time</h2>
<button is="emby-button" type="button" id="heraldStatsRefresh" class="raised button-cancel emby-button">
<span>Refresh</span>
</button>
</div>
<div class="fieldDescription">Approximate time spent playing, counted from the progress reports clients send while playing. Paused time is left out. Days follow the server's clock.</div>
<div class="heraldTableWrap" style="margin-top: 1em;">
<table class="detailTable heraldTable">
<thead>
<tr>
<th class="detailTableHeaderCell"><button type="button" class="heraldSort" data-sort="name">User</button></th>
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="week">Last 7 days</button></th>
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="month">Last 30 days</button></th>
<th class="detailTableHeaderCell heraldNum"><button type="button" class="heraldSort" data-sort="plays">Plays (30 days)</button></th>
<th class="detailTableHeaderCell"><button type="button" class="heraldSort" data-sort="last">Last active</button></th>
</tr>
</thead>
<tbody id="heraldStatsRows"></tbody>
</table>
</div>
<div id="heraldStatsEmpty" class="heraldEmpty hide">No users.</div>
</div>
</div>
</div>
<script type="text/javascript">
(function () {
'use strict';
var page = document.querySelector('#HeraldConfigPage');
var byId = function (id) { return page.querySelector('#' + id); };
var notices = [];
var users = [];
var editingId = null;
var acksFor = null;
var stats = [];
var statsLoaded = false;
var sort = { key: 'month', dir: 'desc' };
// ------------------------------------------------------------ helpers
function api(method, path, body) {
var options = { type: method, url: ApiClient.getUrl(path) };
if (body) {
options.data = JSON.stringify(body);
options.contentType = 'application/json';
}
if (method === 'GET' || body) {
options.dataType = 'json';
}
return ApiClient.ajax(options);
}
function busy(promise) {
Dashboard.showLoadingMsg();
return promise.then(function (result) {
Dashboard.hideLoadingMsg();
return result;
}, function (response) {
Dashboard.hideLoadingMsg();
describeError(response).then(function (message) {
Dashboard.alert(message);
});
throw response;
});
}
function describeError(response) {
var fallback = 'Something went wrong. Check the server log.';
if (!response || typeof response.json !== 'function') {
return Promise.resolve(fallback);
}
return response.json().then(function (problem) {
return (problem && (problem.detail || problem.title)) || fallback;
}, function () {
return fallback;
});
}
function el(tag, className, text) {
var node = document.createElement(tag);
if (className) {
node.className = className;
}
if (text !== undefined && text !== null) {
node.textContent = text;
}
return node;
}
function clear(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function toggle(node, visible) {
node.classList.toggle('hide', !visible);
}
function when(value) {
return value ? new Date(value).toLocaleString() : 'never';
}
function duration(seconds) {
if (!seconds || seconds <= 0) {
return '–';
}
if (seconds < 60) {
return '< 1 min';
}
var minutes = Math.round(seconds / 60);
var h = Math.floor(minutes / 60);
var m = minutes % 60;
return h ? h + ' h ' + (m < 10 ? '0' : '') + m + ' min' : m + ' min';
}
function userName(id) {
for (var i = 0; i < users.length; i++) {
if (users[i].Id.replace(/-/g, '') === String(id).replace(/-/g, '')) {
return users[i].Name;
}
}
return null;
}
// Jellyfin's custom elements only upgrade when they come out of the HTML parser,
// so the element shells are parsed from fixed markup. Anything variable is set as text afterwards.
function parsed(markup) {
var holder = document.createElement('div');
holder.innerHTML = markup;
return holder.firstChild;
}
function checkbox(labelText, checked) {
var label = parsed('<label class="emby-checkbox-label"><input type="checkbox" is="emby-checkbox" /><span></span></label>');
var input = label.querySelector('input');
input.checked = !!checked;
label.querySelector('span').textContent = labelText;
return { label: label, input: input };
}
function iconButton(icon, title, onClick) {
var button = parsed('<button type="button" is="paper-icon-button-light"><span class="material-icons" aria-hidden="true"></span></button>');
button.title = title;
button.setAttribute('aria-label', title);
button.querySelector('span').classList.add(icon);
button.addEventListener('click', onClick);
return button;
}
// ------------------------------------------------------------ notices
function loadNotices() {
return busy(api('GET', 'Herald/Notices')).then(function (result) {
notices = result || [];
renderNotices();
});
}
function describeTarget(notice) {
if (notice.Target.AllUsers) {
return 'All users';
}
var names = notice.Target.UserIds.map(function (id) { return userName(id) || 'deleted user'; });
if (names.length <= 3) {
return names.join(', ');
}
return names.slice(0, 3).join(', ') + ' and ' + (names.length - 3) + ' more';
}
function renderNotices() {
var list = byId('heraldNoticeList');
clear(list);
toggle(byId('heraldNoticeEmpty'), notices.length === 0);
toggle(list, notices.length > 0);
notices.slice().reverse().forEach(function (notice) {
var row = el('div', 'listItem listItem-border');
var text = el('div', 'listItemBody two-line' + (notice.Enabled ? '' : ' heraldOff'));
text.appendChild(el('h3', 'listItemBodyText', notice.Title));
var meta = [describeTarget(notice)];
if (notice.RequireAccept) {
meta.push('must be accepted');
}
if (notice.Revision > 1) {
meta.push('shown ' + notice.Revision + ' times');
}
meta.push('changed ' + when(notice.UpdatedAt));
text.appendChild(el('div', 'listItemBodyText secondary', meta.join(' · ')));
row.appendChild(text);
var actions = el('div', 'heraldRowActions');
var enabled = checkbox('Enabled', notice.Enabled);
var holder = el('div', 'checkboxContainer');
holder.appendChild(enabled.label);
enabled.input.addEventListener('change', function () {
setEnabled(notice, enabled.input.checked);
});
actions.appendChild(holder);
actions.appendChild(iconButton('people', 'Responses', function () { showAcks(notice.Id); }));
actions.appendChild(iconButton('replay', 'Re-show to everyone', function () { reshow(notice); }));
actions.appendChild(iconButton('edit', 'Edit', function () { openForm(notice); }));
actions.appendChild(iconButton('delete', 'Delete', function () { remove(notice); }));
row.appendChild(actions);
list.appendChild(row);
});
}
function draftOf(notice) {
return {
Title: notice.Title,
Body: notice.Body,
RequireAccept: notice.RequireAccept,
Enabled: notice.Enabled,
Target: { AllUsers: notice.Target.AllUsers, UserIds: notice.Target.UserIds }
};
}
function setEnabled(notice, enabled) {
var draft = draftOf(notice);
draft.Enabled = enabled;
busy(api('PUT', 'Herald/Notices/' + notice.Id, draft)).then(loadNotices, loadNotices);
}
function ask(message, title, onYes) {
if (typeof Dashboard.confirm === 'function') {
Dashboard.confirm(message, title, function (yes) {
if (yes) {
onYes();
}
});
} else if (window.confirm(message)) {
onYes();
}
}
function reshow(notice) {
ask('Show "' + notice.Title + '" again to everyone it is addressed to, including users who already responded?', 'Re-show to everyone', function () {
busy(api('POST', 'Herald/Notices/' + notice.Id + '/Reshow')).then(function () {
return loadNotices();
}).then(function () {
if (acksFor === notice.Id) {
showAcks(notice.Id);
}
});
});
}
function remove(notice) {
ask('Delete "' + notice.Title + '" and its recorded responses?', 'Delete notice', function () {
busy(api('DELETE', 'Herald/Notices/' + notice.Id)).then(function () {
if (editingId === notice.Id) {
closeForm();
}
if (acksFor === notice.Id) {
closeAcks();
}
return loadNotices();
});
});
}
// ------------------------------------------------------------ form
function renderUserPicker(selectedIds) {
var box = byId('heraldUsers');
clear(box);
var selected = {};
(selectedIds || []).forEach(function (id) { selected[String(id).replace(/-/g, '')] = true; });
users.forEach(function (user) {
var item = checkbox(user.Name, selected[user.Id.replace(/-/g, '')]);
item.input.setAttribute('data-user-id', user.Id);
box.appendChild(item.label);
});
}
function openForm(notice) {
closeAcks();
editingId = notice ? notice.Id : null;
byId('heraldFormTitle').textContent = notice ? 'Edit notice' : 'New notice';
byId('heraldTitle').value = notice ? notice.Title : '';
byId('heraldBody').value = notice ? notice.Body : '';
byId('heraldRequireAccept').checked = notice ? notice.RequireAccept : false;
byId('heraldEnabled').checked = notice ? notice.Enabled : true;
byId('heraldTarget').value = notice && !notice.Target.AllUsers ? 'selected' : 'all';
renderUserPicker(notice ? notice.Target.UserIds : []);
toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected');
toggle(byId('heraldNoticeForm'), true);
byId('heraldTitle').focus();
}
function closeForm() {
editingId = null;
toggle(byId('heraldNoticeForm'), false);
}
function submitForm(e) {
e.preventDefault();
var allUsers = byId('heraldTarget').value !== 'selected';
var userIds = [];
if (!allUsers) {
var boxes = byId('heraldUsers').querySelectorAll('input[data-user-id]');
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].checked) {
userIds.push(boxes[i].getAttribute('data-user-id'));
}
}
if (!userIds.length) {
Dashboard.alert('Select at least one user, or show the notice to all users.');
return false;
}
}
var draft = {
Title: byId('heraldTitle').value,
Body: byId('heraldBody').value,
RequireAccept: byId('heraldRequireAccept').checked,
Enabled: byId('heraldEnabled').checked,
Target: { AllUsers: allUsers, UserIds: userIds }
};
var request = editingId
? api('PUT', 'Herald/Notices/' + editingId, draft)
: api('POST', 'Herald/Notices', draft);
busy(request).then(function () {
closeForm();
return loadNotices();
});
return false;
}
// ------------------------------------------------------------ responses
function showAcks(noticeId) {
closeForm();
busy(api('GET', 'Herald/Notices/' + noticeId + '/Acks')).then(function (report) {
acksFor = noticeId;
var notice = notices.filter(function (n) { return n.Id === noticeId; })[0];
byId('heraldAcksTitle').textContent = 'Responses: ' + (notice ? notice.Title : '');
byId('heraldAcksNote').textContent = report.Revision > 1
? 'Since it was last re-shown (round ' + report.Revision + ').'
: '';
var rows = byId('heraldAcksRows');
clear(rows);
if (!report.Responses.length) {
var none = el('tr');
var cell = el('td', 'detailTableBodyCell', 'Nobody has responded yet.');
cell.colSpan = 3;
none.appendChild(cell);
rows.appendChild(none);
}
report.Responses.forEach(function (entry) {
var row = el('tr');
row.appendChild(el('td', 'detailTableBodyCell' + (entry.UserName ? '' : ' heraldGone'), entry.UserName || 'deleted user'));
row.appendChild(el('td', 'detailTableBodyCell', entry.Action));
row.appendChild(el('td', 'detailTableBodyCell', when(entry.Timestamp)));
rows.appendChild(row);
});
var pending = byId('heraldAcksPending');
pending.textContent = report.Pending.length
? report.Pending.map(function (entry) { return entry.UserName; }).join(', ')
: 'Everyone it is addressed to has responded.';
toggle(byId('heraldAcks'), true);
byId('heraldAcks').scrollIntoView({ block: 'nearest' });
});
}
function closeAcks() {
acksFor = null;
toggle(byId('heraldAcks'), false);
}
// ------------------------------------------------------------ stats
function loadStats() {
return busy(Promise.all([api('GET', 'Herald/Stats?days=7'), api('GET', 'Herald/Stats?days=30')])).then(function (results) {
var week = {};
(results[0] || []).forEach(function (entry) { week[entry.UserId] = entry; });
stats = (results[1] || []).map(function (entry) {
return {
name: entry.UserName || null,
week: week[entry.UserId] ? week[entry.UserId].WatchedSeconds : 0,
month: entry.WatchedSeconds || 0,
plays: entry.PlayCount || 0,
last: entry.LastActivity ? new Date(entry.LastActivity).getTime() : 0
};
});
statsLoaded = true;
renderStats();
});
}
function renderStats() {
var direction = sort.dir === 'asc' ? 1 : -1;
var sorted = stats.slice().sort(function (a, b) {
var result = sort.key === 'name'
? (a.name || '￿').localeCompare(b.name || '￿', undefined, { sensitivity: 'base' })
: a[sort.key] - b[sort.key];
return result * direction || (a.name || '').localeCompare(b.name || '');
});
var top = stats.reduce(function (max, entry) { return Math.max(max, entry.month); }, 0);
var rows = byId('heraldStatsRows');
clear(rows);
toggle(byId('heraldStatsEmpty'), sorted.length === 0);
sorted.forEach(function (entry) {
var row = el('tr');
row.appendChild(el('td', 'detailTableBodyCell' + (entry.name ? '' : ' heraldGone'), entry.name || 'deleted user'));
row.appendChild(el('td', 'detailTableBodyCell heraldNum', duration(entry.week)));
var month = el('td', 'detailTableBodyCell heraldNum', duration(entry.month));
if (top > 0 && entry.month > 0) {
// Share of the busiest user's time, as a hairline under the value.
var share = el('span', 'heraldShare');
share.style.width = Math.max(4, Math.round(entry.month / top * 100)) + '%';
month.appendChild(share);
}
row.appendChild(month);
row.appendChild(el('td', 'detailTableBodyCell heraldNum', entry.plays ? String(entry.plays) : '–'));
row.appendChild(el('td', 'detailTableBodyCell', entry.last ? new Date(entry.last).toLocaleString() : 'not in the last 30 days'));
rows.appendChild(row);
});
var headers = page.querySelectorAll('.heraldSort');
for (var i = 0; i < headers.length; i++) {
var active = headers[i].getAttribute('data-sort') === sort.key;
if (active) {
headers[i].setAttribute('data-dir', sort.dir);
} else {
headers[i].removeAttribute('data-dir');
}
headers[i].parentNode.setAttribute('aria-sort', active ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none');
}
}
function sortBy(key) {
if (sort.key === key) {
sort.dir = sort.dir === 'asc' ? 'desc' : 'asc';
} else {
sort.key = key;
sort.dir = key === 'name' ? 'asc' : 'desc';
}
renderStats();
}
// ------------------------------------------------------------ tabs and wiring
function showTab(name) {
var tabs = page.querySelectorAll('.heraldTab');
for (var i = 0; i < tabs.length; i++) {
var active = tabs[i].getAttribute('data-tab') === name;
tabs[i].classList.toggle('emby-tab-button-active', active);
tabs[i].setAttribute('aria-selected', active ? 'true' : 'false');
}
toggle(byId('heraldNoticesTab'), name === 'notices');
toggle(byId('heraldStatsTab'), name === 'stats');
if (name === 'stats' && !statsLoaded) {
loadStats();
}
}
page.querySelector('.heraldTabs').addEventListener('click', function (e) {
var tab = e.target.closest('.heraldTab');
if (tab) {
showTab(tab.getAttribute('data-tab'));
}
});
page.querySelector('#heraldStatsTab thead').addEventListener('click', function (e) {
var header = e.target.closest('.heraldSort');
if (header) {
sortBy(header.getAttribute('data-sort'));
}
});
byId('heraldNewNotice').addEventListener('click', function () { openForm(null); });
byId('heraldCancel').addEventListener('click', closeForm);
byId('heraldAcksClose').addEventListener('click', closeAcks);
byId('heraldStatsRefresh').addEventListener('click', loadStats);
byId('heraldNoticeForm').addEventListener('submit', submitForm);
byId('heraldTarget').addEventListener('change', function () {
toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected');
});
page.addEventListener('pageshow', function () {
statsLoaded = false;
showTab('notices');
closeForm();
closeAcks();
busy(ApiClient.getUsers()).then(function (result) {
users = (result || []).slice().sort(function (a, b) {
return a.Name.localeCompare(b.Name, undefined, { sensitivity: 'base' });
});
return loadNotices();
});
});
})();
</script>
</div>
</body>
</html>