plugin: ship JFVR as a real Jellyfin plugin (self-hosted catalog)
Replaces the deploy.py approach (which sed-patched index.html inside the
container, and was therefore lost on every jellyfin/jellyfin upgrade) with a
proper plugin installable from a Jellyfin plugin repository.
The web bundle is unchanged: the same src/*.js -> dist/jfvr.js is now embedded
in Jellyfin.Plugin.JFVR.dll and served from /JFVR/jfvr.js with a content-hash
cache key. index.html is rewritten at request time by an IStartupFilter
middleware, so nothing on disk is touched.
Verified before this commit:
- dotnet build: 0 warnings, 0 errors (net10.0, Jellyfin.Controller 12.1.0)
- the DLL embeds dist/jfvr.js byte for byte
- 19/19 checks on the rewrite logic (injection, idempotency, legacy-tag
takeover, no </body> safety, other scripts preserved, URL override)
- manifest.json passes Jellyfin's PackageInfo/VersionInfo expectations
- the packaged zip's MD5 matches the checksum the manifest advertises
Details that were checked against the Jellyfin source rather than assumed:
- a catalog version survives when targetAbi <= serverVersion, so a single
targetAbi 12.0.0.0 package covers all of 12.x (server is 12.1.0)
- Jellyfin writes meta.json itself at install time, so the zip needs only
the DLL
- Jellyfin verifies the MD5 at install time
Also adds pack.py (build -> package -> manifest -> Gitea release) and documents
the plugin route in README/HANDOFF, keeping deploy.py as a fallback.
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Jellyfin.Plugin.JFVR.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the JFVR web bundle that is embedded in this assembly and exposes it
|
||||
/// together with a short content hash.
|
||||
///
|
||||
/// The hash is the cache-busting token in the injected
|
||||
/// <c><script src="../JFVR/jfvr.js?v=HASH"></c> tag, so a new plugin build
|
||||
/// always forces browsers to refetch the bundle. It is also the same
|
||||
/// <c>md5[:6]</c> version string the in-page HUD reports, which makes "which JS
|
||||
/// is the Quest actually running?" answerable from both sides.
|
||||
/// </summary>
|
||||
public sealed class BundleProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Logical name of the embedded resource, set explicitly in the .csproj so it
|
||||
/// does not depend on the project's folder layout.
|
||||
/// </summary>
|
||||
internal const string ResourceName = "Jellyfin.Plugin.JFVR.Web.jfvr.js";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BundleProvider"/> class.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Thrown when the bundle was not embedded, which means the build is broken.
|
||||
/// </exception>
|
||||
public BundleProvider()
|
||||
{
|
||||
using var stream = typeof(BundleProvider).Assembly.GetManifestResourceStream(ResourceName);
|
||||
if (stream is null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Embedded resource '{ResourceName}' is missing from {typeof(BundleProvider).Assembly.FullName}.");
|
||||
}
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
stream.CopyTo(buffer);
|
||||
Bytes = buffer.ToArray();
|
||||
Hash = Convert.ToHexString(MD5.HashData(Bytes)).ToLowerInvariant()[..8];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw bundle bytes.
|
||||
/// </summary>
|
||||
public byte[] Bytes { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the short (8 hex chars) MD5 of <see cref="Bytes"/>.
|
||||
/// </summary>
|
||||
public string Hash { get; }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Jellyfin.Plugin.JFVR.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The pure text transformation behind <see cref="ScriptInjectionStartupFilter"/>:
|
||||
/// given jellyfin-web's <c>index.html</c>, 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.
|
||||
/// </summary>
|
||||
public static class IndexHtmlRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Marker that identifies an index.html this plugin already rewrote.
|
||||
/// </summary>
|
||||
public const string StartComment = "<!-- BEGIN JFVR (Jellyfin Web VR) -->";
|
||||
|
||||
/// <summary>
|
||||
/// Closing half of the injected block.
|
||||
/// </summary>
|
||||
public const string EndComment = "<!-- END JFVR (Jellyfin Web VR) -->";
|
||||
|
||||
/// <summary>
|
||||
/// Matches the tag written by the old <c>deploy.py</c>
|
||||
/// (<c><script plugin="JellyfinVR" ... src="jfvr-mvp.js?v=..."></script></c>).
|
||||
///
|
||||
/// The plugin's own tag deliberately uses <c>plugin="JFVR"</c>, so the two can
|
||||
/// never be confused: installing the plugin takes over from the legacy
|
||||
/// injection automatically instead of loading the bundle twice.
|
||||
/// </summary>
|
||||
private static readonly Regex LegacyTag = new(
|
||||
"<script[^>]*plugin=\"JellyfinVR\"[^>]*>\\s*</script>\\s*",
|
||||
RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether <paramref name="html"/> already carries our block.
|
||||
/// </summary>
|
||||
/// <param name="html">The served HTML.</param>
|
||||
/// <returns>True when the block is already present.</returns>
|
||||
public static bool IsInjected(string html)
|
||||
{
|
||||
return html.Contains(StartComment, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the block that gets inserted immediately before <c></body></c>.
|
||||
/// </summary>
|
||||
/// <param name="scriptUrl">URL of the bundle to load.</param>
|
||||
/// <returns>The HTML block, newline terminated.</returns>
|
||||
public static string BuildBlock(string scriptUrl)
|
||||
{
|
||||
return StartComment
|
||||
+ "\n<script plugin=\"JFVR\" data-jfvr=\"1\" src=\"" + scriptUrl + "\" defer></script>\n"
|
||||
+ EndComment
|
||||
+ "\n";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Injects the JFVR block into <paramref name="html"/>.
|
||||
///
|
||||
/// Idempotent: an already-injected document is returned unchanged. A legacy
|
||||
/// <c>deploy.py</c> tag is removed on the way so the bundle is never loaded twice.
|
||||
/// If there is no <c></body></c> to anchor to, the (possibly
|
||||
/// legacy-cleaned) input is returned unchanged.
|
||||
/// </summary>
|
||||
/// <param name="html">The served HTML.</param>
|
||||
/// <param name="scriptUrl">URL of the bundle to load.</param>
|
||||
/// <param name="removedLegacy">True when a legacy tag was stripped.</param>
|
||||
/// <returns>The HTML to serve.</returns>
|
||||
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("</body>", StringComparison.OrdinalIgnoreCase);
|
||||
if (bodyClose < 0)
|
||||
{
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
return cleaned[..bodyClose] + BuildBlock(scriptUrl) + "\n" + cleaned[bodyClose..];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.JFVR.Services;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Jellyfin.Plugin.JFVR.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Injects the JFVR <c><script></c> tag into jellyfin-web's index.html at
|
||||
/// request time, through ASP.NET Core middleware registered via
|
||||
/// <see cref="IStartupFilter"/>.
|
||||
///
|
||||
/// Why request-time rewriting instead of the old deploy.py approach (which
|
||||
/// <c>sed</c>-patched <c>/jellyfin/jellyfin-web/index.html</c> inside the
|
||||
/// container):
|
||||
/// - nothing on disk is modified, so a <c>jellyfin/jellyfin:latest</c> upgrade
|
||||
/// cannot silently drop the injection;
|
||||
/// - it is idempotent and additive;
|
||||
/// - on any error the original response is served unchanged -- the middleware
|
||||
/// never throws into the pipeline;
|
||||
/// - it can be switched off from the dashboard.
|
||||
///
|
||||
/// The technique (strip Accept-Encoding so the static handler returns plain
|
||||
/// text, buffer the body, rewrite, fix up the validators) is the same one the
|
||||
/// community JavaScript Injector plugin uses; that plugin's own history is why
|
||||
/// the details below look paranoid.
|
||||
/// </summary>
|
||||
public sealed class ScriptInjectionStartupFilter : IStartupFilter
|
||||
{
|
||||
private readonly BundleProvider _bundle;
|
||||
private readonly ILogger<ScriptInjectionStartupFilter> _logger;
|
||||
private int _loggedOnce;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScriptInjectionStartupFilter"/> class.
|
||||
/// </summary>
|
||||
/// <param name="bundle">Embedded web bundle.</param>
|
||||
/// <param name="logger">Logger.</param>
|
||||
public ScriptInjectionStartupFilter(BundleProvider bundle, ILogger<ScriptInjectionStartupFilter> logger)
|
||||
{
|
||||
_bundle = bundle;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
|
||||
{
|
||||
return app =>
|
||||
{
|
||||
// Registered before next(app) so this runs outermost. That ordering
|
||||
// matters: stripping Accept-Encoding here means the response
|
||||
// compression middleware downstream never compresses the body, so
|
||||
// what we buffer is always complete, plain-text HTML.
|
||||
app.Use(InvokeAsync);
|
||||
next(app);
|
||||
};
|
||||
}
|
||||
|
||||
private async Task InvokeAsync(HttpContext context, Func<Task> nextMw)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config is null || !config.Enabled || !IsIndexRequest(context.Request))
|
||||
{
|
||||
await nextMw().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize the request so the static handler returns a complete 200:
|
||||
// - no Accept-Encoding -> no compression, plain text body;
|
||||
// - no Range/If-Range -> no 206 partial response, which would otherwise
|
||||
// pass through un-injected with a total length that no longer matches.
|
||||
var hadAcceptEncoding = context.Request.Headers.TryGetValue(HeaderNames.AcceptEncoding, out StringValues acceptEncoding);
|
||||
context.Request.Headers.Remove(HeaderNames.AcceptEncoding);
|
||||
context.Request.Headers.Remove(HeaderNames.Range);
|
||||
context.Request.Headers.Remove(HeaderNames.IfRange);
|
||||
|
||||
var originalBody = context.Response.Body;
|
||||
using var buffer = new MemoryStream();
|
||||
context.Response.Body = buffer;
|
||||
try
|
||||
{
|
||||
await nextMw().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Not ours to swallow. Discard the partially buffered body (it never
|
||||
// reached the real stream, so the response has not started) and let
|
||||
// the host render a clean error page.
|
||||
context.Response.Body = originalBody;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (hadAcceptEncoding)
|
||||
{
|
||||
context.Request.Headers[HeaderNames.AcceptEncoding] = acceptEncoding;
|
||||
}
|
||||
}
|
||||
|
||||
context.Response.Body = originalBody;
|
||||
buffer.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
var isHtml = context.Response.StatusCode == 200
|
||||
&& context.Response.ContentType is not null
|
||||
&& context.Response.ContentType.Contains("text/html", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isHtml)
|
||||
{
|
||||
// 304, redirects, non-HTML: pass straight through, byte for byte.
|
||||
await buffer.CopyToAsync(originalBody).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
string html;
|
||||
using (var reader = new StreamReader(buffer, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true))
|
||||
{
|
||||
html = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
html = Rewrite(html, config);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Never break index.html: serve whatever we have.
|
||||
_logger.LogWarning(ex, "JFVR: index.html rewrite failed, serving the original response.");
|
||||
}
|
||||
|
||||
var bytes = Encoding.UTF8.GetBytes(html);
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
context.Response.ContentLength = bytes.Length;
|
||||
|
||||
// The body changed, so validators computed for the original bytes are
|
||||
// invalid, and range requests on the rewritten document are not supported
|
||||
// (they are already stripped on the way in).
|
||||
context.Response.Headers.Remove(HeaderNames.ETag);
|
||||
context.Response.Headers.Remove(HeaderNames.LastModified);
|
||||
context.Response.Headers.Remove(HeaderNames.AcceptRanges);
|
||||
context.Response.Headers.Remove(HeaderNames.ContentEncoding);
|
||||
|
||||
await originalBody.WriteAsync(bytes).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private string Rewrite(string html, PluginConfiguration config)
|
||||
{
|
||||
var scriptUrl = string.IsNullOrWhiteSpace(config.ScriptUrlOverride)
|
||||
? "../JFVR/jfvr.js?v=" + _bundle.Hash
|
||||
: config.ScriptUrlOverride.Trim();
|
||||
|
||||
var rewritten = IndexHtmlRewriter.Rewrite(html, scriptUrl, out var removedLegacy);
|
||||
|
||||
if (removedLegacy)
|
||||
{
|
||||
_logger.LogInformation("JFVR: removed the legacy deploy.py <script> tag from index.html.");
|
||||
}
|
||||
|
||||
if (IndexHtmlRewriter.IsInjected(html) || rewritten == html)
|
||||
{
|
||||
// Already ours (the common case on every reload), or nothing to anchor to.
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref _loggedOnce, 1) == 0)
|
||||
{
|
||||
_logger.LogInformation("JFVR: injecting {Block}", IndexHtmlRewriter.BuildBlock(scriptUrl).Trim());
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Matches the web app shell however it is requested: bare <c>/web</c>,
|
||||
/// <c>/web/</c> (SPA serve) and an explicit <c>/web/index.html</c>. The
|
||||
/// EndsWith form stays correct when Jellyfin is hosted under a base-url
|
||||
/// prefix (e.g. <c>/jellyfin/web/</c>).
|
||||
/// </summary>
|
||||
private static bool IsIndexRequest(HttpRequest request)
|
||||
{
|
||||
if (!HttpMethods.IsGet(request.Method))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var path = request.Path.Value;
|
||||
if (string.IsNullOrEmpty(path) || path == "/")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return path.EndsWith("/web/index.html", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.EndsWith("/web/", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.Equals("/web", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user