3 Commits
Author SHA1 Message Date
cat-shark ac85de2cb8 plugin: publish 0.1.0.0 (bundle 917fde) 2026-10-17 23:25:43 +08:00
cat-shark 7e25861498 plugin: publish 0.1.0.0 (bundle 917fde) 2026-10-17 23:25:01 +08:00
cat-shark f4fe3d61fc 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.
2026-10-17 23:17:00 +08:00
15 changed files with 1256 additions and 9 deletions
+6
View File
@@ -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/
+15 -6
View File
@@ -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='<NAS 密码>'
python3 deploy.py
@@ -401,7 +407,8 @@ python3 deploy.py --legacy
./quest.sh
```
**部署后必须让用户刷新页面**(脚本按页面加载缓存,URL 里的 `?r=<md5前6位>` 是破缓存用的)。
**插件路线**:Jellyfin 里点更新/重装 → 重启 → 刷新浏览器。
**老路线**:部署后必须让用户刷新页面(脚本按页面加载缓存,URL 里的 `?r=<md5前6位>` 是破缓存用的)。
### 诊断信息
@@ -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 浏览器版本会随系统更新变化** → 能力探测(诊断信息里的能力段)是唯一的自检手段。
+48 -3
View File
@@ -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` 在**请求时**把
`<script plugin="JFVR" src="../JFVR/jfvr.js?v=<hash>" defer></script>`
插到 `index.html` 的 `</body>` 之前。磁盘上的 `/jellyfin/jellyfin-web/` 一个字节都不动,
所以升级 Jellyfin 不会丢。如果检测到老 `deploy.py` 留下的 `<script plugin="JellyfinVR" ...>`,
会**自动清掉**,不会重复加载 bundle。
**改完 web 代码后的流程**:
```bash
python3 pack.py --bump --publish # 构建 → 打包 → 建 Release → 推 manifest
# 然后在 Jellyfin 里:插件页点更新(或重装),重启,刷新浏览器
```
> 老路子仍然可用,作为插件的兜底:`JF_PW=... python3 deploy.py`。
> 但**两者不要同时开** —— 装了插件就别再跑 `deploy.py`(跑完插件也会把那个标签清掉)。
---
@@ -255,6 +289,16 @@ WebXR 规范原文:
## 8. 修改 / 部署 / 回滚
### 8.1 插件(推荐)
```bash
python3 pack.py --bump --publish # 构建 + 打包 + 建 Release + 推 manifest.json
```
然后在 Jellyfin 里更新插件并重启,刷新浏览器。
### 8.2 老路子:直接注入容器内文件(兜底)
```bash
# 改 jfvr-mvp.js 后重新部署
JF_PW='<ssh密码>' python3 deploy.py
@@ -264,6 +308,7 @@ JF_PW='<ssh密码>' python3 deploy.py rollback
```
`deploy.py` 用文件 md5 前 6 位作为版本号写进 script 标签的 query,自动破缓存。
插件走的是同一套破缓存思路,只是 hash 由 DLL 内嵌 bundle 的 md5 算出来。
---
+20
View File
@@ -0,0 +1,20 @@
[
{
"name": "Jellyfin Web VR",
"guid": "7d33ef59-f9b0-412b-93bd-5cd5353018de",
"overview": "VR180/VR360 playback inside Jellyfin Web for Meta Quest 3.",
"description": "Injects a \"VR 播放\" button into the Jellyfin Web video player page and drives an immersive WebXR session on Meta Quest 3, preferring XRMediaBinding.createEquirectLayer and falling back to XRWebGLBinding. Ships equirectangular 180/360 plus SBS/OU layouts, in-headset subtitles, a wrist controller, and hand tracking.\n",
"owner": "cat-shark",
"category": "General",
"versions": [
{
"version": "0.1.0.0",
"targetAbi": "12.0.0.0",
"changelog": "Bundle version: `917fde`\n\nFirst plugin build. The web bundle is embedded in the DLL and served from /JFVR/jfvr.js; index.html is rewritten at request time, so nothing is written to the jellyfin-web folder on disk.",
"sourceUrl": "https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin/releases/download/v0.1.0.0/Jellyfin.Plugin.JFVR_12.0.0.0.zip",
"checksum": "F9CC1843F0B9386A9E990669112FF533",
"timestamp": "2026-10-17T15:25:41"
}
]
}
]
+412
View File
@@ -0,0 +1,412 @@
#!/usr/bin/env python3
"""
Build the JFVR Jellyfin plugin, package it the way Jellyfin expects, and
(optionally) publish it to the Gitea repo that doubles as the plugin catalog.
What it does, in order:
1. build.py src/*.js -> dist/jfvr.js
2. dotnet build plugin/Jellyfin.Plugin.JFVR -> Jellyfin.Plugin.JFVR.dll
(the bundle is embedded straight from dist/jfvr.js)
3. verify the DLL really contains the bytes we just built
4. zip one DLL, named <assembly>_<targetAbi>.zip
5. manifest.json add/replace this version's entry (MD5 = the zip's MD5,
which Jellyfin re-checks at install time)
6. --publish create the Gitea release, upload the zip, push the
manifest so Jellyfin can see it
Usage:
python3 pack.py # build + package + update manifest.json
python3 pack.py --bump # same, after bumping the last version field
python3 pack.py --version 0.2.0.0 # same, with an explicit version
python3 pack.py --publish # ... and publish to Gitea
python3 pack.py --print-urls # just show the catalog URL
Env:
GITEA_TOKEN required by --publish. Scope: write:repository.
Falls back to a GITEA_TOKEN line in secrets.local.md.
GITEA_URL default https://git.cat-shark.xyz
GITEA_REPO default cat-shark/jellyfin_vr_web_plugin
GITEA_BRANCH default main
DOTNET path to the dotnet binary (default: $PATH, then ~/.dotnet/dotnet)
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
import zipfile
from datetime import datetime, timezone
import yaml
HERE = os.path.dirname(os.path.abspath(__file__))
PLUGIN_DIR = os.path.join(HERE, "plugin")
BUILD_YAML = os.path.join(PLUGIN_DIR, "build.yaml")
PROJECT = os.path.join(PLUGIN_DIR, "Jellyfin.Plugin.JFVR", "Jellyfin.Plugin.JFVR.csproj")
BUNDLE = os.path.join(HERE, "dist", "jfvr.js")
OUT_DIR = os.path.join(HERE, "dist", "plugin")
MANIFEST = os.path.join(HERE, "manifest.json")
SECRETS = os.path.join(HERE, "secrets.local.md")
ASSEMBLY = "Jellyfin.Plugin.JFVR"
MAX_VERSIONS = 20
GITEA_URL = os.environ.get("GITEA_URL", "https://git.cat-shark.xyz").rstrip("/")
GITEA_REPO = os.environ.get("GITEA_REPO", "cat-shark/jellyfin_vr_web_plugin")
GITEA_BRANCH = os.environ.get("GITEA_BRANCH", "main")
# ---------------------------------------------------------------- helpers
def run(cmd, **kw):
"""Run a command, echo it, and abort on failure."""
print("$ " + " ".join(cmd))
r = subprocess.run(cmd, capture_output=True, text=True, **kw)
if r.stdout.strip():
print(r.stdout.rstrip())
if r.returncode != 0:
print(r.stderr.rstrip(), file=sys.stderr)
sys.exit("command failed: %s" % cmd[0])
if r.stderr.strip():
print(r.stderr.rstrip(), file=sys.stderr)
return r
def dotnet_bin():
explicit = os.environ.get("DOTNET")
if explicit:
return explicit
found = shutil.which("dotnet")
if found:
return found
local = os.path.expanduser("~/.dotnet/dotnet")
if os.path.exists(local):
return local
sys.exit("dotnet not found. Install the .NET 10 SDK, or set DOTNET=/path/to/dotnet")
def md5_of(path):
h = hashlib.md5()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest().upper()
def bundle_version():
"""The 6-char version the in-page HUD reports (build.py uses the same rule)."""
with open(BUNDLE, "rb") as fh:
return hashlib.md5(fh.read()).hexdigest()[:6]
def read_build_yaml():
with open(BUILD_YAML, encoding="utf-8") as fh:
return yaml.safe_load(fh)
def bump(version):
parts = version.split(".")
while len(parts) < 4:
parts.append("0")
parts[-1] = str(int(parts[-1]) + 1)
return ".".join(parts)
def write_build_yaml_version(version):
with open(BUILD_YAML, encoding="utf-8") as fh:
text = fh.read()
text = re.sub(r'^version:\s*".*?"', 'version: "%s"' % version, text, count=1, flags=re.M)
with open(BUILD_YAML, "w", encoding="utf-8") as fh:
fh.write(text)
def catalog_url():
return "%s/%s/raw/branch/%s/manifest.json" % (GITEA_URL, GITEA_REPO, GITEA_BRANCH)
def source_url(tag, asset):
return "%s/%s/releases/download/%s/%s" % (GITEA_URL, GITEA_REPO, tag, asset)
# ---------------------------------------------------------------- gitea
def gitea_token():
token = os.environ.get("GITEA_TOKEN")
if token:
return token.strip()
if os.path.exists(SECRETS):
with open(SECRETS, encoding="utf-8") as fh:
for line in fh:
m = re.match(r"^\s*GITEA_TOKEN\s*[:=]\s*(\S+)", line)
if m:
return m.group(1)
sys.exit(
"--publish needs a Gitea token.\n"
"Create one at %s/user/settings/applications (scope: write:repository)\n"
"then export GITEA_TOKEN=... or add a 'GITEA_TOKEN: ...' line to secrets.local.md"
% GITEA_URL
)
def gitea_request(method, path, token, body=None, ctype="application/json"):
url = "%s/api/v1%s" % (GITEA_URL, path)
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", "token " + token)
req.add_header("Content-Type", ctype)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
raw = resp.read()
return resp.status, (json.loads(raw) if raw else None)
except urllib.error.HTTPError as e:
raw = e.read()
try:
return e.code, json.loads(raw)
except Exception:
return e.code, raw.decode("utf-8", "replace")
def multipart(fields, files):
boundary = "----JFVR" + uuid.uuid4().hex
out = bytearray()
for key, value in fields.items():
out += ('--%s\r\nContent-Disposition: form-data; name="%s"\r\n\r\n%s\r\n'
% (boundary, key, value)).encode()
for key, (filename, data, ctype) in files.items():
out += ('--%s\r\nContent-Disposition: form-data; name="%s"; filename="%s"\r\n'
'Content-Type: %s\r\n\r\n' % (boundary, key, filename, ctype)).encode()
out += data + b"\r\n"
out += ("--%s--\r\n" % boundary).encode()
return bytes(out), "multipart/form-data; boundary=%s" % boundary
def publish(tag, meta, zip_path, asset_name, changelog, token):
path = "/repos/%s/releases/tags/%s" % (GITEA_REPO, tag)
status, release = gitea_request("GET", path, token)
if status == 200:
print("release %s already exists (id %s)" % (tag, release["id"]))
else:
status, release = gitea_request("POST", "/repos/%s/releases" % GITEA_REPO, token, {
"tag_name": tag,
"name": "%s %s" % (meta["name"], tag),
"body": changelog,
"draft": False,
"prerelease": False,
})
if status not in (200, 201):
sys.exit("creating release %s failed (%s): %s" % (tag, status, release))
print("created release %s (id %s)" % (tag, release["id"]))
release_id = release["id"]
for asset in release.get("assets") or []:
if asset["name"] == asset_name:
gitea_request("DELETE",
"/repos/%s/releases/%s/assets/%s" % (GITEA_REPO, release_id, asset["id"]),
token)
print("replaced existing asset %s" % asset_name)
with open(zip_path, "rb") as fh:
payload, ctype = multipart({}, {"attachment": (asset_name, fh.read(), "application/zip")})
url = "%s/api/v1/repos/%s/releases/%s/assets?name=%s" % (GITEA_URL, GITEA_REPO, release_id, asset_name)
req = urllib.request.Request(url, data=payload, method="POST")
req.add_header("Authorization", "token " + token)
req.add_header("Content-Type", ctype)
try:
with urllib.request.urlopen(req, timeout=300) as resp:
json.loads(resp.read())
except urllib.error.HTTPError as e:
sys.exit("uploading %s failed (%s): %s" % (asset_name, e.code, e.read().decode("utf-8", "replace")))
print("uploaded %s" % asset_name)
def head_ok(url):
"""A draft release 404s on its download URL; verify the asset is really live."""
req = urllib.request.Request(url, method="HEAD")
try:
with urllib.request.urlopen(req, timeout=60) as resp:
return resp.status, resp.headers.get("Content-Length")
except urllib.error.HTTPError as e:
return e.code, None
# ---------------------------------------------------------------- steps
def build_bundle():
run([sys.executable, os.path.join(HERE, "build.py")], cwd=HERE)
def build_plugin(version):
env = dict(os.environ)
dotnet = dotnet_bin()
env["DOTNET_ROOT"] = os.path.dirname(dotnet)
env["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"
env["DOTNET_NOLOGO"] = "1"
run([dotnet, "build", PROJECT, "-c", "Release", "-p:Version=" + version], cwd=HERE, env=env)
dll = os.path.join(os.path.dirname(PROJECT), "bin", "Release", "net10.0", ASSEMBLY + ".dll")
if not os.path.exists(dll):
sys.exit("expected build output missing: %s" % dll)
return dll
def verify_embedded(dll):
"""Guard against shipping a DLL whose embedded bundle is not what we built."""
with open(dll, "rb") as fh:
blob = fh.read()
with open(BUNDLE, "rb") as fh:
bundle = fh.read()
at = blob.find(bundle)
if at < 0:
sys.exit("the built DLL does not contain dist/jfvr.js -- refusing to package")
if int.from_bytes(blob[at - 4:at], "little") != len(bundle):
sys.exit("embedded bundle length prefix mismatch -- refusing to package")
print("verified: DLL embeds %d bytes of dist/jfvr.js (md5 %s)" % (len(bundle), bundle_version()))
def make_zip(dll, target_abi):
os.makedirs(OUT_DIR, exist_ok=True)
asset = "%s_%s.zip" % (ASSEMBLY, target_abi)
path = os.path.join(OUT_DIR, asset)
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf:
zf.write(dll, ASSEMBLY + ".dll")
print("packaged %s (%d bytes)" % (path, os.path.getsize(path)))
return path, asset
def update_manifest(meta, version, asset, checksum, changelog):
if os.path.exists(MANIFEST):
with open(MANIFEST, encoding="utf-8") as fh:
manifest = json.load(fh)
else:
manifest = []
package = next((p for p in manifest if p.get("guid") == meta["guid"]), None)
if package is None:
package = {
"name": meta["name"],
"guid": meta["guid"],
"overview": meta["overview"],
"description": meta["description"],
"owner": meta["owner"],
"category": meta["category"],
"versions": [],
}
if meta.get("imageUrl"):
package["imageUrl"] = meta["imageUrl"]
manifest.append(package)
for key in ("name", "overview", "description", "owner", "category"):
package[key] = meta[key]
entry = {
"version": version,
"targetAbi": meta["targetAbi"],
"changelog": changelog,
"sourceUrl": source_url("v" + version, asset),
"checksum": checksum,
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S"),
}
package["versions"] = [v for v in package["versions"] if v.get("version") != version]
package["versions"].insert(0, entry)
package["versions"] = package["versions"][:MAX_VERSIONS]
with open(MANIFEST, "w", encoding="utf-8") as fh:
json.dump(manifest, fh, indent=2, ensure_ascii=False)
fh.write("\n")
return entry
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--version", help="plugin version, e.g. 0.2.0.0")
ap.add_argument("--bump", action="store_true", help="bump the last version component")
ap.add_argument("--publish", action="store_true", help="create the Gitea release and upload the zip")
ap.add_argument("--no-push", action="store_true", help="with --publish: skip git commit/push")
ap.add_argument("--print-urls", action="store_true", help="print the catalog URL and exit")
args = ap.parse_args()
if args.print_urls:
print("Jellyfin plugin repository URL:")
print(" " + catalog_url())
return
meta = read_build_yaml()
if args.version:
version = args.version
write_build_yaml_version(version)
elif args.bump:
version = bump(meta["version"])
write_build_yaml_version(version)
meta = read_build_yaml()
else:
version = meta["version"]
print("=" * 72)
print("JFVR plugin %s (targetAbi %s)" % (version, meta["targetAbi"]))
print("=" * 72)
build_bundle()
js_ver = bundle_version()
dll = build_plugin(version)
verify_embedded(dll)
zip_path, asset = make_zip(dll, meta["targetAbi"])
checksum = md5_of(zip_path)
print("zip md5: %s" % checksum)
changelog = (meta.get("changelog") or "").strip()
changelog = "Bundle version: `%s`\n\n%s" % (js_ver, changelog)
entry = update_manifest(meta, version, asset, checksum, changelog)
print("manifest.json updated: %s" % entry["sourceUrl"])
if args.publish:
token = gitea_token()
publish("v" + version, meta, zip_path, asset, changelog, token)
status, length = head_ok(entry["sourceUrl"])
print("asset check: HTTP %s, %s bytes" % (status, length))
if status != 200:
sys.exit("the asset is not downloadable -- is the release a draft?")
if not args.no_push:
run(["git", "add", "manifest.json", "plugin/build.yaml"], cwd=HERE)
dirty = subprocess.run(
["git", "diff", "--cached", "--quiet", "--", "manifest.json", "plugin/build.yaml"],
cwd=HERE,
).returncode != 0
if dirty:
run(["git", "commit", "-m", "plugin: publish %s (bundle %s)" % (version, js_ver)], cwd=HERE)
else:
print("manifest.json unchanged -- nothing to commit")
run(["git", "push", "origin", GITEA_BRANCH], cwd=HERE)
else:
print("--no-push: push manifest.json yourself, Jellyfin reads it from the branch")
print()
print("=" * 72)
print("Jellyfin plugin repository URL:")
print(" " + catalog_url())
print()
print("Bundle (in-page HUD version): %s" % js_ver)
print("Install: Dashboard > Plugins > Catalog > gear > + > paste the URL above.")
if not args.publish:
print("Then: python3 pack.py --publish (creates the release and pushes the manifest)")
if __name__ == "__main__":
main()
@@ -0,0 +1,129 @@
<!DOCTYPE html>
<html>
<head>
<title>Jellyfin Web VR</title>
</head>
<body>
<div id="JfvrConfigPage" data-role="page" class="page type-interior pluginConfigurationPage">
<div data-role="content">
<div class="content-primary">
<form id="JfvrConfigForm">
<div class="verticalSection">
<div class="sectionTitleContainer flex align-items-center">
<h2 class="sectionTitle">Jellyfin Web VR</h2>
<a is="emby-linkbutton" class="raised raised-mini emby-button" style="margin-left:2em"
target="_blank" rel="noopener"
href="https://git.cat-shark.xyz/cat-shark/jellyfin_vr_web_plugin">
<i class="md-icon button-icon button-icon-left secondaryText"></i>
<span>Help</span>
</a>
</div>
<p class="fieldDescription">
在 jellyfin-web 的 <code>index.html</code> 里注入 VR 播放脚本,让 Quest 3
浏览器直接进入 VR180 / VR360 沉浸播放。改写发生在请求时,磁盘上的文件不会被改动,
所以 Jellyfin 升级不会丢掉注入。
</p>
<p class="fieldDescription">
<strong>改完设置后需要刷新浏览器</strong>(<code>index.html</code> 本身没有强缓存,
普通刷新即可)。
</p>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="chkEnabled" />
<span>启用注入</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
关闭后 <code>index.html</code> 原样返回,不再注入;脚本端点仍然可以访问。
</div>
</div>
<div class="inputContainer">
<input is="emby-input" type="text" id="txtScriptUrl" label="脚本 URL 覆盖(可选)" />
<div class="fieldDescription">
留空则使用插件内置的 bundle:<code id="builtinUrl">/JFVR/jfvr.js</code>。
填了就注入这个 URL(例如自建 CDN 上的副本),内置 bundle 不再使用。
</div>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block">
<span>保存</span>
</button>
</div>
<div class="verticalSection" style="margin-top:1.5em">
<h3 class="sectionTitle" style="font-size:1.1em">状态</h3>
<div id="statusBox" class="fieldDescription">读取中…</div>
</div>
</form>
</div>
</div>
</div>
<script>
(function () {
'use strict';
var PLUGIN_ID = '7d33ef59-f9b0-412b-93bd-5cd5353018de';
function statusLine(label, value) {
return '<div><strong>' + label + ':</strong> ' + value + '</div>';
}
function renderStatus() {
var box = document.querySelector('#statusBox');
var url;
try {
url = ApiClient.getUrl('JFVR/status');
} catch (err) {
url = '/JFVR/status';
}
ApiClient.ajax({ type: 'GET', url: url, dataType: 'json' }).then(function (s) {
box.innerHTML =
statusLine('插件版本', s.version) +
statusLine('bundle 版本', s.bundleHash + '(' + s.bundleBytes + ' bytes)') +
statusLine('注入', s.enabled ? '已启用' : '已关闭') +
statusLine('注入的 URL', '<code>' + s.injectedTag + '</code>');
}).catch(function () {
box.textContent = '无法读取 /JFVR/status(插件可能尚未加载完成)。';
});
}
function loadConfiguration() {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(PLUGIN_ID).then(function (config) {
document.querySelector('#chkEnabled').checked = config.Enabled !== false;
document.querySelector('#txtScriptUrl').value = config.ScriptUrlOverride || '';
Dashboard.hideLoadingMsg();
renderStatus();
});
}
function saveConfiguration(e) {
e.preventDefault();
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(PLUGIN_ID).then(function (config) {
config.Enabled = document.querySelector('#chkEnabled').checked;
config.ScriptUrlOverride = document.querySelector('#txtScriptUrl').value || '';
ApiClient.updatePluginConfiguration(PLUGIN_ID, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
renderStatus();
});
});
return false;
}
document.querySelector('#JfvrConfigForm').addEventListener('submit', saveConfiguration);
document.addEventListener('pageshow', function (e) {
if (e.target.id === 'JfvrConfigPage') {
loadConfiguration();
}
});
})();
</script>
</body>
</html>
@@ -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;
/// <summary>
/// Serves the JFVR web bundle and a small status endpoint.
///
/// The bundle is anonymous on purpose: the injected tag lives in
/// <c>index.html</c>, which the browser fetches before the user has
/// authenticated, and the payload is the same JavaScript that is already public
/// in the project repository.
/// </summary>
[ApiController]
[Route("JFVR")]
public class JfvrController : ControllerBase
{
private readonly BundleProvider _bundle;
/// <summary>
/// Initializes a new instance of the <see cref="JfvrController"/> class.
/// </summary>
/// <param name="bundle">Embedded web bundle.</param>
public JfvrController(BundleProvider bundle)
{
_bundle = bundle;
}
/// <summary>
/// Returns the JFVR web bundle.
/// </summary>
/// <returns>The bundle as JavaScript.</returns>
[HttpGet("jfvr.js")]
[AllowAnonymous]
[Produces("application/javascript")]
public ActionResult GetBundle()
{
var etag = "\"" + _bundle.Hash + "\"";
// The URL is versioned with ?v=<hash>, 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");
}
/// <summary>
/// Reports which bundle the server is serving and whether injection is on.
/// Handy for verifying a deployment without opening DevTools on the Quest.
/// </summary>
/// <returns>A small JSON status object.</returns>
[HttpGet("status")]
[AllowAnonymous]
public ActionResult<object> 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()
};
}
}
@@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Jellyfin.Plugin.JFVR</RootNamespace>
<AssemblyName>Jellyfin.Plugin.JFVR</AssemblyName>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
<!-- Overridden by pack.py from plugin/build.yaml (dotnet build -p:Version=...). -->
<Version>0.1.0.0</Version>
<!--
Single source of truth for the injected bundle. dist/jfvr.js is produced by
build.py from src/*.js; embedding it straight from there (instead of copying
it into the project) means the DLL can never ship a stale bundle.
-->
<JfvrBundlePath>$(MSBuildThisFileDirectory)..\..\dist\jfvr.js</JfvrBundlePath>
</PropertyGroup>
<Target Name="JfvrCheckBundle" BeforeTargets="PrepareForBuild">
<Error
Condition="!Exists('$(JfvrBundlePath)')"
Text="dist/jfvr.js is missing. Run 'python3 build.py' first (pack.py does this for you)." />
</Target>
<ItemGroup>
<!--
ExcludeAssets=runtime is required: Jellyfin provides these at runtime, and
copying them into the plugin folder prevents the plugin from registering.
-->
<PackageReference Include="Jellyfin.Controller" Version="12.1.0">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
<PackageReference Include="Jellyfin.Model" Version="12.1.0">
<ExcludeAssets>runtime</ExcludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="$(JfvrBundlePath)" LogicalName="Jellyfin.Plugin.JFVR.Web.jfvr.js" />
<EmbeddedResource Include="Configuration\configPage.html" LogicalName="Jellyfin.Plugin.JFVR.Configuration.configPage.html" />
</ItemGroup>
</Project>
+66
View File
@@ -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;
/// <summary>
/// The JFVR plugin. Owns the identity (GUID + version) that the Jellyfin plugin
/// catalog matches on, and serves the embedded web bundle.
/// </summary>
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
/// <summary>
/// Initializes a new instance of the <see cref="Plugin"/> class.
/// </summary>
/// <param name="applicationPaths">Jellyfin application paths.</param>
/// <param name="xmlSerializer">XML serializer for the configuration.</param>
/// <param name="bundle">Embedded web bundle.</param>
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, BundleProvider bundle)
: base(applicationPaths, xmlSerializer)
{
Instance = this;
Bundle = bundle;
}
/// <summary>
/// Gets the current plugin instance. Set by the DI container at startup;
/// the injection middleware reads the configuration through it.
/// </summary>
public static Plugin? Instance { get; private set; }
/// <summary>
/// Gets the embedded web bundle.
/// </summary>
public BundleProvider Bundle { get; }
/// <inheritdoc />
public override string Name => "Jellyfin Web VR";
/// <inheritdoc />
public override Guid Id => Guid.Parse("7d33ef59-f9b0-412b-93bd-5cd5353018de");
/// <inheritdoc />
public override string Description =>
"Injects a VR play button into Jellyfin Web so Meta Quest 3 can play VR180/VR360 in WebXR.";
/// <inheritdoc />
public IEnumerable<PluginPageInfo> GetPages()
{
return new[]
{
new PluginPageInfo
{
Name = "JFVR",
DisplayName = "Jellyfin Web VR",
EmbeddedResourcePath = GetType().Namespace + ".Configuration.configPage.html",
EnableInMainMenu = true,
MenuIcon = "view_in_ar"
}
};
}
}
@@ -0,0 +1,25 @@
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.JFVR;
/// <summary>
/// JFVR plugin configuration. Persisted by Jellyfin as XML under
/// <c>&lt;config&gt;/plugins/configurations/Jellyfin.Plugin.JFVR.xml</c>, so it
/// survives container recreation and Jellyfin upgrades.
/// </summary>
public class PluginConfiguration : BasePluginConfiguration
{
/// <summary>
/// Gets or sets a value indicating whether the plugin rewrites the served
/// <c>index.html</c>. When disabled the response is passed through untouched
/// (the legacy injection, if any, is left alone too) but the bundle endpoint
/// stays reachable.
/// </summary>
public bool Enabled { get; set; } = true;
/// <summary>
/// Gets or sets an optional URL used instead of the embedded bundle. Leave
/// empty to serve <c>../JFVR/jfvr.js?v=&lt;hash&gt;</c> from this plugin.
/// </summary>
public string ScriptUrlOverride { get; set; } = string.Empty;
}
@@ -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;
/// <summary>
/// Registers the plugin's services with the Jellyfin host container.
/// </summary>
public class PluginServiceRegistrator : IPluginServiceRegistrator
{
/// <inheritdoc />
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
{
serviceCollection.AddSingleton<BundleProvider>();
// The request-time injection path: rewrites jellyfin-web's index.html on
// the way out. Nothing is written to disk.
serviceCollection.AddSingleton<IStartupFilter, ScriptInjectionStartupFilter>();
}
}
@@ -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>&lt;script src="../JFVR/jfvr.js?v=HASH"&gt;</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>&lt;script plugin="JellyfinVR" ... src="jfvr-mvp.js?v=..."&gt;&lt;/script&gt;</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>&lt;/body&gt;</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>&lt;/body&gt;</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>&lt;script&gt;</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);
}
}
+27
View File
@@ -0,0 +1,27 @@
---
# Metadata for the Jellyfin plugin catalog entry. pack.py reads this file to
# build manifest.json, and passes `version` to dotnet as -p:Version.
#
# targetAbi is deliberately 12.0.0.0 rather than the exact server version:
# Jellyfin keeps a catalog version only when `targetAbi <= serverVersion`
# (InstallationManager.GetAvailablePackages), so one package covers all of 12.x.
name: "Jellyfin Web VR"
guid: "7d33ef59-f9b0-412b-93bd-5cd5353018de"
version: "0.1.0.0"
targetAbi: "12.0.0.0"
framework: "net10.0"
overview: "VR180/VR360 playback inside Jellyfin Web for Meta Quest 3."
description: >
Injects a "VR 播放" button into the Jellyfin Web video player page and drives
an immersive WebXR session on Meta Quest 3, preferring
XRMediaBinding.createEquirectLayer and falling back to XRWebGLBinding.
Ships equirectangular 180/360 plus SBS/OU layouts, in-headset subtitles,
a wrist controller, and hand tracking.
category: "General"
owner: "cat-shark"
artifacts:
- "Jellyfin.Plugin.JFVR.dll"
changelog: >
First plugin build. The web bundle is embedded in the DLL and served from
/JFVR/jfvr.js; index.html is rewritten at request time, so nothing is written
to the jellyfin-web folder on disk.