Initial commit: CinemaTrailers4Jellyfins plugin
Some checks failed
Publish Release / release (push) Failing after 17s

Adapted from Trailers4Jellyfin: keeps TMDB/YouTube trailer downloading,
the scheduled task, language/source/date filters, and trailer rotation,
but drops cinema-mode/IIntroProvider entirely. Each trailer now ships in
its own fake-movie folder (placeholder video + locked NFO + trailer) for
use with a Cinema Mode / trailer pre-roll plugin.
This commit is contained in:
Martin
2026-06-08 14:24:28 -04:00
commit c2d2b1ae44
17 changed files with 1637 additions and 0 deletions

View File

@@ -0,0 +1,147 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
{
/// <summary>
/// Produces the placeholder "fake movie" file and its NFO that sit alongside each
/// downloaded trailer. Jellyfin scans the fake movie as a normal library item (its
/// metadata locked via the NFO so it never queries TMDB) and picks up the adjacent
/// "-trailer.mp4" as that item's local trailer — exactly what a Cinema Mode / trailer
/// pre-roll plugin consumes.
/// </summary>
public class FakeMovieService
{
private const string MasterFileName = "master.mp4";
private readonly ILogger<FakeMovieService> _logger;
private readonly SemaphoreSlim _masterLock = new(1, 1);
public FakeMovieService(ILogger<FakeMovieService> logger)
{
_logger = logger;
}
private static string MasterFilePath =>
Path.Combine(Plugin.Instance.DataFolderPath, "fake-movie", MasterFileName);
/// <summary>
/// Copies the master fake-movie file to <paramref name="destinationPath"/>,
/// generating the master via ffmpeg first if it doesn't exist yet.
/// </summary>
public async Task<bool> CopyFakeMovieAsync(string destinationPath, CancellationToken ct)
{
if (!await EnsureMasterFileAsync(ct).ConfigureAwait(false))
return false;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!);
File.Copy(MasterFilePath, destinationPath, overwrite: true);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to copy fake movie file to {Path}", destinationPath);
return false;
}
}
/// <summary>
/// Writes a minimal Jellyfin/Kodi-compatible movie NFO with &lt;lockdata&gt;true&lt;/lockdata&gt;
/// so Jellyfin never tries to refresh metadata for the fake entry from TMDB.
/// </summary>
public void WriteNfo(string nfoPath, string title, int? year)
{
var settings = new XmlWriterSettings { Indent = true };
using var writer = XmlWriter.Create(nfoPath, settings);
writer.WriteStartDocument();
writer.WriteStartElement("movie");
writer.WriteElementString("title", title);
if (year.HasValue)
writer.WriteElementString("year", year.Value.ToString());
writer.WriteElementString("lockdata", "true");
writer.WriteEndElement();
writer.WriteEndDocument();
}
// Generates a few seconds of black video with silent audio — just enough for
// Jellyfin to recognize the file as a valid playable video. Built once and reused
// by copying, rather than regenerated per trailer.
private async Task<bool> EnsureMasterFileAsync(CancellationToken ct)
{
if (File.Exists(MasterFilePath))
return true;
await _masterLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (File.Exists(MasterFilePath))
return true;
Directory.CreateDirectory(Path.GetDirectoryName(MasterFilePath)!);
var tempPath = MasterFilePath + ".tmp";
if (File.Exists(tempPath)) File.Delete(tempPath);
_logger.LogInformation("|CinemaTrailers4Jellyfins| Generating master fake-movie file via ffmpeg at {Path}", MasterFilePath);
var args = string.Join(" ",
"-y",
"-f lavfi -i \"color=c=black:s=640x360:r=24:d=3\"",
"-f lavfi -i \"anullsrc=channel_layout=stereo:sample_rate=44100\"",
"-shortest",
"-c:v libx264 -tune stillimage -pix_fmt yuv420p",
"-c:a aac -b:a 64k",
$"\"{tempPath}\"");
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
await process.WaitForExitAsync(ct).ConfigureAwait(false);
if (process.ExitCode != 0 || !File.Exists(tempPath))
{
var stderr = await process.StandardError.ReadToEndAsync(ct).ConfigureAwait(false);
_logger.LogError(
"|CinemaTrailers4Jellyfins| ffmpeg failed to generate the master fake-movie file (exit code {Code}): {Error}",
process.ExitCode, stderr);
if (File.Exists(tempPath)) File.Delete(tempPath);
return false;
}
File.Move(tempPath, MasterFilePath, overwrite: true);
_logger.LogInformation("|CinemaTrailers4Jellyfins| Master fake-movie file generated at {Path}", MasterFilePath);
return true;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to generate the master fake-movie file. Is ffmpeg installed and on PATH?");
return false;
}
finally
{
_masterLock.Release();
}
}
}
}

View File

@@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
{
public record TmdbVideo(string Key, string Name, string Language, bool Official, int Size);
public record TmdbMovieResult(int Id, string Title, string ReleaseDate)
{
public int? Year => DateTime.TryParse(ReleaseDate, out var d) ? d.Year : (int?)null;
}
public class TmdbService : IDisposable
{
private readonly HttpClient _httpClient;
private readonly ILogger<TmdbService> _logger;
private const string BaseUrl = "https://api.themoviedb.org/3";
public TmdbService(ILogger<TmdbService> logger)
{
_logger = logger;
// Force IPv4 to avoid ~80s delay when IPv6 is unreachable (Happy Eyeballs fallback).
var handler = new SocketsHttpHandler
{
ConnectCallback = async (ctx, ct) =>
{
var entry = await Dns.GetHostEntryAsync(ctx.DnsEndPoint.Host, AddressFamily.InterNetwork, ct).ConfigureAwait(false);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
try
{
await socket.ConnectAsync(entry.AddressList[0], ctx.DnsEndPoint.Port, ct).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
};
_httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
}
public void Dispose() => _httpClient.Dispose();
// JWT Read Access Tokens start with "eyJ"; v3 short keys (32 hex chars) use ?api_key=.
private static void ApplyAuth(HttpRequestMessage request, string apiKey)
{
if (apiKey.StartsWith("eyJ", StringComparison.Ordinal))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
else
{
var uri = request.RequestUri!.ToString();
var separator = uri.Contains('?') ? "&" : "?";
request.RequestUri = new Uri($"{uri}{separator}api_key={apiKey}");
}
}
/// <summary>
/// Fetches candidate movies from the configured TMDB sources, optionally filtered
/// by a minimum release date. Deduplicates across sources by TMDB ID.
/// </summary>
public async Task<List<TmdbMovieResult>> GetCandidateMoviesAsync(
Configuration.PluginConfiguration config,
CancellationToken ct)
{
DateTime? releasedAfter = config.ReleaseDateRangeMonths > 0
? DateTime.UtcNow.AddMonths(-config.ReleaseDateRangeMonths)
: null;
var seen = new HashSet<int>();
var results = new List<TmdbMovieResult>();
async Task FetchSource(string endpoint)
{
var movies = await FetchSourcePagesAsync(endpoint, config.TmdbApiKey, releasedAfter, config.MaxPagesPerSource, ct)
.ConfigureAwait(false);
foreach (var m in movies)
{
if (seen.Add(m.Id))
results.Add(m);
}
}
if (config.SourceNowPlaying) await FetchSource("now_playing");
if (config.SourceUpcoming) await FetchSource("upcoming");
if (config.SourcePopular) await FetchSource("popular");
if (config.SourceTopRated) await FetchSource("top_rated");
return results;
}
private async Task<List<TmdbMovieResult>> FetchSourcePagesAsync(
string endpoint,
string apiKey,
DateTime? releasedAfter,
int maxPages,
CancellationToken ct)
{
var results = new List<TmdbMovieResult>();
for (int page = 1; page <= maxPages; page++)
{
ct.ThrowIfCancellationRequested();
try
{
var url = $"{BaseUrl}/movie/{endpoint}?language=en-US&page={page}";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
ApplyAuth(request, apiKey);
using var response = await _httpClient.SendAsync(request, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
var pageResults = doc.RootElement.GetProperty("results");
int totalPages = doc.RootElement.GetProperty("total_pages").GetInt32();
bool anyInRange = false;
foreach (var movie in pageResults.EnumerateArray())
{
var releaseDate = movie.TryGetProperty("release_date", out var rd) ? rd.GetString() ?? string.Empty : string.Empty;
var title = movie.TryGetProperty("title", out var t) ? t.GetString() ?? string.Empty : string.Empty;
var id = movie.GetProperty("id").GetInt32();
if (releasedAfter.HasValue && DateTime.TryParse(releaseDate, out var parsed))
{
if (parsed < releasedAfter.Value) continue;
}
anyInRange = true;
results.Add(new TmdbMovieResult(id, title, releaseDate));
}
if (page >= totalPages || (releasedAfter.HasValue && !anyInRange))
break;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to fetch TMDB source '{Endpoint}' page {Page}", endpoint, page);
break;
}
}
return results;
}
public async Task<string?> SearchMovieAsync(string title, int? year, string apiKey, CancellationToken ct)
{
try
{
var url = $"{BaseUrl}/search/movie?query={Uri.EscapeDataString(title)}&language=en-US";
if (year.HasValue) url += $"&year={year.Value}";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
ApplyAuth(request, apiKey);
using var response = await _httpClient.SendAsync(request, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
var res = doc.RootElement.GetProperty("results");
if (res.GetArrayLength() > 0)
return res[0].GetProperty("id").GetInt32().ToString();
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| TMDB search failed for '{Title}'", title);
}
return null;
}
public async Task<List<TmdbVideo>> GetTrailersAsync(
string tmdbId,
string apiKey,
IReadOnlySet<string>? allowedLanguages,
CancellationToken ct)
{
try
{
// No language filter on the URL — we want all available trailers so we can
// filter by iso_639_1 ourselves based on the user's language preference.
var url = $"{BaseUrl}/movie/{tmdbId}/videos";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
ApplyAuth(request, apiKey);
using var response = await _httpClient.SendAsync(request, ct).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
using var doc = JsonDocument.Parse(json);
var videos = new List<TmdbVideo>();
foreach (var result in doc.RootElement.GetProperty("results").EnumerateArray())
{
var type = result.GetProperty("type").GetString();
var site = result.GetProperty("site").GetString();
if (!string.Equals(type, "Trailer", StringComparison.OrdinalIgnoreCase)
|| !string.Equals(site, "YouTube", StringComparison.OrdinalIgnoreCase))
continue;
var key = result.GetProperty("key").GetString();
if (string.IsNullOrEmpty(key)) continue;
var lang = result.TryGetProperty("iso_639_1", out var l) ? (l.GetString() ?? string.Empty) : string.Empty;
if (allowedLanguages != null && allowedLanguages.Count > 0 && !allowedLanguages.Contains(lang))
continue;
videos.Add(new TmdbVideo(
key,
result.GetProperty("name").GetString() ?? "Trailer",
lang,
result.GetProperty("official").GetBoolean(),
result.GetProperty("size").GetInt32()));
}
return videos
.OrderByDescending(v => v.Official)
.ThenByDescending(v => v.Size)
.ToList();
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| GetTrailers failed for TMDB ID {Id}", tmdbId);
return new List<TmdbVideo>();
}
}
}
}

View File

@@ -0,0 +1,183 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using YoutubeExplode;
using YoutubeExplode.Videos.Streams;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
{
public class TrailerDownloadService : IDisposable
{
private readonly ILogger<TrailerDownloadService> _logger;
private readonly HttpClient _httpClient;
public TrailerDownloadService(ILogger<TrailerDownloadService> logger)
{
_logger = logger;
// Force IPv4 to avoid ~80s delay when IPv6 is unreachable (Happy Eyeballs fallback).
var handler = new SocketsHttpHandler
{
ConnectCallback = async (ctx, ct) =>
{
var entry = await Dns.GetHostEntryAsync(ctx.DnsEndPoint.Host, AddressFamily.InterNetwork, ct).ConfigureAwait(false);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
try
{
await socket.ConnectAsync(entry.AddressList[0], ctx.DnsEndPoint.Port, ct).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
};
_httpClient = new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(10) };
}
public void Dispose() => _httpClient.Dispose();
/// <summary>
/// Downloads a YouTube video by key to outputPath.
/// Uses yt-dlp when a valid path is configured (supports 1080p+, requires ffmpeg on PATH).
/// Falls back to YoutubeExplode for built-in download (max 720p, no external tools needed).
/// </summary>
public async Task<bool> DownloadAsync(
string youtubeKey,
string outputPath,
int preferredHeight,
string ytDlpPath,
CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
if (!string.IsNullOrWhiteSpace(ytDlpPath) && File.Exists(ytDlpPath))
{
return await DownloadWithYtDlpAsync(youtubeKey, outputPath, preferredHeight, ytDlpPath, ct)
.ConfigureAwait(false);
}
return await DownloadWithYoutubeExplodeAsync(youtubeKey, outputPath, preferredHeight, ct)
.ConfigureAwait(false);
}
private async Task<bool> DownloadWithYoutubeExplodeAsync(
string key,
string outputPath,
int preferredHeight,
CancellationToken ct)
{
try
{
var youtube = new YoutubeClient(_httpClient);
var manifest = await youtube.Videos.Streams
.GetManifestAsync($"https://www.youtube.com/watch?v={key}", ct)
.ConfigureAwait(false);
// Muxed streams include audio+video in one file. Quality is capped at 720p by YouTube.
var muxedStreams = manifest.GetMuxedStreams().ToList();
if (muxedStreams.Count == 0)
{
_logger.LogWarning("|CinemaTrailers4Jellyfins| No muxed streams available for {Key}. Consider configuring yt-dlp for 1080p support.", key);
return false;
}
// Prefer the highest quality at or below the configured height limit.
var stream = muxedStreams
.Where(s => s.VideoQuality.MaxHeight <= preferredHeight)
.OrderByDescending(s => s.VideoQuality.MaxHeight)
.FirstOrDefault()
?? muxedStreams.OrderByDescending(s => s.VideoQuality.MaxHeight).First();
_logger.LogInformation(
"|CinemaTrailers4Jellyfins| Downloading {Key} at {Quality} to {Path}",
key, stream.VideoQuality.Label, outputPath);
await youtube.Videos.Streams
.DownloadAsync(stream, outputPath, cancellationToken: ct)
.ConfigureAwait(false);
return true;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| YoutubeExplode download failed for {Key}", key);
return false;
}
}
private async Task<bool> DownloadWithYtDlpAsync(
string key,
string outputPath,
int preferredHeight,
string ytDlpPath,
CancellationToken ct)
{
try
{
// Format selects the best video at or below preferredHeight merged with the best audio.
// --merge-output-format mp4 ensures the output is always an mp4.
var args = string.Join(" ",
$"-f \"bestvideo[height<={preferredHeight}]+bestaudio/best[height<={preferredHeight}]\"",
"--merge-output-format mp4",
"--no-playlist",
"--no-warnings",
$"-o \"{outputPath}\"",
$"\"https://www.youtube.com/watch?v={key}\"");
_logger.LogInformation(
"|CinemaTrailers4Jellyfins| Downloading {Key} via yt-dlp at max {Height}p to {Path}",
key, preferredHeight, outputPath);
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = ytDlpPath,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
await process.WaitForExitAsync(ct).ConfigureAwait(false);
if (process.ExitCode != 0)
{
var stderr = await process.StandardError.ReadToEndAsync(ct).ConfigureAwait(false);
_logger.LogError("|CinemaTrailers4Jellyfins| yt-dlp exited with code {Code} for {Key}: {Error}",
process.ExitCode, key, stderr);
return false;
}
return File.Exists(outputPath);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| yt-dlp download failed for {Key}", key);
return false;
}
}
}
}