Files
Jellyfin_Request_tvandmovies/Jellyfin.Plugin.Request/Hosting/WebNavInjector.cs
T
Michael SloanandCursor db166bfc02 fix(nav): reduce request tab flicker on home return
Hide the Request tab instead of removing it off-home, cache the button/panel, and reinject immediately when Jellyfin rebuilds the home tab bar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 21:38:28 -04:00

239 lines
8.1 KiB
C#

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;
/// <summary>
/// Injects the Request nav loader into jellyfin-web.
/// Prefers File Transformation (safe on Docker/Unraid); falls back to patching index.html on disk.
/// </summary>
public sealed class WebNavInjector : IHostedService
{
/// <summary>
/// Script URL injected into jellyfin-web index.html.
/// </summary>
public const string LoaderSrc = "/Requests/Assets/nav-loader.js?v=1.0.1.1";
private const string MarkerStart = "<!-- jellyfin-plugin-request-nav-start -->";
private const string MarkerEnd = "<!-- jellyfin-plugin-request-nav-end -->";
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<WebNavInjector> _logger;
private CancellationTokenSource? _retryCts;
/// <summary>
/// Initializes a new instance of the <see cref="WebNavInjector"/> class.
/// </summary>
/// <param name="applicationPaths">Server application paths.</param>
/// <param name="logger">Logger.</param>
public WebNavInjector(IServerApplicationPaths applicationPaths, ILogger<WebNavInjector> logger)
{
_applicationPaths = applicationPaths;
_logger = logger;
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
_retryCts?.Cancel();
_retryCts?.Dispose();
return Task.CompletedTask;
}
/// <summary>
/// File Transformation reflection callback.
/// </summary>
/// <param name="payload">Current file contents wrapper.</param>
/// <returns>Transformed HTML.</returns>
public static string InjectNavLoader(JObject payload)
{
var html = payload?["contents"]?.ToString() ?? string.Empty;
return InjectHtml(html);
}
/// <summary>
/// Injects the nav-loader script tag into index.html contents.
/// </summary>
/// <param name="html">Current HTML.</param>
/// <returns>Transformed HTML.</returns>
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<script src=\"{LoaderSrc}\" defer></script>\n{MarkerEnd}\n";
var bodyIndex = html.LastIndexOf("</body>", StringComparison.OrdinalIgnoreCase);
return bodyIndex >= 0
? html.Insert(bodyIndex, block)
: html + "\n" + block;
}
private async Task RetryRegisterAsync(CancellationToken cancellationToken)
{
for (var attempt = 1; attempt <= 12; attempt++)
{
try
{
await Task.Delay(TimeSpan.FromSeconds(Math.Min(3 * attempt, 20)), cancellationToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
if (TryRegisterFileTransformation())
{
_logger.LogInformation(
"Request nav loader registered with File Transformation on retry {Attempt}.",
attempt);
return;
}
}
_logger.LogWarning(
"File Transformation still unavailable after retries. Request tab will not appear until File Transformation is installed and Jellyfin is restarted.");
}
private bool TryRegisterFileTransformation()
{
try
{
Assembly? fileTransformationAssembly = AssemblyLoadContext.All
.SelectMany(context => context.Assemblies)
.FirstOrDefault(assembly =>
assembly.FullName?.Contains(".FileTransformation", StringComparison.OrdinalIgnoreCase) == true);
if (fileTransformationAssembly is null)
{
return false;
}
Type? pluginInterfaceType = fileTransformationAssembly.GetType(
"Jellyfin.Plugin.FileTransformation.PluginInterface");
MethodInfo? registerMethod = pluginInterfaceType?.GetMethod(
"RegisterTransformation",
BindingFlags.Public | BindingFlags.Static);
if (registerMethod is null)
{
_logger.LogWarning("File Transformation PluginInterface.RegisterTransformation was not found.");
return false;
}
// Prefer HTTP endpoint: plugin ALC reflection callbacks often fail to resolve.
// Keep callback fields as a secondary path when the host can invoke them.
JObject payload = new()
{
["id"] = TransformationId,
["fileNamePattern"] = @"index\.html",
["transformationEndpoint"] = TransformationEndpoint,
["callbackAssembly"] = typeof(WebNavInjector).Assembly.FullName,
["callbackClass"] = typeof(WebNavInjector).FullName,
["callbackMethod"] = nameof(InjectNavLoader)
};
registerMethod.Invoke(null, [payload]);
return true;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "File Transformation registration failed.");
return false;
}
}
private void TryPatchIndexHtml()
{
var indexPath = ResolveIndexHtmlPath();
if (indexPath is null)
{
_logger.LogWarning("Could not locate jellyfin-web index.html for Request nav injection.");
return;
}
var html = File.ReadAllText(indexPath);
if (html.Contains("/Requests/Assets/nav-loader.js", StringComparison.Ordinal))
{
_logger.LogInformation("Request nav loader already present in {Path}", indexPath);
return;
}
File.WriteAllText(indexPath, InjectHtml(html));
_logger.LogInformation("Injected Request nav loader into {Path}", indexPath);
}
private string? ResolveIndexHtmlPath()
{
var webPath = _applicationPaths.WebPath;
if (!string.IsNullOrWhiteSpace(webPath))
{
var candidate = Path.Combine(webPath, "index.html");
if (File.Exists(candidate))
{
return candidate;
}
}
string[] fallbacks =
[
"/usr/share/jellyfin/web/index.html",
"/usr/lib/jellyfin/bin/jellyfin-web/index.html",
Path.Combine(AppContext.BaseDirectory, "jellyfin-web", "index.html")
];
foreach (var path in fallbacks)
{
if (File.Exists(path))
{
return path;
}
}
return null;
}
}