using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace Jellyfin.Plugin.Request.Hosting;
///
/// Injects the Request nav loader into jellyfin-web.
/// Prefers File Transformation (safe on Docker/Unraid); falls back to patching index.html on disk.
///
public sealed class WebNavInjector : IHostedService
{
///
/// Script URL injected into jellyfin-web index.html.
///
public const string LoaderSrc = "/Requests/Assets/nav-loader.js?v=1.0.0.9";
private const string MarkerStart = "";
private const string MarkerEnd = "";
private const string TransformationEndpoint = "/Requests/TransformIndexHtml";
private static readonly Guid TransformationId = Guid.Parse("11c08950-c4bb-484d-89ff-205b3724416b");
private readonly IServerApplicationPaths _applicationPaths;
private readonly ILogger _logger;
private CancellationTokenSource? _retryCts;
///
/// Initializes a new instance of the class.
///
/// Server application paths.
/// Logger.
public WebNavInjector(IServerApplicationPaths applicationPaths, ILogger logger)
{
_applicationPaths = applicationPaths;
_logger = logger;
}
///
public Task StartAsync(CancellationToken cancellationToken)
{
if (TryRegisterFileTransformation())
{
_logger.LogInformation(
"Request nav loader registered with File Transformation (callback + {Endpoint}).",
TransformationEndpoint);
return Task.CompletedTask;
}
_logger.LogWarning(
"File Transformation plugin was not found yet. Install/enable it from https://www.iamparadox.dev/jellyfin/plugins/manifest.json. Falling back to disk patch and retrying registration.");
try
{
TryPatchIndexHtml();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Could not patch jellyfin-web index.html on disk.");
}
_retryCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_ = RetryRegisterAsync(_retryCts.Token);
return Task.CompletedTask;
}
///
public Task StopAsync(CancellationToken cancellationToken)
{
_retryCts?.Cancel();
_retryCts?.Dispose();
return Task.CompletedTask;
}
///
/// File Transformation reflection callback.
///
/// Current file contents wrapper.
/// Transformed HTML.
public static string InjectNavLoader(JObject payload)
{
var html = payload?["contents"]?.ToString() ?? string.Empty;
return InjectHtml(html);
}
///
/// Injects the nav-loader script tag into index.html contents.
///
/// Current HTML.
/// Transformed HTML.
public static string InjectHtml(string html)
{
html ??= string.Empty;
if (html.Contains("/Requests/Assets/nav-loader.js", StringComparison.Ordinal)
|| html.Contains(MarkerStart, StringComparison.Ordinal))
{
return html;
}
var block = $"{MarkerStart}\n\n{MarkerEnd}\n";
var bodyIndex = html.LastIndexOf("