using System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using Jellyfin.Plugin.Herald.Notices; using Jellyfin.Plugin.Herald.Stats; using MediaBrowser.Common.Api; using MediaBrowser.Controller.Library; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Jellyfin.Plugin.Herald.Api; /// /// The Herald API. /// [ApiController] [Route("Herald")] [Authorize] [Produces(MediaTypeNames.Application.Json)] public class HeraldController : ControllerBase { private const string UserIdClaim = "Jellyfin-UserId"; private const string ClientScriptResource = "Jellyfin.Plugin.Herald.Web.client.js"; private readonly NoticeService _notices; private readonly StatsService _stats; private readonly IUserManager _userManager; /// /// Initializes a new instance of the class. /// /// The notice service. /// The stats service. /// The user manager. public HeraldController(NoticeService notices, StatsService stats, IUserManager userManager) { _notices = notices; _stats = stats; _userManager = userManager; } /// /// Gets the script that shows notices in jellyfin-web. /// /// Script returned. /// The client script. [HttpGet("client.js")] [AllowAnonymous] [Produces("application/javascript")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult GetClientScript() { var stream = typeof(HeraldController).Assembly.GetManifestResourceStream(ClientScriptResource); if (stream is null) { return NotFound(); } Response.Headers.CacheControl = "public, max-age=3600"; return File(stream, "application/javascript; charset=utf-8"); } /// /// Gets the notices the current user has not responded to yet, oldest first. /// /// Pending notices returned. /// The pending notices. [HttpGet("Notices/Pending")] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetPendingNotices() { if (!TryGetUserId(out var userId)) { // API keys are not tied to a user, so nothing can be pending. return Ok(Array.Empty()); } return Ok(_notices.GetPending(userId).Select(n => new PendingNotice { Id = n.Id, Title = n.Title, Body = n.Body, RequireAccept = n.RequireAccept, Revision = n.Revision })); } /// /// Records the current user's response to a notice. /// /// The notice id. /// The response. /// Response stored. /// The request is invalid, or the notice has to be accepted and cannot be dismissed. /// The notice does not exist or is not addressed to the user. /// The notice has a newer revision. /// No content. [HttpPost("Notices/{id:guid}/Ack")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesResponseType(StatusCodes.Status409Conflict)] public ActionResult AcknowledgeNotice([FromRoute] Guid id, [FromBody] AckRequest request) { ArgumentNullException.ThrowIfNull(request); if (!TryGetUserId(out var userId)) { return Problem("Acknowledging a notice needs a user session.", statusCode: StatusCodes.Status400BadRequest); } if (request.Revision is not { } revision || request.Action is not { } action || !Enum.IsDefined(action)) { return Problem("Revision and action are required.", statusCode: StatusCodes.Status400BadRequest); } return _notices.Acknowledge(userId, id, revision, action) switch { AckResult.Ok => NoContent(), AckResult.NotFound => NotFound(), AckResult.RevisionMismatch => Problem("The notice has changed. Fetch the pending notices again.", statusCode: StatusCodes.Status409Conflict), _ => Problem("This notice has to be accepted and cannot be dismissed.", statusCode: StatusCodes.Status400BadRequest) }; } /// /// Gets all notices. /// /// Notices returned. /// The notices, oldest first. [HttpGet("Notices")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetNotices() { return Ok(_notices.GetAll()); } /// /// Gets a notice. /// /// The notice id. /// Notice returned. /// Notice not found. /// The notice. [HttpGet("Notices/{id:guid}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult GetNotice([FromRoute] Guid id) { var notice = _notices.Get(id); return notice is null ? NotFound() : Ok(notice); } /// /// Creates a notice. /// /// The notice. /// Notice created. /// The notice is invalid. /// The created notice. [HttpPost("Notices")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public ActionResult CreateNotice([FromBody] NoticeDraft draft) { var error = NoticeRules.ValidateDraft(draft); if (error is not null) { return Problem(error, statusCode: StatusCodes.Status400BadRequest); } var notice = _notices.Create(draft); return CreatedAtAction(nameof(GetNotice), new { id = notice.Id }, notice); } /// /// Updates a notice. Users who already responded are not asked again; use the re-show action for that. /// /// The notice id. /// The notice. /// Notice updated. /// The notice is invalid. /// Notice not found. /// The updated notice. [HttpPut("Notices/{id:guid}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult UpdateNotice([FromRoute] Guid id, [FromBody] NoticeDraft draft) { var error = NoticeRules.ValidateDraft(draft); if (error is not null) { return Problem(error, statusCode: StatusCodes.Status400BadRequest); } var notice = _notices.Update(id, draft); return notice is null ? NotFound() : Ok(notice); } /// /// Deletes a notice and its acknowledgements. /// /// The notice id. /// Notice deleted. /// Notice not found. /// No content. [HttpDelete("Notices/{id:guid}")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult DeleteNotice([FromRoute] Guid id) { return _notices.Delete(id) ? NoContent() : NotFound(); } /// /// Shows a notice to everyone again by bumping its revision. /// /// The notice id. /// Revision bumped. /// Notice not found. /// The updated notice. [HttpPost("Notices/{id:guid}/Reshow")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult ReshowNotice([FromRoute] Guid id) { var notice = _notices.Reshow(id); return notice is null ? NotFound() : Ok(notice); } /// /// Gets who responded to the current revision of a notice, and which addressed users have not yet. /// /// The notice id. /// Report returned. /// Notice not found. /// The acknowledgement report. [HttpGet("Notices/{id:guid}/Acks")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public ActionResult GetNoticeAcks([FromRoute] Guid id) { var report = _notices.GetAckReport(id, UserNames()); return report is null ? NotFound() : Ok(report); } /// /// Gets approximate watch time per user. /// /// The number of days to cover, today included (1 to 90). /// Stats returned. /// One entry per user. [HttpGet("Stats")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] public ActionResult> GetStats([FromQuery] int days = 30) { return Ok(_stats.GetSummary(days, UserNames())); } private Dictionary UserNames() { return _userManager.GetUsers().ToDictionary(u => u.Id, u => u.Username); } private bool TryGetUserId(out Guid userId) { userId = Guid.Empty; var claim = User.FindFirst(UserIdClaim)?.Value; return !string.IsNullOrEmpty(claim) && Guid.TryParse(claim, out userId) && userId != Guid.Empty; } }