using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.Request.Hosting;
///
/// Ensures jellyfin-web index.html loads the Request nav loader script.
///
public sealed class WebNavInjector : IHostedService
{
private const string LoaderSrc = "/Requests/Assets/nav-loader.js";
private const string MarkerStart = "";
private const string MarkerEnd = "";
private readonly IServerApplicationPaths _applicationPaths;
private readonly ILogger _logger;
///
/// 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)
{
try
{
TryInject();
}
catch (Exception ex)
{
_logger.LogWarning(
ex,
"Could not inject Request nav loader into jellyfin-web. Use scripts/install-web-loader.ps1 or .sh after ensuring index.html is writable.");
}
return Task.CompletedTask;
}
///
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void TryInject()
{
var indexPath = ResolveIndexHtmlPath();
if (indexPath is null)
{
_logger.LogWarning("Could not locate jellyfin-web index.html for Request nav injection.");
return;
}
if (!File.Exists(indexPath))
{
_logger.LogWarning("jellyfin-web index.html was not found at {Path}", indexPath);
return;
}
var html = File.ReadAllText(indexPath);
if (html.Contains(LoaderSrc, StringComparison.Ordinal))
{
_logger.LogInformation("Request nav loader already present in {Path}", indexPath);
return;
}
var block = $"{MarkerStart}{Environment.NewLine}{Environment.NewLine}{MarkerEnd}";
string updated;
var bodyIndex = html.LastIndexOf("