From f4fe3d61fc24e4bace4d12ee39089815373a94da Mon Sep 17 00:00:00 2001 From: catShark <1716967236@qq.com> Date: Sat, 17 Oct 2026 23:17:00 +0800 Subject: [PATCH] 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 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. --- .gitignore | 6 + HANDOFF.md | 21 +- README.md | 51 ++- manifest.json | 20 + pack.py | 412 ++++++++++++++++++ .../Configuration/configPage.html | 129 ++++++ .../Controllers/JfvrController.cs | 82 ++++ .../Jellyfin.Plugin.JFVR.csproj | 48 ++ plugin/Jellyfin.Plugin.JFVR/Plugin.cs | 66 +++ .../PluginConfiguration.cs | 25 ++ .../PluginServiceRegistrator.cs | 23 + .../Services/BundleProvider.cs | 55 +++ .../Services/IndexHtmlRewriter.cs | 97 +++++ .../Services/ScriptInjectionStartupFilter.cs | 203 +++++++++ plugin/build.yaml | 27 ++ 15 files changed, 1256 insertions(+), 9 deletions(-) create mode 100644 manifest.json create mode 100644 pack.py create mode 100644 plugin/Jellyfin.Plugin.JFVR/Configuration/configPage.html create mode 100644 plugin/Jellyfin.Plugin.JFVR/Controllers/JfvrController.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/Jellyfin.Plugin.JFVR.csproj create mode 100644 plugin/Jellyfin.Plugin.JFVR/Plugin.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/PluginConfiguration.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/PluginServiceRegistrator.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/Services/BundleProvider.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/Services/IndexHtmlRewriter.cs create mode 100644 plugin/Jellyfin.Plugin.JFVR/Services/ScriptInjectionStartupFilter.cs create mode 100644 plugin/build.yaml diff --git a/.gitignore b/.gitignore index 0c1f491..cb64996 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,9 @@ __pycache__/ Thumbs.db *.swp *~ + +# --- .NET plugin build ------------------------------------------------- +plugin/**/bin/ +plugin/**/obj/ +# pack.py output: the packaged plugin zip (distributed via Gitea Releases) +dist/plugin/ diff --git a/HANDOFF.md b/HANDOFF.md index 3a41127..f035cba 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -386,7 +386,13 @@ cd /home/cat/Desktop/myProject/jelllyfin_vr_web_plugin # 语法检查(全部模块) python3 build.py --check -# 构建 + 部署(自动构建 → 上传 → 注入 script 标签) +# ---- 插件路线(推荐)---- +python3 pack.py # 构建 + 打包 + 更新 manifest.json +python3 pack.py --bump --publish # 版本号 +1,建 Gitea Release,上传 zip,推 manifest +python3 pack.py --print-urls # 只打印 Jellyfin 要填的仓库地址 +# 需要 GITEA_TOKEN(write:repository),从环境变量或 secrets.local.md 读 + +# ---- 老路线:直接注入容器内文件(兜底)---- # 密码从环境变量读;真实值放在本地 secrets.local.md(不入库) export JF_PW='' python3 deploy.py @@ -401,7 +407,8 @@ python3 deploy.py --legacy ./quest.sh ``` -**部署后必须让用户刷新页面**(脚本按页面加载缓存,URL 里的 `?r=` 是破缓存用的)。 +**插件路线**:Jellyfin 里点更新/重装 → 重启 → 刷新浏览器。 +**老路线**:部署后必须让用户刷新页面(脚本按页面加载缓存,URL 里的 `?r=` 是破缓存用的)。 ### 诊断信息 @@ -432,10 +439,12 @@ errors[] 最近错误 ## 10. 长期隐患 -1. **注入写在容器内文件**(`/jellyfin/jellyfin-web/index.html`)→ - `jellyfin/jellyfin:latest` 一升级就没了,需重跑 `deploy.py`。 - 正式版应改用 **JavaScript Injector**(`n00bcodr/jellyfin-plugins` 的 `12/manifest.json`, - targetAbi 12.0.0.0)或 **File Transformation**(`IAmParadox27/jellyfin-plugin-file-transformation`,554⭐)。 +1. ~~**注入写在容器内文件**(`/jellyfin/jellyfin-web/index.html`)→ `jellyfin/jellyfin:latest` + 一升级就没了~~ —— **已解决**:现在是插件 `Jellyfin.Plugin.JFVR`,在请求时改写 + `index.html`,磁盘上的 web 目录一个字节都不动。见 `plugin/` 和 `pack.py`, + 安装地址 `https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin/raw/branch/main/manifest.json`。 + `deploy.py` 保留作为兜底(两者不要同时用)。 + 剩下的维护成本:Jellyfin 升大版本时可能要重新编译(插件对 `Jellyfin.Controller 12.1.0` / net10.0)。 2. **Three.js 从 CDN 加载**(1.27MB)→ 依赖外网。可改为本地托管。 3. **Quest 浏览器版本会随系统更新变化** → 能力探测(诊断信息里的能力段)是唯一的自检手段。 diff --git a/README.md b/README.md index 52a3fab..9fd4782 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,43 @@ VR180 / VR360 沉浸播放,不用再手动切全屏 + 选投影。 | 备份 | `/vol2/jellyfin/config/_vr_backup/index.html.orig` | | 两个入口都生效 | `http://192.168.123.199:8096/web/` 与 `https://jellyfin.cat-shark.xyz/web/` | -> ⚠️ 注入写在**容器内文件**里,`jellyfin/jellyfin:latest` 一升级就没了,重跑 `deploy.py` 即可。 -> 正式版应改用 **JavaScript Injector 插件**(`n00bcodr/jellyfin-plugins` 的 `12/manifest.json`,targetAbi 12.0.0.0) -> 或 **File Transformation**,这样升级不丢、可开关。 +> ⚠️ 老路子(`deploy.py`):注入写在**容器内文件**里,`jellyfin/jellyfin:latest` 一升级就没了, +> 得重跑 `deploy.py`。**现在已经有插件版了,见下面 §1.1,优先用插件。** + +### 1.1 插件化(推荐,已实现) + +JFVR 同时也是一个标准的 **Jellyfin 插件**,通过自建 Gitea 仓库分发,走 Dashboard 的 +「添加存储库 → Catalog 安装」,**不再改容器内任何文件**。 + +| 项 | 值 | +|---|---| +| 插件仓库地址 | `https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin/raw/branch/main/manifest.json` | +| 插件名 / GUID | `Jellyfin Web VR` / `7d33ef59-f9b0-412b-93bd-5cd5353018de` | +| 目标 ABI | `12.0.0.0`(Jellyfin 只保留 `targetAbi <= 服务器版本` 的条目,所以一份包覆盖整个 12.x) | +| 插件代码 | `plugin/Jellyfin.Plugin.JFVR/`(C#,net10.0,对 `Jellyfin.Controller 12.1.0`) | +| 打包 / 发布 | `python3 pack.py` / `python3 pack.py --bump --publish` | +| 脚本端点 | `/JFVR/jfvr.js`(bundle 内嵌在 DLL 里,URL 带内容哈希做缓存键) | +| 状态查询 | `/JFVR/status` | +| 设置页 | Dashboard → 插件 → Jellyfin Web VR(开关注入 / 覆盖脚本 URL) | + +**安装**:Dashboard → 插件 → 目录 → ⚙️ → ➕ → 粘贴上面的仓库地址 → 保存 → +在 Catalog 里找到 **Jellyfin Web VR** → 安装 → **重启 Jellyfin**。 + +**工作方式**:`ScriptInjectionStartupFilter` 在**请求时**把 +`` +插到 `index.html` 的 `` 之前。磁盘上的 `/jellyfin/jellyfin-web/` 一个字节都不动, +所以升级 Jellyfin 不会丢。如果检测到老 `deploy.py` 留下的 ` + + diff --git a/plugin/Jellyfin.Plugin.JFVR/Controllers/JfvrController.cs b/plugin/Jellyfin.Plugin.JFVR/Controllers/JfvrController.cs new file mode 100644 index 0000000..57d70e9 --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Controllers/JfvrController.cs @@ -0,0 +1,82 @@ +using System; +using System.Threading.Tasks; +using Jellyfin.Plugin.JFVR.Services; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Net.Http.Headers; + +namespace Jellyfin.Plugin.JFVR.Controllers; + +/// +/// Serves the JFVR web bundle and a small status endpoint. +/// +/// The bundle is anonymous on purpose: the injected tag lives in +/// index.html, which the browser fetches before the user has +/// authenticated, and the payload is the same JavaScript that is already public +/// in the project repository. +/// +[ApiController] +[Route("JFVR")] +public class JfvrController : ControllerBase +{ + private readonly BundleProvider _bundle; + + /// + /// Initializes a new instance of the class. + /// + /// Embedded web bundle. + public JfvrController(BundleProvider bundle) + { + _bundle = bundle; + } + + /// + /// Returns the JFVR web bundle. + /// + /// The bundle as JavaScript. + [HttpGet("jfvr.js")] + [AllowAnonymous] + [Produces("application/javascript")] + public ActionResult GetBundle() + { + var etag = "\"" + _bundle.Hash + "\""; + + // The URL is versioned with ?v=, so the body for a given URL never + // changes: it is safe to cache forever, and an update always produces a + // new URL. + Response.Headers[HeaderNames.CacheControl] = "public, max-age=31536000, immutable"; + Response.Headers[HeaderNames.ETag] = etag; + + if (Request.Headers[HeaderNames.IfNoneMatch].ToString().Contains(_bundle.Hash, StringComparison.Ordinal)) + { + return StatusCode(304); + } + + return File(_bundle.Bytes, "application/javascript; charset=utf-8"); + } + + /// + /// Reports which bundle the server is serving and whether injection is on. + /// Handy for verifying a deployment without opening DevTools on the Quest. + /// + /// A small JSON status object. + [HttpGet("status")] + [AllowAnonymous] + public ActionResult GetStatus() + { + var config = Plugin.Instance?.Configuration; + + return new + { + plugin = "Jellyfin.Plugin.JFVR", + version = typeof(Plugin).Assembly.GetName().Version?.ToString() ?? "unknown", + bundleHash = _bundle.Hash, + bundleBytes = _bundle.Bytes.Length, + enabled = config?.Enabled ?? false, + scriptUrlOverride = config?.ScriptUrlOverride ?? string.Empty, + injectedTag = string.IsNullOrWhiteSpace(config?.ScriptUrlOverride) + ? "../JFVR/jfvr.js?v=" + _bundle.Hash + : config!.ScriptUrlOverride.Trim() + }; + } +} diff --git a/plugin/Jellyfin.Plugin.JFVR/Jellyfin.Plugin.JFVR.csproj b/plugin/Jellyfin.Plugin.JFVR/Jellyfin.Plugin.JFVR.csproj new file mode 100644 index 0000000..f8a0c83 --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Jellyfin.Plugin.JFVR.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + Jellyfin.Plugin.JFVR + Jellyfin.Plugin.JFVR + enable + disable + latest + false + false + + + 0.1.0.0 + + + $(MSBuildThisFileDirectory)..\..\dist\jfvr.js + + + + + + + + + + runtime + + + runtime + + + + + + + + + diff --git a/plugin/Jellyfin.Plugin.JFVR/Plugin.cs b/plugin/Jellyfin.Plugin.JFVR/Plugin.cs new file mode 100644 index 0000000..87d8eaa --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Plugin.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using Jellyfin.Plugin.JFVR.Services; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Plugins; +using MediaBrowser.Model.Plugins; +using MediaBrowser.Model.Serialization; + +namespace Jellyfin.Plugin.JFVR; + +/// +/// The JFVR plugin. Owns the identity (GUID + version) that the Jellyfin plugin +/// catalog matches on, and serves the embedded web bundle. +/// +public class Plugin : BasePlugin, IHasWebPages +{ + /// + /// Initializes a new instance of the class. + /// + /// Jellyfin application paths. + /// XML serializer for the configuration. + /// Embedded web bundle. + public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, BundleProvider bundle) + : base(applicationPaths, xmlSerializer) + { + Instance = this; + Bundle = bundle; + } + + /// + /// Gets the current plugin instance. Set by the DI container at startup; + /// the injection middleware reads the configuration through it. + /// + public static Plugin? Instance { get; private set; } + + /// + /// Gets the embedded web bundle. + /// + public BundleProvider Bundle { get; } + + /// + public override string Name => "Jellyfin Web VR"; + + /// + public override Guid Id => Guid.Parse("7d33ef59-f9b0-412b-93bd-5cd5353018de"); + + /// + public override string Description => + "Injects a VR play button into Jellyfin Web so Meta Quest 3 can play VR180/VR360 in WebXR."; + + /// + public IEnumerable GetPages() + { + return new[] + { + new PluginPageInfo + { + Name = "JFVR", + DisplayName = "Jellyfin Web VR", + EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html", + EnableInMainMenu = true, + MenuIcon = "view_in_ar" + } + }; + } +} diff --git a/plugin/Jellyfin.Plugin.JFVR/PluginConfiguration.cs b/plugin/Jellyfin.Plugin.JFVR/PluginConfiguration.cs new file mode 100644 index 0000000..e5e3780 --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/PluginConfiguration.cs @@ -0,0 +1,25 @@ +using MediaBrowser.Model.Plugins; + +namespace Jellyfin.Plugin.JFVR; + +/// +/// JFVR plugin configuration. Persisted by Jellyfin as XML under +/// <config>/plugins/configurations/Jellyfin.Plugin.JFVR.xml, so it +/// survives container recreation and Jellyfin upgrades. +/// +public class PluginConfiguration : BasePluginConfiguration +{ + /// + /// Gets or sets a value indicating whether the plugin rewrites the served + /// index.html. When disabled the response is passed through untouched + /// (the legacy injection, if any, is left alone too) but the bundle endpoint + /// stays reachable. + /// + public bool Enabled { get; set; } = true; + + /// + /// Gets or sets an optional URL used instead of the embedded bundle. Leave + /// empty to serve ../JFVR/jfvr.js?v=<hash> from this plugin. + /// + public string ScriptUrlOverride { get; set; } = string.Empty; +} diff --git a/plugin/Jellyfin.Plugin.JFVR/PluginServiceRegistrator.cs b/plugin/Jellyfin.Plugin.JFVR/PluginServiceRegistrator.cs new file mode 100644 index 0000000..51cd6af --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/PluginServiceRegistrator.cs @@ -0,0 +1,23 @@ +using Jellyfin.Plugin.JFVR.Services; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Plugins; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; + +namespace Jellyfin.Plugin.JFVR; + +/// +/// Registers the plugin's services with the Jellyfin host container. +/// +public class PluginServiceRegistrator : IPluginServiceRegistrator +{ + /// + public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost) + { + serviceCollection.AddSingleton(); + + // The request-time injection path: rewrites jellyfin-web's index.html on + // the way out. Nothing is written to disk. + serviceCollection.AddSingleton(); + } +} diff --git a/plugin/Jellyfin.Plugin.JFVR/Services/BundleProvider.cs b/plugin/Jellyfin.Plugin.JFVR/Services/BundleProvider.cs new file mode 100644 index 0000000..fcbbd5b --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Services/BundleProvider.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using System.Security.Cryptography; + +namespace Jellyfin.Plugin.JFVR.Services; + +/// +/// 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 +/// <script src="../JFVR/jfvr.js?v=HASH"> tag, so a new plugin build +/// always forces browsers to refetch the bundle. It is also the same +/// md5[:6] version string the in-page HUD reports, which makes "which JS +/// is the Quest actually running?" answerable from both sides. +/// +public sealed class BundleProvider +{ + /// + /// Logical name of the embedded resource, set explicitly in the .csproj so it + /// does not depend on the project's folder layout. + /// + internal const string ResourceName = "Jellyfin.Plugin.JFVR.Web.jfvr.js"; + + /// + /// Initializes a new instance of the class. + /// + /// + /// Thrown when the bundle was not embedded, which means the build is broken. + /// + 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]; + } + + /// + /// Gets the raw bundle bytes. + /// + public byte[] Bytes { get; } + + /// + /// Gets the short (8 hex chars) MD5 of . + /// + public string Hash { get; } +} diff --git a/plugin/Jellyfin.Plugin.JFVR/Services/IndexHtmlRewriter.cs b/plugin/Jellyfin.Plugin.JFVR/Services/IndexHtmlRewriter.cs new file mode 100644 index 0000000..40f575e --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Services/IndexHtmlRewriter.cs @@ -0,0 +1,97 @@ +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( + "]*plugin=\"JellyfinVR\"[^>]*>\\s*\\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("", StringComparison.OrdinalIgnoreCase); + if (bodyClose < 0) + { + return cleaned; + } + + return cleaned[..bodyClose] + BuildBlock(scriptUrl) + "\n" + cleaned[bodyClose..]; + } +} diff --git a/plugin/Jellyfin.Plugin.JFVR/Services/ScriptInjectionStartupFilter.cs b/plugin/Jellyfin.Plugin.JFVR/Services/ScriptInjectionStartupFilter.cs new file mode 100644 index 0000000..383bd97 --- /dev/null +++ b/plugin/Jellyfin.Plugin.JFVR/Services/ScriptInjectionStartupFilter.cs @@ -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; + +/// +/// Injects the JFVR <script> tag into jellyfin-web's index.html at +/// request time, through ASP.NET Core middleware registered via +/// . +/// +/// Why request-time rewriting instead of the old deploy.py approach (which +/// sed-patched /jellyfin/jellyfin-web/index.html inside the +/// container): +/// - nothing on disk is modified, so a jellyfin/jellyfin:latest 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. +/// +public sealed class ScriptInjectionStartupFilter : IStartupFilter +{ + private readonly BundleProvider _bundle; + private readonly ILogger _logger; + private int _loggedOnce; + + /// + /// Initializes a new instance of the class. + /// + /// Embedded web bundle. + /// Logger. + public ScriptInjectionStartupFilter(BundleProvider bundle, ILogger logger) + { + _bundle = bundle; + _logger = logger; + } + + /// + public Action Configure(Action 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 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