Completes the scheduled jobs module with default jobs, a themed scheduler page and aligned recovery semantics

This commit is contained in:
BinaryAlley committed 2026-09-04 13:56:04 -07:00
1 parent 99a6159f7f
commit 4b7cfbbe11
67 files changed
+3324 -745

No files matched your search

@@ -6,7 +6,6 @@ using Lumina.Presentation.Web.Common.DTO.Scheduling;
using Lumina.Presentation.Web.Common.Requests.Scheduling;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -41,6 +40,7 @@ public class AddScheduledJobEndpoint : BaseEndpoint<AddScheduledJobRequest, IRes
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class FireScheduledJobEndpoint : BaseEndpoint<FireScheduledJobRequest, IR
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class RemoveScheduledJobEndpoint : BaseEndpoint<RemoveScheduledJobRequest
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -1,10 +1,20 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Lumina.Presentation.Web.Core.Themes;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -16,6 +26,40 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Admin.Scheduler;
/// </summary>
public class SchedulerIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
// the resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath
private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Admin.Scheduler";
private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
// the page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope
private const string VIEW_PAGE_KEY = "admin/scheduler";
private readonly IAntiforgery _antiforgery;
private readonly IOptionsSnapshot<ServerConfigurationDto> _serverConfigurationOptions;
private readonly IUrlService _urlService;
private readonly ThemePageRenderer _themePageRenderer;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="SchedulerIndexViewEndpoint"/> class.
/// </summary>
/// <param name="antiforgery">Injected service used to create the anti forgery tokens of the page.</param>
/// <param name="serverConfigurationOptions">Injected options used to read the address of the API server that hosts the scheduled jobs hub.</param>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public SchedulerIndexViewEndpoint(
IAntiforgery antiforgery,
IOptionsSnapshot<ServerConfigurationDto> serverConfigurationOptions,
IUrlService urlService,
ThemePageRenderer themePageRenderer,
IStringLocalizerFactory stringLocalizerFactory)
{
_antiforgery = antiforgery;
_serverConfigurationOptions = serverConfigurationOptions;
_urlService = urlService;
_themePageRenderer = themePageRenderer;
_localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
}
/// <summary>
/// Configures the endpoint.
/// </summary>
@@ -30,12 +74,65 @@ public class SchedulerIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
}
/// <summary>
/// Displays the scheduled jobs dashboard.
/// Displays the scheduled jobs dashboard, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
return Task.FromResult(View("/Core/Views/Admin/Scheduler.cshtml"));
ServerConfigurationDto serverConfiguration = _serverConfigurationOptions.Value;
Dictionary<string, object?> localizedStrings = ThemePageDataFactory.CreateLocalizedStrings(_localizer);
ThemePageDto pageModel = new()
{
PageKey = VIEW_PAGE_KEY,
Title = _localizer["ScheduledJobs"].Value,
Description = string.Empty,
PageData = new Dictionary<string, object?>
{
["scheduledJobsHubUrl"] = $"{serverConfiguration.BaseAddress}:{serverConfiguration.Port}/scheduledJobsHub",
["jobsListUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOBS) ?? string.Empty,
["addJobUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.ADD_SCHEDULED_JOB) ?? string.Empty,
["historyUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_SCHEDULED_JOB_HISTORY) ?? string.Empty,
["startJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.START_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty,
["stopJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.STOP_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty,
["fireJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.FIRE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty,
["removeJobUrlTemplate"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.REMOVE_SCHEDULED_JOB, new { scheduledJobId = default(System.Guid) }) ?? string.Empty,
["accessTokenUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Authentication.GET_API_ACCESS_TOKEN) ?? string.Empty,
["getDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.GET_DISPLAY_PREFERENCES) ?? string.Empty,
["updateDisplayPreferencesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Scheduler.UPDATE_DISPLAY_PREFERENCES) ?? string.Empty,
["antiforgeryToken"] = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken ?? string.Empty,
["strings"] = localizedStrings,
["taskTypeNames"] = CreateSubgroup(localizedStrings, "TaskType", ["ScanMediaLibraries", "CleanTemporaryFiles", "RepairThemes", "CleanScheduledJobExecutionHistory"]),
["statusNames"] = CreateSubgroup(localizedStrings, "Status", ["Added", "Active", "Running", "Completed"])
}
};
Result<ThemePageRenderResultDto> sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false);
if (sectionResult.IsFailure)
return View("/Core/Views/Admin/Scheduler.cshtml");
return View(
"/Core/Views/Shared/_ThemedView.cshtml",
new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script),
new Dictionary<string, object?> { ["Title"] = pageModel.Title });
}
/// <summary>
/// Creates the subgroup of the localized strings whose resource names start with the provided prefix followed by a dot,
/// keyed by the remainder of their names, so that a template can resolve them with non dotted expressions.
/// </summary>
/// <param name="localizedStrings">The localized strings keyed by their resource names.</param>
/// <param name="prefix">The prefix of the resource names of the subgroup.</param>
/// <param name="names">The names of the subgroup entries, without the prefix.</param>
/// <returns>The localized strings of the subgroup keyed by their names.</returns>
private static IReadOnlyDictionary<string, object?> CreateSubgroup(IReadOnlyDictionary<string, object?> localizedStrings, string prefix, IReadOnlyList<string> names)
{
Dictionary<string, object?> subgroup = new(StringComparer.OrdinalIgnoreCase);
foreach (string name in names)
if (localizedStrings.TryGetValue($"{prefix}.{name}", out object? value))
subgroup[name] = value;
return subgroup;
}
}
@@ -40,6 +40,7 @@ public class StartScheduledJobEndpoint : BaseEndpoint<StartScheduledJobRequest,
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class StopScheduledJobEndpoint : BaseEndpoint<StopScheduledJobRequest, IR
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -40,6 +40,7 @@ public class UpdateSchedulerDisplayPreferencesEndpoint : BaseEndpoint<UpdateSche
DontAutoTag();
Options(options => options.WithTags("Admin"));
Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
EnableAntiforgery();
}
/// <summary>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>اسم المهمة مطلوب.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>إصلاح السمات</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>تنظيف سجل الوظائف</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>عند بدء التشغيل</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Der Aufgabenname ist erforderlich.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Designs reparieren</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Jobverlauf bereinigen</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Beim Start</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>The job name is required.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repair themes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Clean job history</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>At startup</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>El nombre de la tarea es obligatorio.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Reparar temas</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Limpiar historial de trabajos</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Al inicio</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Le nom de la tâche est requis.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Réparer les thèmes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Nettoyer l'historique des tâches</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Au démarrage</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Il nome dell'attività è obbligatorio.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Ripara i temi</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Pulisci la cronologia dei processi</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>All'avvio</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>ジョブ名が必要です。</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>テーマを修復</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>ジョブ履歴を削除</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>起動時</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>The job name is required.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repair themes</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Clean job history</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>At startup</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Numele sarcinii este obligatoriu.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Repară temele</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Curăță istoricul proceselor</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>La pornire</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>Назва завдання обов'язкова.</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>Відновлення тем</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>Очистити історію завдань</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>Під час запуску</value>
</data>
</root>
@@ -159,4 +159,13 @@
<data name="JobNameRequired" xml:space="preserve">
<value>需要提供任务名称。</value>
</data>
<data name="TaskType.RepairThemes" xml:space="preserve">
<value>修复主题</value>
</data>
<data name="TaskType.CleanScheduledJobExecutionHistory" xml:space="preserve">
<value>清理作业历史</value>
</data>
<data name="StartupSchedule" xml:space="preserve">
<value>启动时</value>
</data>
</root>
@@ -1,5 +1,9 @@
@*
/admin/scheduled-jobs
This view is the application fallback of the scheduler page, rendered only when the theme page of the scheduler cannot be loaded.
It is intentionally plain and unstyled: on a healthy site the page comes from the theme's scheduler template, styled by the theme.
It keeps the DOM contract the client script binds to, without any images or colors, so that the active theme cannot leak into the fallback.
*@
@using Lumina.Presentation.Web.Common.DTO.Configuration
@@ -40,7 +44,9 @@
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="All">@_localizer["All"]</div>
<div class="enlightenment-option" data-value="ScanMediaLibraries">@_localizer["TaskType.ScanMediaLibraries"]</div>
<div class="enlightenment-option last-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="RepairThemes">@_localizer["TaskType.RepairThemes"]</div>
<div class="enlightenment-option last-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
</div>
</div>
</div>
@@ -109,7 +115,9 @@
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="ScanMediaLibraries">@_localizer["TaskType.ScanMediaLibraries"]</div>
<div class="enlightenment-option last-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="CleanTemporaryFiles">@_localizer["TaskType.CleanTemporaryFiles"]</div>
<div class="enlightenment-option" data-value="RepairThemes">@_localizer["TaskType.RepairThemes"]</div>
<div class="enlightenment-option last-option" data-value="CleanScheduledJobExecutionHistory">@_localizer["TaskType.CleanScheduledJobExecutionHistory"]</div>
</div>
</div>
</div>
@@ -124,7 +132,8 @@
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option" data-value="WithIntervalInMinutes">@_localizer["IntervalSchedule"]</div>
<div class="enlightenment-option last-option" data-value="DailyAtHourAndMinute">@_localizer["DailySchedule"]</div>
<div class="enlightenment-option" data-value="DailyAtHourAndMinute">@_localizer["DailySchedule"]</div>
<div class="enlightenment-option last-option" data-value="OnceAtStartup">@_localizer["StartupSchedule"]</div>
</div>
</div>
</div>
@@ -159,6 +168,7 @@
noJobs: '@_localizer["NoJobs"]',
daily: '@_localizer["DailySchedule"]',
interval: '@_localizer["IntervalSchedule"]',
startup: '@_localizer["StartupSchedule"]',
jobStarted: '@_localizer["JobStarted"]',
jobRemoved: '@_localizer["JobRemoved"]',
jobStopped: '@_localizer["JobStopped"]',
@@ -168,7 +178,9 @@
jobAlreadyRunning: '@_localizer["JobAlreadyRunning"]',
taskTypeNames: {
ScanMediaLibraries: '@_localizer["TaskType.ScanMediaLibraries"]',
CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]'
CleanTemporaryFiles: '@_localizer["TaskType.CleanTemporaryFiles"]',
RepairThemes: '@_localizer["TaskType.RepairThemes"]',
CleanScheduledJobExecutionHistory: '@_localizer["TaskType.CleanScheduledJobExecutionHistory"]'
},
statusNames: {
Added: '@_localizer["Status.Added"]',
@@ -181,7 +193,9 @@
// Colors of the job types.
const jobTypeColors = {
ScanMediaLibraries: '#5aa7c7',
CleanTemporaryFiles: '#c7a15a'
CleanTemporaryFiles: '#c7a15a',
RepairThemes: '#8bc34a',
CleanScheduledJobExecutionHistory: '#ba68c8'
};
const jobsTable = document.getElementById('scheduler-jobs-table');
@@ -281,7 +295,7 @@
}
// Graph state.
const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles'];
const taskTypeOrder = ['ScanMediaLibraries', 'CleanTemporaryFiles', 'RepairThemes', 'CleanScheduledJobExecutionHistory'];
const graphState = {
dataPoints: [],
pixelsPerSecond: 0,
@@ -341,13 +355,15 @@
row.dataset.scheduledJobId = job.id;
const isInterval = job.scheduleType === 'WithIntervalInMinutes';
const isDaily = job.scheduleType === 'DailyAtHourAndMinute';
const scheduleLabel = isInterval ? schedulerStrings.interval : isDaily ? schedulerStrings.daily : schedulerStrings.startup;
row.innerHTML = `
<td data-label="${escapeHtml(columnLabels[0])}">${job.id}</td>
<td data-label="${escapeHtml(columnLabels[1])}">${escapeHtml(job.name)}</td>
<td data-label="${escapeHtml(columnLabels[2])}">${schedulerStrings.taskTypeNames[job.taskType] ?? job.taskType}</td>
<td data-label="${escapeHtml(columnLabels[3])}">${isInterval ? schedulerStrings.interval : schedulerStrings.daily}</td>
<td data-label="${escapeHtml(columnLabels[3])}">${scheduleLabel}</td>
<td data-label="${escapeHtml(columnLabels[4])}">${isInterval ? job.intervalMinutes + ' ' + '@_localizer["MinutesShort"]' : '-'}</td>
<td data-label="${escapeHtml(columnLabels[5])}">${isInterval ? '-' : String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0')}</td>
<td data-label="${escapeHtml(columnLabels[5])}">${isDaily ? String(job.hour).padStart(2, '0') + ':' + String(job.minute).padStart(2, '0') : '-'}</td>
<td data-label="${escapeHtml(columnLabels[6])}">${schedulerStrings.statusNames[job.status] ?? job.status}</td>
<td data-label="${escapeHtml(columnLabels[7])}">${formatDateTime(job.lastStartedOnUtc)}</td>
<td data-label="${escapeHtml(columnLabels[8])}">${formatDateTime(job.lastCompletedOnUtc)}</td>
@@ -746,8 +762,10 @@
// Toggle the schedule fields based on the selected schedule type.
const toggleScheduleFields = () => {
const isDaily = getComboboxValue(jobScheduleTypeSelect) === 'DailyAtHourAndMinute';
intervalGroup.classList.toggle('hidden', isDaily);
const scheduleType = getComboboxValue(jobScheduleTypeSelect);
const isInterval = scheduleType === 'WithIntervalInMinutes';
const isDaily = scheduleType === 'DailyAtHourAndMinute';
intervalGroup.classList.toggle('hidden', !isInterval);
dailyGroup.classList.toggle('hidden', !isDaily);
dailyMinuteGroup.classList.toggle('hidden', !isDaily);
};