feat: add a wait before a notice can be accepted

This commit is contained in:
2026-11-13 22:46:07 +01:00
parent 28b6244a17
commit 93036bae89
12 changed files with 131 additions and 7 deletions
@@ -143,6 +143,18 @@ public class NoticeRulesTests
Assert.NotNull(NoticeRules.ValidateDraft(new NoticeDraft { Title = title })); Assert.NotNull(NoticeRules.ValidateDraft(new NoticeDraft { Title = title }));
} }
[Theory]
[InlineData(-1, false)]
[InlineData(0, true)]
[InlineData(600, true)]
[InlineData(601, false)]
public void Draft_AcceptDelayHasToBeInRange(int seconds, bool valid)
{
var draft = new NoticeDraft { Title = "Hi", RequireAccept = true, AcceptDelaySeconds = seconds };
Assert.Equal(valid, NoticeRules.ValidateDraft(draft) is null);
}
[Fact] [Fact]
public void Draft_SelectedUsersNeedAtLeastOneUser() public void Draft_SelectedUsersNeedAtLeastOneUser()
{ {
@@ -30,6 +30,26 @@ public sealed class NoticeServiceTests : IDisposable
return notice; return notice;
} }
[Fact]
public void AcceptDelay_IsStoredForMustAcceptNotices()
{
var created = Create("Terms", d =>
{
d.RequireAccept = true;
d.AcceptDelaySeconds = 15;
});
Assert.Equal(15, _service.Get(created.Id)!.AcceptDelaySeconds);
}
[Fact]
public void AcceptDelay_IsDroppedWithoutRequireAccept()
{
var created = Create("Info", d => d.AcceptDelaySeconds = 15);
Assert.Equal(0, _service.Get(created.Id)!.AcceptDelaySeconds);
}
[Fact] [Fact]
public void Create_RoundTripsThroughTheDatabase() public void Create_RoundTripsThroughTheDatabase()
{ {
@@ -83,6 +83,7 @@ public class HeraldController : ControllerBase
Title = n.Title, Title = n.Title,
Body = n.Body, Body = n.Body,
RequireAccept = n.RequireAccept, RequireAccept = n.RequireAccept,
AcceptDelaySeconds = n.AcceptDelaySeconds,
Revision = n.Revision Revision = n.Revision
})); }));
} }
@@ -27,6 +27,11 @@ public class PendingNotice
/// </summary> /// </summary>
public bool RequireAccept { get; set; } public bool RequireAccept { get; set; }
/// <summary>
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
/// </summary>
public int AcceptDelaySeconds { get; set; }
/// <summary> /// <summary>
/// Gets or sets the revision to send back with the response. /// Gets or sets the revision to send back with the response.
/// </summary> /// </summary>
@@ -72,6 +72,11 @@
</label> </label>
<div class="fieldDescription checkboxFieldDescription">The notice can only be closed with an "Accept" button.</div> <div class="fieldDescription checkboxFieldDescription">The notice can only be closed with an "Accept" button.</div>
</div> </div>
<div class="inputContainer" id="heraldDelayField">
<label class="inputLabel inputLabelUnfocused" for="heraldAcceptDelay">Wait before "Accept" can be clicked (seconds)</label>
<input id="heraldAcceptDelay" type="number" is="emby-input" min="0" max="600" step="1" value="0" />
<div class="fieldDescription">The button stays locked and counts down while the notice is on screen. 0 means no wait.</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription"> <div class="checkboxContainer checkboxContainer-withDescription">
<label class="emby-checkbox-label"> <label class="emby-checkbox-label">
<input id="heraldEnabled" type="checkbox" is="emby-checkbox" checked /> <input id="heraldEnabled" type="checkbox" is="emby-checkbox" checked />
@@ -310,7 +315,7 @@
text.appendChild(el('h3', 'listItemBodyText', notice.Title)); text.appendChild(el('h3', 'listItemBodyText', notice.Title));
var meta = [describeTarget(notice)]; var meta = [describeTarget(notice)];
if (notice.RequireAccept) { if (notice.RequireAccept) {
meta.push('must be accepted'); meta.push(notice.AcceptDelaySeconds > 0 ? 'must be accepted after ' + notice.AcceptDelaySeconds + ' s' : 'must be accepted');
} }
if (notice.Revision > 1) { if (notice.Revision > 1) {
meta.push('shown ' + notice.Revision + ' times'); meta.push('shown ' + notice.Revision + ' times');
@@ -342,6 +347,7 @@
Title: notice.Title, Title: notice.Title,
Body: notice.Body, Body: notice.Body,
RequireAccept: notice.RequireAccept, RequireAccept: notice.RequireAccept,
AcceptDelaySeconds: notice.AcceptDelaySeconds || 0,
Enabled: notice.Enabled, Enabled: notice.Enabled,
Target: { AllUsers: notice.Target.AllUsers, UserIds: notice.Target.UserIds } Target: { AllUsers: notice.Target.AllUsers, UserIds: notice.Target.UserIds }
}; };
@@ -413,6 +419,8 @@
byId('heraldTitle').value = notice ? notice.Title : ''; byId('heraldTitle').value = notice ? notice.Title : '';
byId('heraldBody').value = notice ? notice.Body : ''; byId('heraldBody').value = notice ? notice.Body : '';
byId('heraldRequireAccept').checked = notice ? notice.RequireAccept : false; byId('heraldRequireAccept').checked = notice ? notice.RequireAccept : false;
byId('heraldAcceptDelay').value = notice ? (notice.AcceptDelaySeconds || 0) : 0;
toggle(byId('heraldDelayField'), byId('heraldRequireAccept').checked);
byId('heraldEnabled').checked = notice ? notice.Enabled : true; byId('heraldEnabled').checked = notice ? notice.Enabled : true;
byId('heraldTarget').value = notice && !notice.Target.AllUsers ? 'selected' : 'all'; byId('heraldTarget').value = notice && !notice.Target.AllUsers ? 'selected' : 'all';
renderUserPicker(notice ? notice.Target.UserIds : []); renderUserPicker(notice ? notice.Target.UserIds : []);
@@ -448,6 +456,7 @@
Title: byId('heraldTitle').value, Title: byId('heraldTitle').value,
Body: byId('heraldBody').value, Body: byId('heraldBody').value,
RequireAccept: byId('heraldRequireAccept').checked, RequireAccept: byId('heraldRequireAccept').checked,
AcceptDelaySeconds: byId('heraldRequireAccept').checked ? (parseInt(byId('heraldAcceptDelay').value, 10) || 0) : 0,
Enabled: byId('heraldEnabled').checked, Enabled: byId('heraldEnabled').checked,
Target: { AllUsers: allUsers, UserIds: userIds } Target: { AllUsers: allUsers, UserIds: userIds }
}; };
@@ -617,6 +626,9 @@
byId('heraldAcksClose').addEventListener('click', closeAcks); byId('heraldAcksClose').addEventListener('click', closeAcks);
byId('heraldStatsRefresh').addEventListener('click', loadStats); byId('heraldStatsRefresh').addEventListener('click', loadStats);
byId('heraldNoticeForm').addEventListener('submit', submitForm); byId('heraldNoticeForm').addEventListener('submit', submitForm);
byId('heraldRequireAccept').addEventListener('change', function () {
toggle(byId('heraldDelayField'), this.checked);
});
byId('heraldTarget').addEventListener('change', function () { byId('heraldTarget').addEventListener('change', function () {
toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected'); toggle(byId('heraldUsers'), byId('heraldTarget').value === 'selected');
}); });
+5
View File
@@ -27,6 +27,11 @@ public class Notice
/// </summary> /// </summary>
public bool RequireAccept { get; set; } public bool RequireAccept { get; set; }
/// <summary>
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
/// </summary>
public int AcceptDelaySeconds { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the notice is shown at all. /// Gets or sets a value indicating whether the notice is shown at all.
/// </summary> /// </summary>
@@ -20,6 +20,11 @@ public class NoticeDraft
/// </summary> /// </summary>
public bool RequireAccept { get; set; } public bool RequireAccept { get; set; }
/// <summary>
/// Gets or sets the number of seconds the notice has to be on screen before it can be accepted.
/// </summary>
public int AcceptDelaySeconds { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the notice is shown. /// Gets or sets a value indicating whether the notice is shown.
/// </summary> /// </summary>
@@ -19,6 +19,11 @@ public static class NoticeRules
/// </summary> /// </summary>
public const int MaxBodyLength = 20000; public const int MaxBodyLength = 20000;
/// <summary>
/// Longest wait before a notice can be accepted, in seconds.
/// </summary>
public const int MaxAcceptDelaySeconds = 600;
/// <summary> /// <summary>
/// Checks whether a notice is addressed to a user. /// Checks whether a notice is addressed to a user.
/// </summary> /// </summary>
@@ -124,6 +129,11 @@ public static class NoticeRules
return "Body is too long."; return "Body is too long.";
} }
if (draft.AcceptDelaySeconds < 0 || draft.AcceptDelaySeconds > MaxAcceptDelaySeconds)
{
return "The wait before accepting has to be between 0 and 600 seconds.";
}
if (draft.Target is { AllUsers: false } target && (target.UserIds is null || target.UserIds.Count == 0)) if (draft.Target is { AllUsers: false } target && (target.UserIds is null || target.UserIds.Count == 0))
{ {
return "Select at least one user or address all users."; return "Select at least one user or address all users.";
@@ -210,6 +210,7 @@ public class NoticeService
notice.Title = (draft.Title ?? string.Empty).Trim(); notice.Title = (draft.Title ?? string.Empty).Trim();
notice.Body = (draft.Body ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Trim(); notice.Body = (draft.Body ?? string.Empty).Replace("\r\n", "\n", StringComparison.Ordinal).Trim();
notice.RequireAccept = draft.RequireAccept; notice.RequireAccept = draft.RequireAccept;
notice.AcceptDelaySeconds = draft.RequireAccept ? draft.AcceptDelaySeconds : 0;
notice.Enabled = draft.Enabled; notice.Enabled = draft.Enabled;
var allUsers = draft.Target?.AllUsers ?? true; var allUsers = draft.Target?.AllUsers ?? true;
@@ -50,6 +50,11 @@ public class HeraldDatabase
PRIMARY KEY (user_id, date) PRIMARY KEY (user_id, date)
); );
CREATE INDEX ix_watch_daily_date ON watch_daily (date); CREATE INDEX ix_watch_daily_date ON watch_daily (date);
""",
// 3: wait before a notice can be accepted
"""
ALTER TABLE notices ADD COLUMN accept_delay INTEGER NOT NULL DEFAULT 0;
""" """
]; ];
@@ -12,7 +12,7 @@ namespace Jellyfin.Plugin.Herald.Storage;
/// </summary> /// </summary>
public class SqliteNoticeStore : INoticeStore public class SqliteNoticeStore : INoticeStore
{ {
private const string NoticeColumns = "id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at"; private const string NoticeColumns = "id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at, accept_delay";
private const string AckColumns = "notice_id, revision, user_id, action, timestamp"; private const string AckColumns = "notice_id, revision, user_id, action, timestamp";
private readonly HeraldDatabase _database; private readonly HeraldDatabase _database;
@@ -66,12 +66,13 @@ public class SqliteNoticeStore : INoticeStore
connection, connection,
transaction, transaction,
""" """
INSERT INTO notices (id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at) INSERT INTO notices (id, title, body, require_accept, enabled, target_all, target_users, revision, created_at, updated_at, accept_delay)
VALUES ($id, $title, $body, $requireAccept, $enabled, $targetAll, $targetUsers, $revision, $createdAt, $updatedAt) VALUES ($id, $title, $body, $requireAccept, $enabled, $targetAll, $targetUsers, $revision, $createdAt, $updatedAt, $acceptDelay)
ON CONFLICT (id) DO UPDATE SET ON CONFLICT (id) DO UPDATE SET
title = excluded.title, title = excluded.title,
body = excluded.body, body = excluded.body,
require_accept = excluded.require_accept, require_accept = excluded.require_accept,
accept_delay = excluded.accept_delay,
enabled = excluded.enabled, enabled = excluded.enabled,
target_all = excluded.target_all, target_all = excluded.target_all,
target_users = excluded.target_users, target_users = excluded.target_users,
@@ -88,6 +89,7 @@ public class SqliteNoticeStore : INoticeStore
command.Parameters.AddWithValue("$revision", notice.Revision); command.Parameters.AddWithValue("$revision", notice.Revision);
command.Parameters.AddWithValue("$createdAt", Db.Time(notice.CreatedAt)); command.Parameters.AddWithValue("$createdAt", Db.Time(notice.CreatedAt));
command.Parameters.AddWithValue("$updatedAt", Db.Time(notice.UpdatedAt)); command.Parameters.AddWithValue("$updatedAt", Db.Time(notice.UpdatedAt));
command.Parameters.AddWithValue("$acceptDelay", notice.AcceptDelaySeconds);
return command.ExecuteNonQuery(); return command.ExecuteNonQuery();
}); });
} }
@@ -184,6 +186,7 @@ public class SqliteNoticeStore : INoticeStore
Title = reader.GetString(1), Title = reader.GetString(1),
Body = reader.GetString(2), Body = reader.GetString(2),
RequireAccept = reader.GetBoolean(3), RequireAccept = reader.GetBoolean(3),
AcceptDelaySeconds = reader.GetInt32(10),
Enabled = reader.GetBoolean(4), Enabled = reader.GetBoolean(4),
Target = new NoticeTarget Target = new NoticeTarget
{ {
+48 -3
View File
@@ -186,7 +186,8 @@
'.heraldLink{color:var(--jf-palette-primary-main,#00a4dc);text-decoration:underline}', '.heraldLink{color:var(--jf-palette-primary-main,#00a4dc);text-decoration:underline}',
'.heraldFoot{flex:none;display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:.4em 1em;padding:.7em 1.7em 1.3em}', '.heraldFoot{flex:none;display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:.4em 1em;padding:.7em 1.7em 1.3em}',
'.heraldError{flex:1 1 12em;margin:0;font-size:.9em;color:var(--jf-palette-error-main,#e2574c)}', '.heraldError{flex:1 1 12em;margin:0;font-size:.9em;color:var(--jf-palette-error-main,#e2574c)}',
'.heraldButton.heraldButton{flex:none;margin:0;min-width:8.5em;justify-content:center;text-align:center}', '.heraldButton.heraldButton{flex:none;margin:0;min-width:8.5em;justify-content:center;text-align:center;font-variant-numeric:tabular-nums}',
'.heraldButton.heraldWaiting{opacity:.5;cursor:default}',
'@media (max-width:30em){.heraldBackdrop{padding:.6em;align-items:flex-end}.heraldMast{padding:1.2em 1.2em 0}', '@media (max-width:30em){.heraldBackdrop{padding:.6em;align-items:flex-end}.heraldMast{padding:1.2em 1.2em 0}',
'.heraldBody{padding:.8em 1.2em .2em}.heraldFoot{padding:.6em 1.2em 1.1em}.heraldButton.heraldButton{flex:1 1 100%}}', '.heraldBody{padding:.8em 1.2em .2em}.heraldFoot{padding:.6em 1.2em 1.1em}.heraldButton.heraldButton{flex:1 1 100%}}',
'@media (prefers-reduced-motion:reduce){.heraldBackdrop,.heraldSheet.heraldSheet{transition:none}}' '@media (prefers-reduced-motion:reduce){.heraldBackdrop,.heraldSheet.heraldSheet{transition:none}}'
@@ -228,6 +229,7 @@
var backdrop = element('div', 'heraldBackdrop'); var backdrop = element('div', 'heraldBackdrop');
// "dialog" and the button classes are jellyfin-web's own, so the active theme colors them. // "dialog" and the button classes are jellyfin-web's own, so the active theme colors them.
var sheet = element('div', 'heraldSheet dialog'); var sheet = element('div', 'heraldSheet dialog');
sheet.tabIndex = -1;
sheet.setAttribute('role', mustAccept ? 'alertdialog' : 'dialog'); sheet.setAttribute('role', mustAccept ? 'alertdialog' : 'dialog');
sheet.setAttribute('aria-modal', 'true'); sheet.setAttribute('aria-modal', 'true');
sheet.setAttribute('aria-labelledby', titleId); sheet.setAttribute('aria-labelledby', titleId);
@@ -266,6 +268,7 @@
button: button, button: button,
error: error, error: error,
sending: false, sending: false,
timer: null,
previousFocus: document.activeElement, previousFocus: document.activeElement,
onKey: null onKey: null
}; };
@@ -302,7 +305,45 @@
backdrop.classList.add('heraldIn'); backdrop.classList.add('heraldIn');
}); });
}); });
button.focus(); var wait = mustAccept ? Math.floor(Number(notice.AcceptDelaySeconds) || 0) : 0;
if (wait > 0) {
holdButton(state, wait);
sheet.focus();
} else {
button.focus();
}
}
// Keeps the button locked for the given number of seconds. Only time with the tab in view counts.
function holdButton(state, seconds) {
var button = state.button;
var label = button.textContent;
var left = seconds;
function paint() {
button.textContent = label + ' (' + left + ')';
}
button.disabled = true;
button.classList.add('heraldWaiting');
paint();
state.timer = setInterval(function () {
if (document.hidden) {
return;
}
left--;
if (left > 0) {
paint();
return;
}
clearInterval(state.timer);
state.timer = null;
button.textContent = label;
button.classList.remove('heraldWaiting');
button.disabled = false;
button.focus();
}, 1000);
} }
function keepFocusInside(e, sheet) { function keepFocusInside(e, sheet) {
@@ -325,7 +366,7 @@
} }
function respond(state, action) { function respond(state, action) {
if (state.sending || open !== state) { if (state.sending || state.timer || open !== state) {
return; return;
} }
state.sending = true; state.sending = true;
@@ -361,6 +402,10 @@
return; return;
} }
open = null; open = null;
if (state.timer) {
clearInterval(state.timer);
state.timer = null;
}
document.removeEventListener('keydown', state.onKey, true); document.removeEventListener('keydown', state.onKey, true);
if (state.backdrop.parentNode) { if (state.backdrop.parentNode) {
state.backdrop.parentNode.removeChild(state.backdrop); state.backdrop.parentNode.removeChild(state.backdrop);