Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d70d7166d | ||
|
|
5331f0faf1 | ||
|
|
0508188705 | ||
|
|
cc861f4263 | ||
|
|
10e6cdc4a2 | ||
|
|
a8c7faab6b | ||
|
|
6df390fa18 | ||
|
|
d0c3d7ee4d | ||
|
|
bc621aacdf | ||
|
|
73eb30d671 | ||
|
|
2cfbec95c9 | ||
|
|
08fc29cba3 | ||
|
|
0d6b835486 | ||
|
|
bf620e447f | ||
|
|
3117d627dd | ||
|
|
71402f7e86 | ||
|
|
cce202b88d | ||
|
|
1d334e4d95 | ||
|
|
142063ce63 | ||
|
|
1a0050ae1a | ||
|
|
46ebfdbafc | ||
|
|
14d2bb957b | ||
|
|
7a0c1e4488 | ||
|
|
ec0e686e00 | ||
|
|
54395896b3 | ||
|
|
8b2fe59f5a | ||
|
|
a44bf7ebf4 | ||
|
|
1f273906bf | ||
|
|
0534d0458e | ||
|
|
8b0d6f137d | ||
|
|
2208b86a47 | ||
|
|
5a1048687c |
246
Injector_new.cs
Normal file
246
Injector_new.cs
Normal file
@@ -0,0 +1,246 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Loader;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using Jellyfin.Plugin.MediaBarEnhanced.Helpers;
|
||||
|
||||
namespace Jellyfin.Plugin.MediaBarEnhanced
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the injection of the MediaBarEnhanced script into the Jellyfin web interface.
|
||||
/// </summary>
|
||||
public class ScriptInjector
|
||||
{
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly ILogger<ScriptInjector> _logger;
|
||||
public const string ScriptTag = "<script src=\"../MediaBarEnhanced/Resources/mediaBarEnhanced.js\" defer></script>";
|
||||
public const string CssTag = "<link rel=\"stylesheet\" href=\"../MediaBarEnhanced/Resources/mediaBarEnhanced.css\" />";
|
||||
public const string ScriptMarker = "</body>";
|
||||
public const string CssMarker = "</head>";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ScriptInjector"/> class.
|
||||
/// </summary>
|
||||
/// <param name="appPaths">The application paths.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public ScriptInjector(IApplicationPaths appPaths, ILogger<ScriptInjector> logger)
|
||||
{
|
||||
_appPaths = appPaths;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Injects the script tag into index.html if it's not already present.
|
||||
/// </summary>
|
||||
public void Inject()
|
||||
{
|
||||
try
|
||||
{
|
||||
var webPath = GetWebPath();
|
||||
if (string.IsNullOrEmpty(webPath))
|
||||
{
|
||||
_logger.LogWarning("Could not find Jellyfin web path. Script injection skipped. Attempting fallback.");
|
||||
RegisterFileTransformation();
|
||||
return;
|
||||
}
|
||||
|
||||
var indexPath = Path.Combine(webPath, "index.html");
|
||||
if (!File.Exists(indexPath))
|
||||
{
|
||||
_logger.LogWarning("index.html not found at {Path}. Script injection skipped. Attempting fallback.", indexPath);
|
||||
RegisterFileTransformation();
|
||||
return;
|
||||
}
|
||||
|
||||
var content = File.ReadAllText(indexPath);
|
||||
var injectedJS = false;
|
||||
var injectedCSS = false;
|
||||
|
||||
if (!content.Contains(ScriptTag))
|
||||
{
|
||||
var index = content.IndexOf(ScriptMarker, StringComparison.OrdinalIgnoreCase);
|
||||
if (index != -1)
|
||||
{
|
||||
content = content.Insert(index, ScriptTag + Environment.NewLine);
|
||||
injectedJS = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!content.Contains(CssTag))
|
||||
{
|
||||
var index = content.IndexOf(CssMarker, StringComparison.OrdinalIgnoreCase);
|
||||
if (index != -1)
|
||||
{
|
||||
content = content.Insert(index, CssTag + Environment.NewLine);
|
||||
injectedCSS = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (injectedJS && injectedCSS)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced script injected into index.html.");
|
||||
} else if (injectedJS)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced JS script injected into index.html. But CSS was already present or could not be injected.");
|
||||
}
|
||||
else if (injectedCSS)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced CSS injected into index.html. But JS script was already present or could not be injected.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced script and CSS already present in index.html. Or could not be injected.");
|
||||
}
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
_logger.LogWarning("Unauthorized access when attempting to inject script into index.html. Automatic injection failed. Attempting fallback now...");
|
||||
RegisterFileTransformation();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error injecting MediaBarEnhanced resources. Attempting fallback.");
|
||||
RegisterFileTransformation();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the script tag from index.html.
|
||||
/// </summary>
|
||||
public void Remove()
|
||||
{
|
||||
UnregisterFileTransformation();
|
||||
|
||||
try
|
||||
{
|
||||
var webPath = GetWebPath();
|
||||
if (string.IsNullOrEmpty(webPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var indexPath = Path.Combine(webPath, "index.html");
|
||||
if (!File.Exists(indexPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var content = File.ReadAllText(indexPath);
|
||||
var modified = false;
|
||||
|
||||
if (content.Contains(ScriptTag))
|
||||
{
|
||||
content = content.Replace(ScriptTag + Environment.NewLine, "").Replace(ScriptTag, "");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (content.Contains(CssTag))
|
||||
{
|
||||
content = content.Replace(CssTag + Environment.NewLine, "").Replace(CssTag, "");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced script removed from index.html.");
|
||||
} else
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced script not found in index.html. No removal necessary.");
|
||||
}
|
||||
}
|
||||
catch (UnauthorizedAccessException uaEx)
|
||||
{
|
||||
_logger.LogError(uaEx, "Unauthorized access when trying to remove MediaBarEnhanced script. Check file permissions.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error removing MediaBarEnhanced script.");
|
||||
}
|
||||
}
|
||||
|
||||
private string? GetWebPath()
|
||||
{
|
||||
var prop = _appPaths.GetType().GetProperty("WebPath", BindingFlags.Instance | BindingFlags.Public);
|
||||
return prop?.GetValue(_appPaths) as string;
|
||||
}
|
||||
|
||||
private void RegisterFileTransformation()
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced Fallback. Registering file transformations.");
|
||||
|
||||
List<JObject> payloads = new List<JObject>();
|
||||
|
||||
{
|
||||
JObject payload = new JObject();
|
||||
payload.Add("id", "0dfac9d7-d898-4944-900b-1c1837707279");
|
||||
payload.Add("fileNamePattern", "index.html");
|
||||
payload.Add("callbackAssembly", GetType().Assembly.FullName);
|
||||
payload.Add("callbackClass", typeof(TransformationPatches).FullName);
|
||||
payload.Add("callbackMethod", nameof(TransformationPatches.IndexHtml));
|
||||
|
||||
payloads.Add(payload);
|
||||
}
|
||||
|
||||
Assembly? fileTransformationAssembly =
|
||||
AssemblyLoadContext.All.SelectMany(x => x.Assemblies).FirstOrDefault(x =>
|
||||
x.FullName?.Contains(".FileTransformation") ?? false);
|
||||
|
||||
if (fileTransformationAssembly != null)
|
||||
{
|
||||
Type? pluginInterfaceType = fileTransformationAssembly.GetType("Jellyfin.Plugin.FileTransformation.PluginInterface");
|
||||
|
||||
if (pluginInterfaceType != null)
|
||||
{
|
||||
foreach (JObject payload in payloads)
|
||||
{
|
||||
pluginInterfaceType.GetMethod("RegisterTransformation")?.Invoke(null, new object?[] { payload });
|
||||
}
|
||||
_logger.LogInformation("File transformations registered successfully.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("FileTransformation plugin found but PluginInterface type missing.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("FileTransformation plugin assembly not found. Fallback failed.");
|
||||
}
|
||||
}
|
||||
|
||||
private void UnregisterFileTransformation()
|
||||
{
|
||||
try
|
||||
{
|
||||
Assembly? fileTransformationAssembly =
|
||||
AssemblyLoadContext.All.SelectMany(x => x.Assemblies).FirstOrDefault(x =>
|
||||
x.FullName?.Contains(".FileTransformation") ?? false);
|
||||
|
||||
if (fileTransformationAssembly != null)
|
||||
{
|
||||
Type? pluginInterfaceType = fileTransformationAssembly.GetType("Jellyfin.Plugin.FileTransformation.PluginInterface");
|
||||
|
||||
if (pluginInterfaceType != null)
|
||||
{
|
||||
Guid id = Guid.Parse("0dfac9d7-d898-4944-900b-1c1837707279");
|
||||
pluginInterfaceType.GetMethod("RemoveTransformation")?.Invoke(null, new object?[] { id });
|
||||
_logger.LogInformation("File transformation unregistered successfully.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Error attempting to unregister file transformation. It might not have been registered.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -241,7 +241,7 @@
|
||||
<span>Start Muted</span>
|
||||
</label>
|
||||
<div class="fieldDescription">Start trailer video playback muted. (Known issue: In the
|
||||
Android/IOS app, backdrop trailers are always muted.)</div>
|
||||
Android/IOS app, backdrop trailers are always muted.)<br><b style="color:#ffcc00">Warning:</b> Disabling this may cause autoplay to fail on certain browsers due to strict autoplay policies.</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label>
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<!-- <TreatWarningsAsErrors>false</TreatWarningsAsErrors> -->
|
||||
<Title>Jellyfin Media Bar Enhanced Plugin</Title>
|
||||
<Authors>CodeDevMLH</Authors>
|
||||
<Version>1.6.6.0</Version>
|
||||
<Version>1.7.0.5</Version>
|
||||
<RepositoryUrl>https://github.com/CodeDevMLH/jellyfin-plugin-media-bar-enhanced</RepositoryUrl>
|
||||
</PropertyGroup>
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ namespace Jellyfin.Plugin.MediaBarEnhanced
|
||||
var content = File.ReadAllText(indexPath);
|
||||
var injectedJS = false;
|
||||
var injectedCSS = false;
|
||||
var modified = false;
|
||||
|
||||
// Cleanup legacy tags first to avoid duplicates or conflicts
|
||||
content = RemoveLegacyTags(content, ref modified);
|
||||
|
||||
|
||||
if (!content.Contains(ScriptTag))
|
||||
{
|
||||
@@ -81,19 +86,26 @@ namespace Jellyfin.Plugin.MediaBarEnhanced
|
||||
}
|
||||
}
|
||||
|
||||
if (injectedJS && injectedCSS)
|
||||
if (injectedJS || injectedCSS || modified)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced script injected into index.html.");
|
||||
} else if (injectedJS)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced JS script injected into index.html. But CSS was already present or could not be injected.");
|
||||
}
|
||||
else if (injectedCSS)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
_logger.LogInformation("MediaBarEnhanced CSS injected into index.html. But JS script was already present or could not be injected.");
|
||||
|
||||
if (injectedJS && injectedCSS)
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced script injected into index.html.");
|
||||
}
|
||||
else if (injectedJS)
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced JS script injected into index.html. But CSS was already present or could not be injected.");
|
||||
}
|
||||
else if (injectedCSS)
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced CSS injected into index.html. But JS script was already present or could not be injected.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("MediaBarEnhanced script and CSS already present. Legacy tags removed if found.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -148,6 +160,9 @@ namespace Jellyfin.Plugin.MediaBarEnhanced
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// Remove legacy tags
|
||||
content = RemoveLegacyTags(content, ref modified);
|
||||
|
||||
if (modified)
|
||||
{
|
||||
File.WriteAllText(indexPath, content);
|
||||
@@ -242,5 +257,33 @@ namespace Jellyfin.Plugin.MediaBarEnhanced
|
||||
_logger.LogWarning(ex, "Error attempting to unregister file transformation. It might not have been registered.");
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// Removes legacy script and css tags from the content.
|
||||
/// </summary>
|
||||
/// <param name="content">The file content.</param>
|
||||
/// <param name="modified">Ref bool to track if changes were made.</param>
|
||||
/// <returns>The modified content.</returns>
|
||||
private string RemoveLegacyTags(string content, ref bool modified)
|
||||
{
|
||||
// Legacy tags (used in versions prior to 1.6.3.0 where paths started with / instead of ../)
|
||||
const string LegacyScriptTag = "<script src=\"/MediaBarEnhanced/Resources/mediaBarEnhanced.js\" defer></script>";
|
||||
const string LegacyCssTag = "<link rel=\"stylesheet\" href=\"/MediaBarEnhanced/Resources/mediaBarEnhanced.css\" />";
|
||||
|
||||
if (content.Contains(LegacyScriptTag))
|
||||
{
|
||||
content = content.Replace(LegacyScriptTag + Environment.NewLine, "").Replace(LegacyScriptTag, "");
|
||||
modified = true;
|
||||
_logger.LogInformation("Legacy MediaBarEnhanced script tag removed.");
|
||||
}
|
||||
|
||||
if (content.Contains(LegacyCssTag))
|
||||
{
|
||||
content = content.Replace(LegacyCssTag + Environment.NewLine, "").Replace(LegacyCssTag, "");
|
||||
modified = true;
|
||||
_logger.LogInformation("Legacy MediaBarEnhanced CSS tag removed.");
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -744,6 +744,7 @@ const SlideUtils = {
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
videoId: videoId,
|
||||
host: 'https://www.youtube-nocookie.com',
|
||||
playerVars: {
|
||||
autoplay: 1,
|
||||
controls: 1,
|
||||
@@ -751,8 +752,15 @@ const SlideUtils = {
|
||||
rel: 0,
|
||||
playsinline: 1,
|
||||
origin: window.location.origin,
|
||||
widget_referrer: window.location.href,
|
||||
enablejsapi: 1
|
||||
},
|
||||
events: {
|
||||
'onReady': (event) => {
|
||||
const iframe = event.target.getIframe();
|
||||
if (iframe) {
|
||||
iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1395,7 +1403,9 @@ const ApiUtils = {
|
||||
|
||||
return {
|
||||
id: trailer.Id,
|
||||
url: `${STATE.jellyfinData.serverAddress}/Videos/${trailer.Id}/stream.mp4?mediaSourceId=${mediaSourceId}&api_key=${STATE.jellyfinData.accessToken}`
|
||||
// static=true forces Jellyfin to direct-stream (no transcoding) which enables
|
||||
// HTTP Range Requests (Accept-Ranges: bytes) — required by Safari for video playback
|
||||
url: `${STATE.jellyfinData.serverAddress}/Videos/${trailer.Id}/stream.mp4?mediaSourceId=${mediaSourceId}&api_key=${STATE.jellyfinData.accessToken}&static=true`
|
||||
};
|
||||
}
|
||||
return null;
|
||||
@@ -1723,133 +1733,249 @@ const SlideCreator = {
|
||||
// Create container for YouTube API
|
||||
const videoClass = CONFIG.fullWidthVideo ? "video-backdrop-full" : "video-backdrop-default";
|
||||
|
||||
// Create a wrapper for opacity transition
|
||||
videoBackdrop = SlideUtils.createElement("div", {
|
||||
className: `backdrop video-backdrop ${videoClass}`,
|
||||
id: `youtube-player-${itemId}`
|
||||
className: `backdrop video-backdrop ${videoClass}`,
|
||||
style: "opacity: 0; transition: opacity 1.2s ease-in-out;"
|
||||
});
|
||||
|
||||
// Initialize YouTube Player
|
||||
SlideUtils.loadYouTubeIframeAPI().then(() => {
|
||||
// Fetch SponsorBlock data
|
||||
// Detect Safari/WebKit — the YouTube IFrame API causes Error 153 on WebKit
|
||||
// due to cross-origin postMessage restrictions. Use a plain iframe embed instead.
|
||||
const isSafariWebKit = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/Chromium/.test(navigator.userAgent);
|
||||
|
||||
if (isSafariWebKit) {
|
||||
// ── Safari: plain iframe embed ───────────────────────────────────────────
|
||||
// Fetch SponsorBlock data and apply as URL params (start= / end=)
|
||||
ApiUtils.fetchSponsorBlockData(videoId).then(segments => {
|
||||
const playerVars = {
|
||||
autoplay: 0,
|
||||
mute: STATE.slideshow.isMuted ? 1 : 0,
|
||||
controls: 0,
|
||||
disablekb: 1,
|
||||
fs: 0,
|
||||
iv_load_policy: 3,
|
||||
rel: 0,
|
||||
loop: 0,
|
||||
playsinline: 1,
|
||||
origin: window.location.origin,
|
||||
widget_referrer: window.location.href,
|
||||
enablejsapi: 1
|
||||
};
|
||||
|
||||
// Determine video quality
|
||||
let quality = 'hd1080';
|
||||
if (CONFIG.preferredVideoQuality === 'Maximum') {
|
||||
quality = 'highres';
|
||||
} else if (CONFIG.preferredVideoQuality === '720p') {
|
||||
quality = 'hd720';
|
||||
} else if (CONFIG.preferredVideoQuality === '1080p') {
|
||||
quality = 'hd1080';
|
||||
} else { // Auto or fallback
|
||||
// If screen is wider than 1920, prefer highres, otherwise 1080p
|
||||
quality = window.screen.width > 1920 ? 'highres' : 'hd1080';
|
||||
}
|
||||
|
||||
playerVars.suggestedQuality = quality;
|
||||
|
||||
// Apply SponsorBlock start/end times
|
||||
let startParam = '';
|
||||
let endParam = '';
|
||||
if (segments.intro) {
|
||||
playerVars.start = Math.ceil(segments.intro[1]);
|
||||
console.info(`SponsorBlock intro detected for video ${videoId}: skipping to ${playerVars.start}s`);
|
||||
startParam = `&start=${Math.ceil(segments.intro[1])}`;
|
||||
console.info(`SponsorBlock (Safari) intro skip: starting at ${Math.ceil(segments.intro[1])}s`);
|
||||
}
|
||||
if (segments.outro) {
|
||||
playerVars.end = Math.floor(segments.outro[0]);
|
||||
console.info(`SponsorBlock outro detected for video ${videoId}: ending at ${playerVars.end}s`);
|
||||
endParam = `&end=${Math.floor(segments.outro[0])}`;
|
||||
console.info(`SponsorBlock (Safari) outro skip: ending at ${Math.floor(segments.outro[0])}s`);
|
||||
}
|
||||
|
||||
STATE.slideshow.videoPlayers[itemId] = new YT.Player(`youtube-player-${itemId}`, {
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
videoId: videoId,
|
||||
playerVars: playerVars,
|
||||
events: {
|
||||
'onReady': (event) => {
|
||||
// Store start/end time and videoId for later use
|
||||
event.target._startTime = playerVars.start || 0;
|
||||
event.target._endTime = playerVars.end || undefined;
|
||||
event.target._videoId = videoId;
|
||||
// enablejsapi=1 needed for postMessage commands — does NOT trigger IFrame API handshake
|
||||
const embedUrl = `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1&mute=1&controls=0&playsinline=1&rel=0&iv_load_policy=3&enablejsapi=1&origin=${encodeURIComponent(window.location.origin)}${startParam}${endParam}`;
|
||||
|
||||
if (STATE.slideshow.isMuted) {
|
||||
event.target.mute();
|
||||
} else {
|
||||
event.target.unMute();
|
||||
event.target.setVolume(40);
|
||||
}
|
||||
const ytIframe = document.createElement('iframe');
|
||||
ytIframe.style.cssText = 'width:100%;height:100%;border:0;pointer-events:none;';
|
||||
ytIframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
|
||||
ytIframe.setAttribute('allowfullscreen', '');
|
||||
ytIframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
|
||||
ytIframe.src = embedUrl;
|
||||
videoBackdrop.appendChild(ytIframe);
|
||||
|
||||
if (typeof event.target.setPlaybackQuality === 'function') {
|
||||
event.target.setPlaybackQuality(quality);
|
||||
}
|
||||
// Show immediately — no onStateChange available for plain iframes
|
||||
videoBackdrop.style.opacity = '1';
|
||||
|
||||
// Only play if this is the active slide
|
||||
// Helper: send postMessage command to the iframe player
|
||||
const ytCmd = (func, args = []) => {
|
||||
try {
|
||||
ytIframe.contentWindow?.postMessage(
|
||||
JSON.stringify({ event: 'command', func, args }),
|
||||
'https://www.youtube-nocookie.com'
|
||||
);
|
||||
} catch(e) { /* cross-origin access may fail on some iOS versions */ }
|
||||
};
|
||||
|
||||
// Listen for YouTube state changes (e.g. video ended → advance slide)
|
||||
const handleYtMessage = (event) => {
|
||||
if (!event.origin.includes('youtube')) return;
|
||||
try {
|
||||
const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
|
||||
if (data.event === 'onStateChange' && data.info === 0) { // 0 = YT.PlayerState.ENDED
|
||||
const slide = document.querySelector(`.slide[data-item-id="${itemId}"]`);
|
||||
const isVideoPlayerOpen = document.querySelector('.videoPlayerContainer') || document.querySelector('.youtubePlayerContainer');
|
||||
|
||||
if (slide && slide.classList.contains('active') && !document.hidden && (!isVideoPlayerOpen || isVideoPlayerOpen.classList.contains('hide'))) {
|
||||
event.target.playVideo();
|
||||
|
||||
// Check if it actually started playing after a short delay (handling autoplay blocks)
|
||||
const timeoutId = setTimeout(() => {
|
||||
// Re-check conditions before processing fallback
|
||||
const isVideoPlayerOpenNow = document.querySelector('.videoPlayerContainer') || document.querySelector('.youtubePlayerContainer');
|
||||
if (document.hidden || (isVideoPlayerOpenNow && !isVideoPlayerOpenNow.classList.contains('hide')) || !slide.classList.contains('active')) {
|
||||
console.log(`Navigation detected during autoplay check for ${itemId}, stopping video.`);
|
||||
try {
|
||||
event.target.stopVideo();
|
||||
} catch (e) { console.warn("Error stopping video in timeout:", e); }
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target.getPlayerState() !== YT.PlayerState.PLAYING &&
|
||||
event.target.getPlayerState() !== YT.PlayerState.BUFFERING) {
|
||||
console.warn(`Autoplay blocked for ${itemId}, attempting muted fallback`);
|
||||
event.target.mute();
|
||||
event.target.playVideo();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
if (!STATE.slideshow.autoplayTimeouts) STATE.slideshow.autoplayTimeouts = [];
|
||||
STATE.slideshow.autoplayTimeouts.push(timeoutId);
|
||||
|
||||
// Pause slideshow timer when video starts if configured
|
||||
if (CONFIG.waitForTrailerToEnd && STATE.slideshow.slideInterval) {
|
||||
STATE.slideshow.slideInterval.stop();
|
||||
}
|
||||
}
|
||||
},
|
||||
'onStateChange': (event) => {
|
||||
if (event.data === YT.PlayerState.ENDED) {
|
||||
const slide = document.querySelector(`.slide[data-item-id="${itemId}"]`);
|
||||
if (slide && slide.classList.contains('active')) {
|
||||
SlideshowManager.nextSlide();
|
||||
}
|
||||
}
|
||||
},
|
||||
'onError': (event) => {
|
||||
console.warn(`YouTube player error ${event.data} for video ${videoId}`);
|
||||
// Fallback to next slide on error
|
||||
if (CONFIG.waitForTrailerToEnd) {
|
||||
if (slide && slide.classList.contains('active')) {
|
||||
SlideshowManager.nextSlide();
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
};
|
||||
window.addEventListener('message', handleYtMessage);
|
||||
|
||||
// Create a postMessage-based stub compatible with all slide management code
|
||||
// Key: we NEVER clear ytIframe.src — that would break the YouTube session and cause Error 153.
|
||||
// Instead we use postMessage pause/play/seek to control playback state.
|
||||
STATE.slideshow.videoPlayers[itemId] = {
|
||||
_isSafariIframe: true,
|
||||
_iframe: ytIframe,
|
||||
_videoId: videoId,
|
||||
_embedUrl: embedUrl,
|
||||
_msgHandler: handleYtMessage,
|
||||
pauseVideo() { ytCmd('pauseVideo'); },
|
||||
stopVideo() { ytCmd('pauseVideo'); ytCmd('seekTo', [0, true]); },
|
||||
playVideo() { ytCmd('playVideo'); },
|
||||
mute() { ytCmd('mute'); },
|
||||
unMute() { ytCmd('unMute'); },
|
||||
setVolume(v) { ytCmd('setVolume', [v]); },
|
||||
getIframe() { return ytIframe; },
|
||||
getPlayerState() { return 1; }, // approximate: avoids triggering fallback timeouts
|
||||
loadVideoById({ videoId: vid, startSeconds = 0 }) {
|
||||
if (vid === this._videoId) {
|
||||
// Same video — seek to start and resume. NEVER change src (would cause Error 153).
|
||||
ytCmd('seekTo', [startSeconds, true]);
|
||||
ytCmd('playVideo');
|
||||
} else {
|
||||
// Different video — need a fresh embed URL
|
||||
const url = `https://www.youtube-nocookie.com/embed/${vid}?autoplay=1&mute=1&controls=0&playsinline=1&rel=0&iv_load_policy=3&enablejsapi=1&origin=${encodeURIComponent(window.location.origin)}`;
|
||||
ytIframe.src = url;
|
||||
this._videoId = vid;
|
||||
this._embedUrl = url;
|
||||
}
|
||||
},
|
||||
destroy() {
|
||||
window.removeEventListener('message', this._msgHandler);
|
||||
ytIframe.remove();
|
||||
}
|
||||
};
|
||||
|
||||
console.log(`🍎 Safari detected — using plain iframe embed for YouTube video ${videoId}`);
|
||||
});
|
||||
|
||||
} else {
|
||||
// ── Non-Safari: YouTube IFrame API ──────────────────────────────────────
|
||||
const ytPlayerDiv = SlideUtils.createElement("div", {
|
||||
id: `youtube-player-${itemId}`,
|
||||
style: "width: 100%; height: 100%;"
|
||||
});
|
||||
|
||||
videoBackdrop.appendChild(ytPlayerDiv);
|
||||
|
||||
SlideUtils.loadYouTubeIframeAPI().then(() => {
|
||||
ApiUtils.fetchSponsorBlockData(videoId).then(segments => {
|
||||
const playerVars = {
|
||||
autoplay: 1,
|
||||
mute: 1, // need to be muted for Safari, because apple makes life difficult...
|
||||
controls: 0,
|
||||
disablekb: 1,
|
||||
fs: 0,
|
||||
iv_load_policy: 3,
|
||||
rel: 0,
|
||||
loop: 0,
|
||||
playsinline: 1,
|
||||
origin: window.location.origin,
|
||||
enablejsapi: 1
|
||||
};
|
||||
|
||||
// Determine video quality
|
||||
let quality = 'hd1080';
|
||||
if (CONFIG.preferredVideoQuality === 'Maximum') {
|
||||
quality = 'highres';
|
||||
} else if (CONFIG.preferredVideoQuality === '720p') {
|
||||
quality = 'hd720';
|
||||
} else if (CONFIG.preferredVideoQuality === '1080p') {
|
||||
quality = 'hd1080';
|
||||
} else {
|
||||
quality = window.screen.width > 1920 ? 'highres' : 'hd1080';
|
||||
}
|
||||
|
||||
playerVars.suggestedQuality = quality;
|
||||
|
||||
// Apply SponsorBlock start/end times
|
||||
if (segments.intro) {
|
||||
playerVars.start = Math.ceil(segments.intro[1]);
|
||||
console.info(`SponsorBlock intro detected for video ${videoId}: skipping to ${playerVars.start}s`);
|
||||
}
|
||||
if (segments.outro) {
|
||||
playerVars.end = Math.floor(segments.outro[0]);
|
||||
console.info(`SponsorBlock outro detected for video ${videoId}: ending at ${playerVars.end}s`);
|
||||
}
|
||||
|
||||
STATE.slideshow.videoPlayers[itemId] = new YT.Player(`youtube-player-${itemId}`, {
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
videoId: videoId,
|
||||
host: 'https://www.youtube-nocookie.com',
|
||||
playerVars: playerVars,
|
||||
events: {
|
||||
'onReady': (event) => {
|
||||
const iframe = event.target.getIframe();
|
||||
if (iframe) {
|
||||
iframe.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
|
||||
// Full allow attribute matching what YouTube sets on their own embed pages
|
||||
iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
|
||||
}
|
||||
|
||||
// Store start/end time and videoId for later use
|
||||
event.target._startTime = playerVars.start || 0;
|
||||
event.target._endTime = playerVars.end || undefined;
|
||||
event.target._videoId = videoId;
|
||||
|
||||
// Store reference to wrapper for fading
|
||||
event.target._wrapperDiv = videoBackdrop;
|
||||
|
||||
// Unmute now if user wants sound.
|
||||
if (!STATE.slideshow.isMuted) {
|
||||
event.target.unMute();
|
||||
event.target.setVolume(40);
|
||||
}
|
||||
|
||||
if (typeof event.target.setPlaybackQuality === 'function') {
|
||||
event.target.setPlaybackQuality(quality);
|
||||
}
|
||||
|
||||
// Stop playback if slide was navigated away from
|
||||
const slide = document.querySelector(`.slide[data-item-id="${itemId}"]`);
|
||||
const isVideoPlayerOpen = document.querySelector('.videoPlayerContainer') || document.querySelector('.youtubePlayerContainer');
|
||||
|
||||
if (!slide || !slide.classList.contains('active') || document.hidden || (isVideoPlayerOpen && !isVideoPlayerOpen.classList.contains('hide'))) {
|
||||
event.target.stopVideo();
|
||||
} else {
|
||||
if (CONFIG.waitForTrailerToEnd && STATE.slideshow.slideInterval) {
|
||||
STATE.slideshow.slideInterval.stop();
|
||||
}
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
const isVideoPlayerOpenNow = document.querySelector('.videoPlayerContainer') || document.querySelector('.youtubePlayerContainer');
|
||||
if (document.hidden || (isVideoPlayerOpenNow && !isVideoPlayerOpenNow.classList.contains('hide')) || !slide.classList.contains('active')) {
|
||||
console.log(`Navigation detected during autoplay check for ${itemId}, stopping video.`);
|
||||
try {
|
||||
event.target.stopVideo();
|
||||
} catch (e) { console.warn("Error stopping video:", e); }
|
||||
return;
|
||||
}
|
||||
|
||||
const state = event.target.getPlayerState();
|
||||
if (state !== YT.PlayerState.PLAYING && state !== YT.PlayerState.BUFFERING) {
|
||||
console.warn(`Autoplay stalled for ${itemId}, attempting muted fallback`);
|
||||
event.target.mute();
|
||||
event.target.playVideo();
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
if (!STATE.slideshow.autoplayTimeouts) STATE.slideshow.autoplayTimeouts = [];
|
||||
STATE.slideshow.autoplayTimeouts.push(timeoutId);
|
||||
}
|
||||
},
|
||||
'onStateChange': (event) => {
|
||||
if (event.data === YT.PlayerState.PLAYING) {
|
||||
if (event.target._wrapperDiv) {
|
||||
event.target._wrapperDiv.style.opacity = "1";
|
||||
}
|
||||
}
|
||||
|
||||
if (event.data === YT.PlayerState.ENDED) {
|
||||
const slide = document.querySelector(`.slide[data-item-id="${itemId}"]`);
|
||||
if (slide && slide.classList.contains('active')) {
|
||||
SlideshowManager.nextSlide();
|
||||
}
|
||||
}
|
||||
},
|
||||
'onError': (event) => {
|
||||
console.warn(`YouTube player error ${event.data} for video ${videoId}`);
|
||||
if (CONFIG.waitForTrailerToEnd) {
|
||||
SlideshowManager.nextSlide();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
} // end non-Safari
|
||||
|
||||
// 2. Check for local video trailers in MediaSources if yt is not available
|
||||
} else if (!isYoutube) {
|
||||
@@ -1861,10 +1987,11 @@ const SlideCreator = {
|
||||
preload: "none",
|
||||
disablePictureInPicture: true,
|
||||
"data-src": videoSrc,
|
||||
style: "object-fit: cover; object-position: center center; width: 100%; height: 100%; position: absolute; top: 0; left: 0; pointer-events: none;"
|
||||
style: "object-fit: cover; object-position: center center; width: 100%; height: 100%; position: absolute; top: 0; left: 0; pointer-events: none; opacity: 0; transition: opacity 1.2s ease-in-out;"
|
||||
};
|
||||
|
||||
videoAttributes.muted = "";
|
||||
videoAttributes.playsinline = ""; // again Safari needs extra treatment...
|
||||
|
||||
videoBackdrop = SlideUtils.createElement("video", videoAttributes);
|
||||
videoBackdrop.volume = 0.4;
|
||||
@@ -1879,6 +2006,10 @@ const SlideCreator = {
|
||||
event.target.currentTime = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Fade in
|
||||
event.target.style.opacity = "1";
|
||||
|
||||
if (CONFIG.waitForTrailerToEnd && STATE.slideshow.slideInterval) {
|
||||
STATE.slideshow.slideInterval.stop();
|
||||
}
|
||||
@@ -1892,7 +2023,10 @@ const SlideCreator = {
|
||||
});
|
||||
|
||||
videoBackdrop.addEventListener('error', (event) => {
|
||||
console.warn(`Local video error for item ${itemId}`);
|
||||
const src = event.target.src || event.target.getAttribute('data-src') || 'unknown';
|
||||
const errCode = event.target.error ? event.target.error.code : 'n/a';
|
||||
const errMsg = event.target.error ? event.target.error.message : 'n/a';
|
||||
console.warn(`Local video error for item ${itemId} | code=${errCode} | msg=${errMsg} | url=${src}`);
|
||||
const slide = event.target.closest('.slide');
|
||||
if (slide && slide.classList.contains('active')) {
|
||||
SlideshowManager.nextSlide();
|
||||
@@ -2371,30 +2505,32 @@ const SlideshowManager = {
|
||||
|
||||
// Manage Video Playback: Stop others, Play current
|
||||
// 1. Stop all other YouTube players and local video elements, release connections
|
||||
if (STATE.slideshow.videoPlayers) {
|
||||
Object.keys(STATE.slideshow.videoPlayers).forEach(id => {
|
||||
if (id !== currentItemId) {
|
||||
const p = STATE.slideshow.videoPlayers[id];
|
||||
if (!p) return;
|
||||
// YouTube player
|
||||
if (typeof p.pauseVideo === 'function') {
|
||||
p.pauseVideo();
|
||||
}
|
||||
// HTML5 <video> element (local trailers), release HTTP connection
|
||||
if (p instanceof HTMLVideoElement) {
|
||||
p.pause();
|
||||
p.muted = true;
|
||||
p.currentTime = 0;
|
||||
// Save src to data-src and release the HTTP streaming connection
|
||||
if (p.src && !p.getAttribute('data-src')) {
|
||||
p.setAttribute('data-src', p.src);
|
||||
setTimeout(() => {
|
||||
if (STATE.slideshow.videoPlayers) {
|
||||
Object.keys(STATE.slideshow.videoPlayers).forEach(id => {
|
||||
if (id !== currentItemId) {
|
||||
const p = STATE.slideshow.videoPlayers[id];
|
||||
if (!p) return;
|
||||
// YouTube player
|
||||
if (typeof p.pauseVideo === 'function') {
|
||||
p.pauseVideo();
|
||||
}
|
||||
// HTML5 <video> element (local trailers), release HTTP connection
|
||||
if (p instanceof HTMLVideoElement) {
|
||||
p.pause();
|
||||
p.muted = true;
|
||||
p.currentTime = 0;
|
||||
// Save src to data-src and release the HTTP streaming connection
|
||||
if (p.src && !p.getAttribute('data-src')) {
|
||||
p.setAttribute('data-src', p.src);
|
||||
}
|
||||
p.removeAttribute('src');
|
||||
p.load();
|
||||
}
|
||||
p.removeAttribute('src');
|
||||
p.load();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, CONFIG.fadeTransitionDuration);
|
||||
|
||||
// 2. Pause all other HTML5 videos e.g. local trailers
|
||||
document.querySelectorAll('video').forEach(video => {
|
||||
@@ -2429,42 +2565,58 @@ const SlideshowManager = {
|
||||
if (videoBackdrop.tagName === 'VIDEO') {
|
||||
// Restore src from data-src if it was deactivated to release connections
|
||||
const lazySrc = videoBackdrop.getAttribute('data-src');
|
||||
if (lazySrc && !videoBackdrop.src) {
|
||||
videoBackdrop.src = lazySrc;
|
||||
}
|
||||
|
||||
videoBackdrop.currentTime = 0;
|
||||
const isFreshLoad = lazySrc && !videoBackdrop.src;
|
||||
|
||||
videoBackdrop.muted = STATE.slideshow.isMuted;
|
||||
if (!STATE.slideshow.isMuted) {
|
||||
videoBackdrop.volume = 0.4;
|
||||
}
|
||||
|
||||
videoBackdrop.play().catch(e => {
|
||||
// Check if it actually started playing after a short delay (handling autoplay blocks)
|
||||
setTimeout(() => {
|
||||
if (videoBackdrop.paused && currentSlide.classList.contains('active')) {
|
||||
console.warn(`Autoplay blocked for ${currentItemId}, attempting muted fallback`);
|
||||
videoBackdrop.muted = true;
|
||||
videoBackdrop.play().catch(err => console.error("Muted fallback failed", err));
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
const doPlay = () => {
|
||||
if (!currentSlide.classList.contains('active')) return;
|
||||
videoBackdrop.play().catch(e => {
|
||||
setTimeout(() => {
|
||||
if (videoBackdrop.paused && currentSlide.classList.contains('active')) {
|
||||
console.warn(`Autoplay blocked for ${currentItemId}, attempting muted fallback`);
|
||||
videoBackdrop.muted = true;
|
||||
videoBackdrop.play().catch(err => console.error("Muted fallback failed", err));
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
};
|
||||
|
||||
if (isFreshLoad) {
|
||||
// Safari: set src, then wait for loadedmetadata before seeking/playing
|
||||
videoBackdrop.src = lazySrc;
|
||||
videoBackdrop.load();
|
||||
videoBackdrop.addEventListener('loadedmetadata', () => {
|
||||
videoBackdrop.currentTime = 0;
|
||||
doPlay();
|
||||
}, { once: true });
|
||||
} else {
|
||||
// src already set (e.g. paused slide resuming)
|
||||
videoBackdrop.currentTime = 0;
|
||||
doPlay();
|
||||
}
|
||||
} else if (STATE.slideshow.videoPlayers && STATE.slideshow.videoPlayers[currentItemId]) {
|
||||
const player = STATE.slideshow.videoPlayers[currentItemId];
|
||||
if (player && typeof player.loadVideoById === 'function' && player._videoId) {
|
||||
// Use loadVideoById to enforce start and end times
|
||||
// load always starts muted first, then unmute if needed
|
||||
player.loadVideoById({
|
||||
videoId: player._videoId,
|
||||
startSeconds: player._startTime || 0,
|
||||
endSeconds: player._endTime
|
||||
});
|
||||
|
||||
if (STATE.slideshow.isMuted) {
|
||||
player.mute();
|
||||
} else {
|
||||
player.unMute();
|
||||
player.setVolume(40);
|
||||
player.mute();
|
||||
if (!STATE.slideshow.isMuted) {
|
||||
setTimeout(() => {
|
||||
// Only unmute if still on the same slide
|
||||
if (currentSlide.classList.contains('active')) {
|
||||
player.unMute();
|
||||
player.setVolume(40);
|
||||
}
|
||||
}, 600);
|
||||
}
|
||||
|
||||
// Check if playback successfully started, otherwise fallback to muted
|
||||
@@ -3697,8 +3849,8 @@ const slidesInit = async () => {
|
||||
|
||||
if (CONFIG.enableClientSideSettings) {
|
||||
MediaBarEnhancedSettingsManager.init();
|
||||
const isEnabled = MediaBarEnhancedSettingsManager.getSetting('enabled', true);
|
||||
if (!isEnabled) {
|
||||
const isClientSideEnabled = MediaBarEnhancedSettingsManager.getSetting('enabled', true);
|
||||
if (!isClientSideEnabled) {
|
||||
console.log("MediaBarEnhanced: Disabled by client-side setting.");
|
||||
const homeSections = document.querySelector('.homeSectionsContainer');
|
||||
if (homeSections) {
|
||||
|
||||
@@ -9,12 +9,20 @@
|
||||
"imageUrl": "https://git.mahom03-spacecloud.de/CodeDevMLH/jellyfin-plugin-media-bar-enhanced/raw/branch/main/logo.png",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.6.6.0",
|
||||
"version": "1.7.0.5",
|
||||
"changelog": "- Add YouTube no-cookie host and referrer policy for iframe security to fix playback issues on iOS/MacOS",
|
||||
"targetAbi": "10.11.0.0",
|
||||
"sourceUrl": "https://git.mahom03-spacecloud.de/CodeDevMLH/jellyfin-plugin-media-bar-enhanced/releases/download/v1.7.0.5/Jellyfin.Plugin.MediaBarEnhanced.zip",
|
||||
"checksum": "2d7e4d747c610e853b375726162febee",
|
||||
"timestamp": "2026-03-05T23:59:05Z"
|
||||
},
|
||||
{
|
||||
"version": "1.6.6.4",
|
||||
"changelog": "- feat: add static backdrop also for video backdrops\n- fix: renaming issue of settings (avoiding conflict with other plugins)",
|
||||
"targetAbi": "10.11.0.0",
|
||||
"sourceUrl": "https://git.mahom03-spacecloud.de/CodeDevMLH/jellyfin-plugin-media-bar-enhanced/releases/download/v1.6.6.0/Jellyfin.Plugin.MediaBarEnhanced.zip",
|
||||
"checksum": "af624d779b5e43cc6e21899eb24db26d",
|
||||
"timestamp": "2026-02-19T01:01:20Z"
|
||||
"sourceUrl": "https://git.mahom03-spacecloud.de/CodeDevMLH/jellyfin-plugin-media-bar-enhanced/releases/download/v1.6.6.4/Jellyfin.Plugin.MediaBarEnhanced.zip",
|
||||
"checksum": "2c55cf9687e44b04a0824997e2980dc9",
|
||||
"timestamp": "2026-02-19T17:21:40Z"
|
||||
},
|
||||
{
|
||||
"version": "1.6.5.2",
|
||||
|
||||
Reference in New Issue
Block a user