using System;
using System.Text.RegularExpressions;
namespace Jellyfin.Plugin.JFVR.Services;
///
/// The pure text transformation behind :
/// given jellyfin-web's index.html, return the version with the JFVR
/// script tag in it.
///
/// Deliberately free of ASP.NET and Jellyfin types so it can be exercised
/// directly against captured HTML.
///
public static class IndexHtmlRewriter
{
///
/// Marker that identifies an index.html this plugin already rewrote.
///
public const string StartComment = "";
///
/// Closing half of the injected block.
///
public const string EndComment = "";
///
/// Matches the tag written by the old deploy.py
/// (<script plugin="JellyfinVR" ... src="jfvr-mvp.js?v=..."></script>).
///
/// The plugin's own tag deliberately uses plugin="JFVR", so the two can
/// never be confused: installing the plugin takes over from the legacy
/// injection automatically instead of loading the bundle twice.
///
private static readonly Regex LegacyTag = new(
"\\s*",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
///
/// Gets a value indicating whether already carries our block.
///
/// The served HTML.
/// True when the block is already present.
public static bool IsInjected(string html)
{
return html.Contains(StartComment, StringComparison.Ordinal);
}
///
/// Builds the block that gets inserted immediately before </body>.
///
/// URL of the bundle to load.
/// The HTML block, newline terminated.
public static string BuildBlock(string scriptUrl)
{
return StartComment
+ "\n\n"
+ EndComment
+ "\n";
}
///
/// Injects the JFVR block into .
///
/// Idempotent: an already-injected document is returned unchanged. A legacy
/// deploy.py tag is removed on the way so the bundle is never loaded twice.
/// If there is no </body> to anchor to, the (possibly
/// legacy-cleaned) input is returned unchanged.
///
/// The served HTML.
/// URL of the bundle to load.
/// True when a legacy tag was stripped.
/// The HTML to serve.
public static string Rewrite(string html, string scriptUrl, out bool removedLegacy)
{
removedLegacy = false;
if (IsInjected(html))
{
return html;
}
var cleaned = html;
if (LegacyTag.IsMatch(html))
{
cleaned = LegacyTag.Replace(html, string.Empty);
removedLegacy = true;
}
var bodyClose = cleaned.LastIndexOf("