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("", StringComparison.OrdinalIgnoreCase); if (bodyIndex >= 0) { updated = html.Insert(bodyIndex, block + Environment.NewLine); } else { updated = html + Environment.NewLine + block + Environment.NewLine; } File.WriteAllText(indexPath, updated); _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; } }