57 lines
1.8 KiB
C#
57 lines
1.8 KiB
C#
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);
|
|
}
|
|
}
|