feat: inject client script through File Transformation
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Injection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the index.html transformation with the File Transformation plugin at startup.
|
||||
/// That plugin lives in its own load context, so it is only ever touched through reflection.
|
||||
/// </summary>
|
||||
public class FileTransformationRegistrar : IHostedService
|
||||
{
|
||||
private const string InterfaceTypeName = "Jellyfin.Plugin.FileTransformation.PluginInterface";
|
||||
// File Transformation treats this as a regular expression. Unanchored, "index.html" would also
|
||||
// match script chunks such as "session-login-index-html.<hash>.chunk.js".
|
||||
private const string IndexHtmlPattern = @"^index\.html$";
|
||||
private static readonly Guid _transformationId = Guid.Parse("bf6fabc9-721c-46d9-9e13-3cc415a9ae1b");
|
||||
|
||||
private readonly ILogger<FileTransformationRegistrar> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="FileTransformationRegistrar"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public FileTransformationRegistrar(ILogger<FileTransformationRegistrar> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
Register();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Registering with the File Transformation plugin failed. Notices will not pop up until the client script is added manually (see the Herald README)");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
private void Register()
|
||||
{
|
||||
var assembly = AssemblyLoadContext.All
|
||||
.SelectMany(context => context.Assemblies)
|
||||
.FirstOrDefault(a => a.FullName?.Contains(".FileTransformation", StringComparison.Ordinal) ?? false);
|
||||
|
||||
if (assembly is null)
|
||||
{
|
||||
_logger.LogWarning("The File Transformation plugin is not installed, so the Herald client script is not injected into the web client and notices will not pop up. Install File Transformation, or add the script manually (see the Herald README)");
|
||||
return;
|
||||
}
|
||||
|
||||
var register = assembly.GetType(InterfaceTypeName)?.GetMethod("RegisterTransformation", BindingFlags.Public | BindingFlags.Static);
|
||||
var payloadType = register?.GetParameters().FirstOrDefault()?.ParameterType;
|
||||
|
||||
// The payload is a Newtonsoft JObject from File Transformation's own context; build it there.
|
||||
var parse = payloadType?.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, [typeof(string)]);
|
||||
if (register is null || parse is null)
|
||||
{
|
||||
_logger.LogWarning("The installed File Transformation plugin ({Assembly}) does not expose the expected registration API. The Herald client script is not injected", assembly.FullName);
|
||||
return;
|
||||
}
|
||||
|
||||
var json = JsonSerializer.Serialize(new
|
||||
{
|
||||
id = _transformationId,
|
||||
fileNamePattern = IndexHtmlPattern,
|
||||
callbackAssembly = typeof(IndexHtmlTransformer).Assembly.FullName,
|
||||
callbackClass = typeof(IndexHtmlTransformer).FullName,
|
||||
callbackMethod = nameof(IndexHtmlTransformer.Transform)
|
||||
});
|
||||
|
||||
register.Invoke(null, [parse.Invoke(null, [json])]);
|
||||
_logger.LogInformation("Registered the Herald client script with File Transformation {Version}", assembly.GetName().Version);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Jellyfin.Plugin.Herald.Injection;
|
||||
|
||||
/// <summary>
|
||||
/// The object File Transformation hands to a transformation callback.
|
||||
/// </summary>
|
||||
public class IndexHtmlPayload
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the current contents of the requested file.
|
||||
/// </summary>
|
||||
public string? Contents { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Jellyfin.Plugin.Herald.Injection;
|
||||
|
||||
/// <summary>
|
||||
/// Adds the Herald client script to jellyfin-web's index.html.
|
||||
/// Invoked by the File Transformation plugin through reflection.
|
||||
/// </summary>
|
||||
public static class IndexHtmlTransformer
|
||||
{
|
||||
/// <summary>
|
||||
/// Marks the injected tag so it is never added twice.
|
||||
/// </summary>
|
||||
public const string Marker = "data-herald-client";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the script tag that loads the client. The path is relative to <c>/web/</c>, so it survives a base URL.
|
||||
/// </summary>
|
||||
public static string ScriptTag
|
||||
{
|
||||
get
|
||||
{
|
||||
var version = typeof(IndexHtmlTransformer).Assembly.GetName().Version?.ToString() ?? "0";
|
||||
return string.Format(CultureInfo.InvariantCulture, "<script {0} defer src=\"../Herald/client.js?v={1}\"></script>", Marker, version);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Transformation callback.
|
||||
/// </summary>
|
||||
/// <param name="payload">The file contents as provided by File Transformation.</param>
|
||||
/// <returns>The transformed contents.</returns>
|
||||
public static string Transform(IndexHtmlPayload payload)
|
||||
{
|
||||
return Inject(payload?.Contents ?? string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the script tag before the closing body tag. Content without one is not a page and is left alone.
|
||||
/// </summary>
|
||||
/// <param name="html">The page.</param>
|
||||
/// <returns>The page with the script tag.</returns>
|
||||
public static string Inject(string html)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(html);
|
||||
|
||||
if (html.Contains(Marker, StringComparison.Ordinal))
|
||||
{
|
||||
return html;
|
||||
}
|
||||
|
||||
var index = html.LastIndexOf("</body>", StringComparison.OrdinalIgnoreCase);
|
||||
return index < 0 ? html : html.Insert(index, ScriptTag);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user