Files
jRay/Jellyfin.Plugin.JRay/Controllers/TasksController.cs
dtourolleandClaude Opus 5 3b24fe1b3c Requirements register, spec rewrite, and TRACES tags
jRay had no requirement IDs, so nothing in this repo could be traced to and
the CI gate had no denominator to read. The other two components had already
moved to registers; this brings the plugin level with them.

Adds docs/requirements.md with 46 permanent JR-nnn IDs, each carrying a parent
requirement, priority, status and verification tier, plus a per-requirement
verification plan. JR is flat rather than split by theme: the plugin is one
deployable with one audience, and JRay-public-server already ships UR/DR, so a
second repo using those prefixes would make UR-007 ambiguous across registers.

Rewrites SPEC.md as requirements prose with Current:/Gap: on every one. It had
drifted into a format-plus-API reference that documented schema_version 1 while
owning a format whose v2 shape was specified only in the other two repos, said
nothing about SR-002's scene-scoped semantics, and carried the manifest
exchange as a "planned" aside while its configuration classes were already
implemented. Plugin-side exchange obligations move here from the server's
spec, where they were an ownership inversion.

Adds JR-038..041 for PR-005, which had no software row in any repo -- it was
held structurally by SR-004 and GR-005 both being prohibitions, and a goal
preserved only by prohibitions is the kind that erodes unnoticed. jRay is the
component that actually opens a socket.

Tags 18 units with the requirements they satisfy. Tags name what the code
satisfies, so FileTransformationRegistration is not tagged JR-021: that
requirement is a prohibition and was still violated elsewhere when this was
written.

Vendors jray-project as a submodule for the system spec and shared gate.

TRACES: JR-001, JR-004, JR-005, JR-007, JR-008, JR-009, JR-010, JR-011
TRACES: JR-012, JR-013, JR-014, JR-015, JR-016, JR-017, JR-018, JR-019
TRACES: JR-020, JR-024, JR-025, JR-036, JR-038

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 18:57:48 +02:00

142 lines
5.5 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Jellyfin.Data.Enums;
using Jellyfin.Plugin.JRay.Models;
using Jellyfin.Plugin.JRay.Services;
using Jellyfin.Plugin.JRay.Services.Interfaces;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Plugin.JRay.Controllers;
/// <summary>
/// Lets a remote extraction worker discover which library items still need
/// to be processed.
/// </summary>
/// <remarks>
/// The sample is random so that repeated polling spreads work across the
/// backlog without the server tracking who holds what, and so two workers
/// polling concurrently mostly do not collide.
///
/// Prioritise/ignore rules are applied <b>here and only here</b> (JR-017):
/// they express "don't spend compute on this", not "pretend this does not
/// exist", so they never reach the read endpoints or the overlay.
/// </remarks>
[ApiController]
[Route("Plugins/JRay/Tasks")]
[Authorize(Roles = "Administrator")]
// TRACES: JR-015, JR-017 | PR-003
public class TasksController : ControllerBase
{
private const int DefaultLimit = 10;
private const int MaxLimit = 100;
private readonly ILibraryManager _libraryManager;
private readonly ITruthDataService _truthDataService;
private readonly IMediaPolicyStore _policyStore;
/// <summary>
/// Initializes a new instance of the <see cref="TasksController"/> class.
/// </summary>
/// <param name="libraryManager">The Jellyfin library manager.</param>
/// <param name="truthDataService">The truth data service.</param>
/// <param name="policyStore">The prioritise/ignore policy store.</param>
public TasksController(ILibraryManager libraryManager, ITruthDataService truthDataService, IMediaPolicyStore policyStore)
{
_libraryManager = libraryManager;
_truthDataService = truthDataService;
_policyStore = policyStore;
}
/// <summary>
/// Gets a random sample of movies/episodes that have no truth data yet.
/// </summary>
/// <param name="limit">The maximum number of items to return (default 10, max 100).</param>
/// <returns>Up to <paramref name="limit"/> items with no truth data, in random order.</returns>
[HttpGet("Pending")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<IEnumerable<PendingExtractionItem>> GetPending([FromQuery] int limit = DefaultLimit)
{
var effectiveLimit = Math.Clamp(limit, 1, MaxLimit);
var rules = _policyStore.GetRules();
var items = _libraryManager.GetItemList(new InternalItemsQuery
{
IncludeItemTypes = new[] { BaseItemKind.Movie, BaseItemKind.Episode },
IsVirtualItem = false,
Recursive = true,
});
// Keep only items that still need truth data, then apply the policy:
// drop anything ignored, and order prioritised items ahead of the rest.
// Randomise within each tier so the backlog still spreads across workers.
var pending = items
.Where(item => MediaFileExists(item) && !_truthDataService.HasTruth(item.Id, item.Path))
.Select(item => new
{
Item = item,
Action = PolicyResolver.Resolve(rules, item.Id, GetSeriesId(item), item.Genres)
})
.Where(x => x.Action != PolicyAction.Ignore)
.OrderByDescending(x => x.Action == PolicyAction.Prioritise)
.ThenBy(_ => Random.Shared.Next())
.Take(effectiveLimit)
.Select(x => new PendingExtractionItem
{
ItemId = x.Item.Id,
Path = x.Item.Path,
Name = x.Item.Name
});
return Ok(pending);
}
/// <summary>
/// Gets the series id for an episode, or <see cref="Guid.Empty"/> for any
/// other item type (so series rules only ever match episodes).
/// </summary>
/// <param name="item">The library item.</param>
/// <returns>The owning series id, or empty.</returns>
internal static Guid GetSeriesId(BaseItem item)
{
return item is Episode episode ? episode.SeriesId : Guid.Empty;
}
/// <summary>
/// Determines whether an item's backing media still exists on disk.
/// <para>
/// A library item can outlive its file: deleting media from disk does not
/// always purge the Jellyfin database entry, and such ghosts keep
/// <c>IsVirtualItem == false</c>, so filtering on that flag alone is not
/// enough. Without this check the pending endpoint hands stale paths/URLs to
/// extraction workers, and — because a missing file can never gain truth
/// data — those items stay pending forever.
/// </para>
/// Only local (file-protocol) items are stat-checked; remote/streamed items
/// are assumed present so we never stat something off-box.
/// </summary>
/// <param name="item">The library item.</param>
/// <returns><c>true</c> if the item has usable backing media; otherwise <c>false</c>.</returns>
internal static bool MediaFileExists(BaseItem item)
{
if (string.IsNullOrEmpty(item.Path))
{
return false;
}
if (!item.IsFileProtocol)
{
return true;
}
// Path may point at a file or, for folder-based media, a directory.
return System.IO.File.Exists(item.Path) || Directory.Exists(item.Path);
}
}