feat: Update to version 1.2.0.0 with script injection improvements and fallback support

This commit is contained in:
CodeDevMLH
2025-12-17 16:34:02 +01:00
parent ca813bacb7
commit 4433cbb949
10 changed files with 142 additions and 20 deletions

View File

@@ -12,13 +12,14 @@
<!-- <TreatWarningsAsErrors>false</TreatWarningsAsErrors> -->
<Title>Jellyfin Seasonals Plugin</Title>
<Authors>CodeDevMLH</Authors>
<Version>1.1.0.0</Version>
<Version>1.2.0.0</Version>
<RepositoryUrl>https://github.com/CodeDevMLH/jellyfin-plugin-seasonals</RepositoryUrl>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="$(JellyfinVersion)" />
<PackageReference Include="Jellyfin.Model" Version="$(JellyfinVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,12 +1,17 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Jellyfin.Plugin.Seasonals.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Jellyfin.Plugin.Seasonals;
@@ -28,7 +33,10 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
Instance = this;
_scriptInjector = new ScriptInjector(applicationPaths, loggerFactory.CreateLogger<ScriptInjector>());
_scriptInjector.Inject();
if (!_scriptInjector.Inject())
{
TryRegisterFallback(loggerFactory.CreateLogger("FileTransformationFallback"));
}
}
/// <inheritdoc />
@@ -42,16 +50,99 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
/// </summary>
public static Plugin? Instance { get; private set; }
/// <summary>
/// Callback method for FileTransformation plugin.
/// </summary>
/// <param name="payload">The payload containing the file contents.</param>
/// <returns>The modified file contents.</returns>
public static string TransformIndexHtml(JObject payload)
{
// CRITICAL: Always return original content if something fails or is null
string? originalContents = payload?["contents"]?.ToString();
if (string.IsNullOrEmpty(originalContents))
{
return originalContents ?? string.Empty;
}
try
{
var html = originalContents;
const string inject = "<script src=\"/Seasonals/Resources/seasonals.js\"></script>\n<body";
if (!html.Contains("seasonals.js", StringComparison.Ordinal))
{
return html.Replace("<body", inject, StringComparison.OrdinalIgnoreCase);
}
return html;
}
catch
{
// On error, return original content to avoid breaking the UI
return originalContents;
}
}
private void TryRegisterFallback(ILogger logger)
{
try
{
// Find the FileTransformation assembly across all load contexts
var assembly = AssemblyLoadContext.All
.SelectMany(x => x.Assemblies)
.FirstOrDefault(x => x.FullName?.Contains(".FileTransformation") ?? false);
if (assembly == null)
{
logger.LogWarning("FileTransformation plugin not found. Fallback injection skipped.");
return;
}
var type = assembly.GetType("Jellyfin.Plugin.FileTransformation.PluginInterface");
if (type == null)
{
logger.LogWarning("Jellyfin.Plugin.FileTransformation.PluginInterface not found.");
return;
}
var method = type.GetMethod("RegisterTransformation");
if (method == null)
{
logger.LogWarning("RegisterTransformation method not found.");
return;
}
// Create JObject payload directly using Newtonsoft.Json
var payload = new JObject
{
{ "id", Id.ToString() },
{ "fileNamePattern", "index.html" },
{ "callbackAssembly", this.GetType().Assembly.FullName },
{ "callbackClass", this.GetType().FullName },
{ "callbackMethod", nameof(TransformIndexHtml) }
};
// Invoke RegisterTransformation with the JObject payload
method.Invoke(null, new object[] { payload });
logger.LogInformation("Successfully registered fallback transformation via FileTransformation plugin.");
}
catch (Exception ex)
{
logger.LogError(ex, "Error attempting to register fallback transformation.");
}
}
/// <inheritdoc />
public IEnumerable<PluginPageInfo> GetPages()
{
return
[
return new[]
{
new PluginPageInfo
{
Name = Name,
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Configuration.configPage.html", GetType().Namespace)
}
];
};
}
}

View File

@@ -30,7 +30,8 @@ public class ScriptInjector
/// <summary>
/// Injects the script tag into index.html if it's not already present.
/// </summary>
public void Inject()
/// <returns>True if injection was successful or already present, false otherwise.</returns>
public bool Inject()
{
try
{
@@ -38,21 +39,21 @@ public class ScriptInjector
if (string.IsNullOrEmpty(webPath))
{
_logger.LogWarning("Could not find Jellyfin web path. Script injection skipped.");
return;
return false;
}
var indexPath = Path.Combine(webPath, "index.html");
if (!File.Exists(indexPath))
{
_logger.LogWarning("index.html not found at {Path}. Script injection skipped.", indexPath);
return;
return false;
}
var content = File.ReadAllText(indexPath);
if (content.Contains(ScriptTag, StringComparison.Ordinal))
{
_logger.LogInformation("Seasonals script already injected.");
return;
return true;
}
// Insert before the closing body tag
@@ -60,19 +61,22 @@ public class ScriptInjector
if (string.Equals(newContent, content, StringComparison.Ordinal))
{
_logger.LogWarning("Could not find closing body tag in index.html. Script injection skipped.");
return;
return false;
}
File.WriteAllText(indexPath, newContent);
_logger.LogInformation("Successfully injected Seasonals script into index.html.");
return true;
}
catch (UnauthorizedAccessException)
{
_logger.LogWarning("Permission denied when attempting to inject script into index.html. Automatic injection failed. Please ensure the Jellyfin web directory is writable by the process, or manually add the script tag: {ScriptTag}", ScriptTag);
return false;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error injecting Seasonals script.");
return false;
}
}

View File

@@ -162,6 +162,7 @@ async function initializeTheme() {
automateThemeSelection = config.automateSeasonSelection;
defaultTheme = config.selectedSeason;
window.SeasonalsPluginConfig = config;
console.log('Seasonals Config loaded:', config);
} else {
console.error('Failed to fetch Seasonals config');
}
@@ -170,7 +171,7 @@ async function initializeTheme() {
}
let currentTheme;
if (!automateThemeSelection) {
if (automateThemeSelection === false) {
currentTheme = defaultTheme;
} else {
currentTheme = determineCurrentTheme();
@@ -178,7 +179,7 @@ async function initializeTheme() {
console.log(`Selected theme: ${currentTheme}`);
if (currentTheme === 'none') {
if (!currentTheme || currentTheme === 'none') {
console.log('No theme selected.');
removeSelf();
return;
@@ -200,8 +201,9 @@ async function initializeTheme() {
removeSelf();
}
//document.addEventListener('DOMContentLoaded', initializeTheme);
document.addEventListener('DOMContentLoaded', () => {
// Ensure DOM is ready before initializing
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeTheme);
} else {
initializeTheme();
});
}