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,42 @@
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Configuration
{
public class PluginConfiguration : BasePluginConfiguration
{
// ── TMDB ──────────────────────────────────────────────────────────────
public string TmdbApiKey { get; set; } = string.Empty;
// ── Sources ───────────────────────────────────────────────────────────
public bool SourceNowPlaying { get; set; } = true;
public bool SourceUpcoming { get; set; } = true;
public bool SourcePopular { get; set; } = false;
public bool SourceTopRated { get; set; } = false;
// ── Date Range ────────────────────────────────────────────────────────
public int ReleaseDateRangeMonths { get; set; } = 6;
// ── Download Settings ─────────────────────────────────────────────────
public string DownloadFolder { get; set; } = string.Empty;
public int MaxTrailersToDownload { get; set; } = 20;
public int MaxPagesPerSource { get; set; } = 3;
public int PreferredVideoHeight { get; set; } = 720;
public bool SkipAlreadyDownloaded { get; set; } = true;
public bool SkipMoviesInLibrary { get; set; } = true;
public string YtDlpPath { get; set; } = string.Empty;
// ── Languages ─────────────────────────────────────────────────────────
/// <summary>Comma-separated ISO 639-1 codes. Empty = all languages allowed.</summary>
public string AllowedLanguages { get; set; } = string.Empty;
// ── Trailer Rotation ──────────────────────────────────────────────────
/// <summary>Maximum trailers to keep on disk. Oldest are deleted first when exceeded. 0 = unlimited.</summary>
public int MaxTotalTrailers { get; set; } = 50;
}
}

View File

@@ -0,0 +1,302 @@
<!DOCTYPE html>
<html>
<head>
<title>CinemaTrailers4Jellyfins</title>
</head>
<body>
<div data-role="page" class="page type-interior pluginConfigurationPage cinemaTrailers4JellyfinsConfigPage"
data-require="emby-input,emby-button,emby-checkbox,emby-select">
<div data-role="content">
<div class="content-primary">
<form class="cinemaTrailers4JellyfinsConfigPage">
<div class="sectionTitleContainer flex align-items-center">
<h2 class="sectionTitle">CinemaTrailers4Jellyfins</h2>
<a is="emby-linkbutton" class="raised button-alt headerHelpButton emby-button"
target="_blank" href="https://www.git.quarantinedstudio.com/mvezina/CinemaTrailers4Jellyfins#readme">Help</a>
</div>
<div class="verticalSection">
<p>
Downloads trailers for <strong>upcoming and recently released movies not in your library</strong>
from TMDB/YouTube and stores each one inside its own fake-movie folder, ready to be
picked up by a Cinema Mode / trailer pre-roll plugin.
</p>
<p style="margin-top:0">
A free TMDB API key is required.
<a href="https://www.themoviedb.org/settings/api" target="_blank" rel="noopener">Get one here →</a>
</p>
</div>
<!-- TMDB -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">TMDB</h3></legend>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="tmdb-api-key">TMDB API Key</label>
<input type="password" id="tmdb-api-key" is="emby-input" autocomplete="off" />
<div class="fieldDescription">
Your TMDB Read Access Token (JWT) or v3 API key from
<a href="https://www.themoviedb.org/settings/api" target="_blank" rel="noopener">themoviedb.org/settings/api</a>.
</div>
</div>
</fieldset>
<!-- Languages -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Trailer Languages</h3></legend>
<p class="fieldDescription">
Only download trailers in the selected languages.
Leave everything unchecked to allow all languages.
</p>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:0 2em;">
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-en" /><span>English</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-es" /><span>Spanish</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-fr" /><span>French</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-de" /><span>German</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-it" /><span>Italian</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-pt" /><span>Portuguese</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-nl" /><span>Dutch</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-ru" /><span>Russian</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-pl" /><span>Polish</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-sv" /><span>Swedish</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-no" /><span>Norwegian</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-da" /><span>Danish</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-ja" /><span>Japanese</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-ko" /><span>Korean</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-zh" /><span>Chinese</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-ar" /><span>Arabic</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-hi" /><span>Hindi</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-tr" /><span>Turkish</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-th" /><span>Thai</span></label></div>
<div class="checkboxContainer"><label><input is="emby-checkbox" type="checkbox" id="lang-id" /><span>Indonesian</span></label></div>
</div>
</fieldset>
<!-- Sources -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Trailer Sources</h3></legend>
<p class="fieldDescription">
Choose which TMDB lists to pull trailers from. Enable multiple for more variety.
</p>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="source-now-playing" />
<span>Now Playing</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Movies currently in theatres. Refreshes weekly on TMDB.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="source-upcoming" />
<span>Upcoming</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Movies coming soon to theatres. Great for seeing what's on the horizon.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="source-popular" />
<span>Popular</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Most popular movies on TMDB right now, filtered by the date range below.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="source-top-rated" />
<span>Top Rated</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Highest rated movies on TMDB, filtered by the date range below.
</div>
</div>
</fieldset>
<!-- Date Range -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Date Range</h3></legend>
<div class="selectContainer">
<label class="selectLabel" for="date-range">Only include movies released within</label>
<select is="emby-select" id="date-range" class="emby-select-withcolor emby-select">
<option value="3">Last 3 months</option>
<option value="6">Last 6 months</option>
<option value="12">Last 1 year</option>
<option value="24">Last 2 years</option>
<option value="0">All time (no limit)</option>
</select>
<div class="fieldDescription">
Applies to all sources. "Now Playing" and "Upcoming" already have tight date windows
set by TMDB, but this provides an additional filter.
</div>
</div>
</fieldset>
<!-- Download Settings -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Download Settings</h3></legend>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="download-folder">Output Folder</label>
<input type="text" id="download-folder" is="emby-input" placeholder="/media/trailers" />
<div class="fieldDescription">
Where the fake-movie/trailer folders are created. Add this as a Jellyfin Movies
library and scan it so a Cinema Mode / trailer pre-roll plugin can use the trailers.
</div>
</div>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="max-trailers">Max trailers per run</label>
<input type="number" id="max-trailers" is="emby-input" min="1" max="200" />
<div class="fieldDescription">
Maximum number of trailers to download each time the task runs. Default: 20.
</div>
</div>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="max-pages">Pages per source</label>
<input type="number" id="max-pages" is="emby-input" min="1" max="10" />
<div class="fieldDescription">
How many pages to fetch from each TMDB source (20 movies per page). Default: 3.
</div>
</div>
<div class="selectContainer">
<label class="selectLabel" for="video-quality">Video quality</label>
<select is="emby-select" id="video-quality" class="emby-select-withcolor emby-select">
<option value="720">720p (built-in, no extra tools)</option>
<option value="480">480p (built-in, no extra tools)</option>
<option value="1080">1080p (requires yt-dlp + ffmpeg)</option>
</select>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="skip-library" />
<span>Skip movies already in my Jellyfin library</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
Trailers for movies you already own won't be downloaded.
</div>
</div>
<div class="checkboxContainer checkboxContainer-withDescription">
<label>
<input is="emby-checkbox" type="checkbox" id="skip-downloaded" />
<span>Skip trailers already downloaded</span>
</label>
<div class="fieldDescription checkboxFieldDescription">
If a folder already exists for a movie, don't re-download it.
</div>
</div>
</fieldset>
<!-- Trailer Rotation -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Trailer Rotation</h3></legend>
<p class="fieldDescription">
Keep your trailer library fresh by automatically removing the oldest entries
each time the download task runs.
</p>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="max-total-trailers">Max trailers to keep</label>
<input type="number" id="max-total-trailers" is="emby-input" min="0" max="500" />
<div class="fieldDescription">
Maximum number of trailer folders to keep on disk at once. When this limit is exceeded,
the oldest are deleted first to make room for new downloads. Set to 0 for unlimited.
Default: 50.
</div>
</div>
</fieldset>
<!-- Advanced -->
<fieldset class="verticalSection verticalSection-extrabottompadding">
<legend><h3 class="sectionTitle">Advanced</h3></legend>
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="ytdlp-path">yt-dlp path (optional)</label>
<input type="text" id="ytdlp-path" is="emby-input" placeholder="/usr/local/bin/yt-dlp" />
<div class="fieldDescription">
Full path to <a href="https://github.com/yt-dlp/yt-dlp" target="_blank" rel="noopener">yt-dlp</a>.
Required for 1080p quality. Also needs <strong>ffmpeg</strong> on the system PATH.
Leave blank to use the built-in downloader (720p max, zero extra tools).
</div>
</div>
</fieldset>
<br />
<button is="emby-button" type="submit" class="raised button-submit block">
<span>${Save}</span>
</button>
</form>
</div>
</div>
<script type="text/javascript">
var pluginId = "b581493e-1046-40ed-b6dc-cb8027624984";
$('.cinemaTrailers4JellyfinsConfigPage').on('pageshow', function () {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginId).then(function (config) {
document.getElementById('tmdb-api-key').value = config.TmdbApiKey || '';
document.getElementById('source-now-playing').checked = config.SourceNowPlaying !== false;
document.getElementById('source-upcoming').checked = config.SourceUpcoming !== false;
document.getElementById('source-popular').checked = !!config.SourcePopular;
document.getElementById('source-top-rated').checked = !!config.SourceTopRated;
document.getElementById('date-range').value = String(config.ReleaseDateRangeMonths ?? 6);
document.getElementById('download-folder').value = config.DownloadFolder || '';
document.getElementById('max-trailers').value = config.MaxTrailersToDownload ?? 20;
document.getElementById('max-pages').value = config.MaxPagesPerSource ?? 3;
document.getElementById('video-quality').value = String(config.PreferredVideoHeight ?? 720);
document.getElementById('skip-library').checked = config.SkipMoviesInLibrary !== false;
document.getElementById('skip-downloaded').checked = config.SkipAlreadyDownloaded !== false;
document.getElementById('ytdlp-path').value = config.YtDlpPath || '';
var langs = (config.AllowedLanguages || '').split(',').map(l => l.trim()).filter(Boolean);
['en','es','fr','de','it','pt','nl','ru','pl','sv','no','da','ja','ko','zh','ar','hi','tr','th','id']
.forEach(function(code) {
document.getElementById('lang-' + code).checked = langs.length === 0 || langs.indexOf(code) !== -1;
});
document.getElementById('max-total-trailers').value = config.MaxTotalTrailers ?? 50;
Dashboard.hideLoadingMsg();
});
});
$('.cinemaTrailers4JellyfinsConfigPage').on('submit', function () {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(pluginId).then(function (config) {
config.TmdbApiKey = document.getElementById('tmdb-api-key').value;
config.SourceNowPlaying = document.getElementById('source-now-playing').checked;
config.SourceUpcoming = document.getElementById('source-upcoming').checked;
config.SourcePopular = document.getElementById('source-popular').checked;
config.SourceTopRated = document.getElementById('source-top-rated').checked;
config.ReleaseDateRangeMonths = parseInt(document.getElementById('date-range').value, 10);
config.DownloadFolder = document.getElementById('download-folder').value;
config.MaxTrailersToDownload = parseInt(document.getElementById('max-trailers').value, 10) || 20;
config.MaxPagesPerSource = parseInt(document.getElementById('max-pages').value, 10) || 3;
config.PreferredVideoHeight = parseInt(document.getElementById('video-quality').value, 10) || 720;
config.SkipMoviesInLibrary = document.getElementById('skip-library').checked;
config.SkipAlreadyDownloaded = document.getElementById('skip-downloaded').checked;
config.YtDlpPath = document.getElementById('ytdlp-path').value;
var allLangCodes = ['en','es','fr','de','it','pt','nl','ru','pl','sv','no','da','ja','ko','zh','ar','hi','tr','th','id'];
var checkedLangs = allLangCodes.filter(function(code) {
return document.getElementById('lang-' + code).checked;
});
// If all are checked treat it as "no preference" (empty string)
config.AllowedLanguages = checkedLangs.length === allLangCodes.length ? '' : checkedLangs.join(',');
config.MaxTotalTrailers = parseInt(document.getElementById('max-total-trailers').value, 10) || 50;
ApiClient.updatePluginConfiguration(pluginId, config)
.then(Dashboard.processPluginConfigurationUpdateResult);
});
return false;
});
</script>
</div>
</body>
</html>

View File

@@ -0,0 +1,60 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 280" width="400" height="280">
<defs>
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#1b2735"/>
<stop offset="100%" style="stop-color:#0c1118"/>
</linearGradient>
<linearGradient id="folderBody" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#3fd1c0"/>
<stop offset="100%" style="stop-color:#1f9e93"/>
</linearGradient>
<linearGradient id="folderTab" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#5be3d3"/>
<stop offset="100%" style="stop-color:#2fb3a6"/>
</linearGradient>
<filter id="glow">
<feGaussianBlur stdDeviation="3" result="coloredBlur"/>
<feMerge>
<feMergeNode in="coloredBlur"/>
<feMergeNode in="SourceGraphic"/>
</feMerge>
</filter>
</defs>
<!-- Background -->
<rect width="400" height="280" fill="url(#bg)" rx="12"/>
<!-- Folder tab -->
<path d="M 130 78 h 60 l 16 18 h 64 a 10 10 0 0 1 10 10 v 6 H 120 v -24 a 10 10 0 0 1 10 -10 z" fill="url(#folderTab)"/>
<!-- Folder body -->
<rect x="110" y="112" width="180" height="100" rx="12" fill="url(#folderBody)"/>
<!-- Inner "screen" cut-out suggesting a video file inside the folder -->
<rect x="132" y="132" width="136" height="62" rx="6" fill="#0c1118" fill-opacity="0.55"/>
<!-- Play triangle -->
<polygon points="186,148 186,178 216,163" fill="#ffffff" filter="url(#glow)"/>
<!-- Duplicate ghost folder behind, hinting at the "copied placeholder" concept -->
<rect x="252" y="100" width="64" height="46" rx="8" fill="#5be3d3" fill-opacity="0.18"/>
<rect x="252" y="100" width="64" height="46" rx="8" fill="none" stroke="#5be3d3" stroke-opacity="0.45" stroke-width="1.5" stroke-dasharray="4 3"/>
<!-- Title -->
<text x="200" y="240"
font-family="'Segoe UI', Arial, sans-serif"
font-size="25"
font-weight="700"
fill="#ffffff"
text-anchor="middle"
letter-spacing="0.5">CinemaTrailers4Jellyfins</text>
<!-- Subtitle -->
<text x="200" y="260"
font-family="'Segoe UI', Arial, sans-serif"
font-size="12"
fill="#5be3d3"
text-anchor="middle"
letter-spacing="3"
font-weight="400">TRAILER LIBRARY BUILDER</text>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<RootNamespace>Jellyfin.Plugin.CinemaTrailers4Jellyfins</RootNamespace>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.11.0" />
<PackageReference Include="Jellyfin.Model" Version="10.11.0" />
<PackageReference Include="YoutubeExplode" Version="6.*" />
</ItemGroup>
<ItemGroup>
<None Remove="Configuration\config.html" />
<EmbeddedResource Include="Configuration\config.html" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using Jellyfin.Plugin.CinemaTrailers4Jellyfins.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins
{
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{
public override string Name => "CinemaTrailers4Jellyfins";
public override Guid Id => Guid.Parse("b581493e-1046-40ed-b6dc-cb8027624984");
public static Plugin Instance { get; private set; } = null!;
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
: base(applicationPaths, xmlSerializer)
{
Instance = this;
}
public IEnumerable<PluginPageInfo> GetPages()
{
yield return new PluginPageInfo
{
Name = Name,
EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
};
}
}
}

View File

@@ -0,0 +1,20 @@
using Jellyfin.Plugin.CinemaTrailers4Jellyfins.ScheduledTasks;
using Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins
{
public class PluginServiceRegistrator : IPluginServiceRegistrator
{
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
{
serviceCollection.AddSingleton<TmdbService>();
serviceCollection.AddSingleton<TrailerDownloadService>();
serviceCollection.AddSingleton<FakeMovieService>();
serviceCollection.AddTransient<IScheduledTask, DownloadTrailersTask>();
}
}
}

View File

@@ -0,0 +1,254 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
using Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.ScheduledTasks
{
public class DownloadTrailersTask : IScheduledTask
{
private readonly ILogger<DownloadTrailersTask> _logger;
private readonly ILibraryManager _libraryManager;
private readonly TmdbService _tmdbService;
private readonly TrailerDownloadService _downloadService;
private readonly FakeMovieService _fakeMovieService;
public string Name => "Download TMDB Trailers";
public string Key => "CinemaTrailers4JellyfinsDownload";
public string Description => "Downloads trailers from TMDB for upcoming and recently released movies not in your library, packaged as fake-movie folders for use with a Cinema Mode / trailer pre-roll plugin.";
public string Category => "CinemaTrailers4Jellyfins";
public DownloadTrailersTask(
ILogger<DownloadTrailersTask> logger,
ILibraryManager libraryManager,
TmdbService tmdbService,
TrailerDownloadService downloadService,
FakeMovieService fakeMovieService)
{
_logger = logger;
_libraryManager = libraryManager;
_tmdbService = tmdbService;
_downloadService = downloadService;
_fakeMovieService = fakeMovieService;
}
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
{
yield return new TaskTriggerInfo
{
Type = TaskTriggerInfoType.IntervalTrigger,
IntervalTicks = TimeSpan.FromHours(24).Ticks,
};
}
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
{
var config = Plugin.Instance.Configuration;
if (string.IsNullOrWhiteSpace(config.TmdbApiKey))
{
_logger.LogWarning("|CinemaTrailers4Jellyfins| No TMDB API key configured. Skipping task.");
return;
}
if (string.IsNullOrWhiteSpace(config.DownloadFolder))
{
_logger.LogWarning("|CinemaTrailers4Jellyfins| No output folder configured. Skipping task.");
return;
}
if (!config.SourceNowPlaying && !config.SourceUpcoming && !config.SourcePopular && !config.SourceTopRated)
{
_logger.LogWarning("|CinemaTrailers4Jellyfins| No TMDB sources selected. Enable at least one source. Skipping task.");
return;
}
Directory.CreateDirectory(config.DownloadFolder);
CleanupOldTrailers(config);
progress.Report(5);
var libraryTmdbIds = config.SkipMoviesInLibrary
? GetLibraryTmdbIds()
: new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_logger.LogInformation("|CinemaTrailers4Jellyfins| Library contains {Count} movies with TMDB IDs (will skip these)", libraryTmdbIds.Count);
progress.Report(10);
var allowedLanguages = string.IsNullOrWhiteSpace(config.AllowedLanguages)
? null
: new HashSet<string>(
config.AllowedLanguages.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
StringComparer.OrdinalIgnoreCase) as IReadOnlySet<string>;
_logger.LogInformation("|CinemaTrailers4Jellyfins| Fetching candidates from TMDB...");
var candidates = await _tmdbService.GetCandidateMoviesAsync(config, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("|CinemaTrailers4Jellyfins| Found {Count} candidate movies across all sources", candidates.Count);
progress.Report(20);
if (config.SkipMoviesInLibrary)
{
candidates = candidates
.Where(m => !libraryTmdbIds.Contains(m.Id.ToString()))
.ToList();
_logger.LogInformation("|CinemaTrailers4Jellyfins| {Count} candidates remain after filtering library movies", candidates.Count);
}
if (candidates.Count == 0)
{
_logger.LogInformation("|CinemaTrailers4Jellyfins| No new candidates to download. All done.");
progress.Report(100);
return;
}
int downloaded = 0;
int processed = 0;
foreach (var movie in candidates)
{
cancellationToken.ThrowIfCancellationRequested();
if (downloaded >= config.MaxTrailersToDownload)
break;
double taskProgress = 20 + (80.0 * processed / candidates.Count);
progress.Report(taskProgress);
processed++;
var paths = BuildMoviePaths(movie.Title, movie.Year, config);
if (config.SkipAlreadyDownloaded && Directory.Exists(paths.MovieFolder))
{
_logger.LogDebug("|CinemaTrailers4Jellyfins| Already downloaded: {Path}", paths.MovieFolder);
continue;
}
var trailers = await _tmdbService.GetTrailersAsync(
movie.Id.ToString(), config.TmdbApiKey, allowedLanguages, cancellationToken).ConfigureAwait(false);
if (trailers.Count == 0)
{
_logger.LogDebug("|CinemaTrailers4Jellyfins| No YouTube trailers on TMDB for '{Title}'", movie.Title);
continue;
}
var trailer = trailers[0];
_logger.LogInformation("|CinemaTrailers4Jellyfins| Downloading '{Trailer}' for '{Movie}'", trailer.Name, movie.Title);
var success = await _downloadService.DownloadAsync(
trailer.Key,
paths.TrailerPath,
config.PreferredVideoHeight,
config.YtDlpPath,
cancellationToken).ConfigureAwait(false);
if (!success)
continue;
var fakeMovieReady = await _fakeMovieService.CopyFakeMovieAsync(paths.FakeMoviePath, cancellationToken).ConfigureAwait(false);
if (!fakeMovieReady)
{
_logger.LogError(
"|CinemaTrailers4Jellyfins| Could not create the fake movie file for '{Movie}'. Removing incomplete folder {Folder}.",
movie.Title, paths.MovieFolder);
TryDeleteFolder(paths.MovieFolder);
continue;
}
_fakeMovieService.WriteNfo(paths.NfoPath, movie.Title, movie.Year);
downloaded++;
_logger.LogInformation(
"|CinemaTrailers4Jellyfins| [{Done}/{Max}] Saved trailer for '{Movie}' → {Path}",
downloaded, config.MaxTrailersToDownload, movie.Title, paths.MovieFolder);
}
_logger.LogInformation("|CinemaTrailers4Jellyfins| Task complete. Downloaded {Count} trailer(s).", downloaded);
progress.Report(100);
}
private HashSet<string> GetLibraryTmdbIds()
{
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var movies = _libraryManager
.GetItemList(new InternalItemsQuery { IncludeItemTypes = new[] { BaseItemKind.Movie }, Recursive = true })
.OfType<Movie>();
foreach (var movie in movies)
{
var tmdbId = movie.GetProviderId(MetadataProvider.Tmdb);
if (!string.IsNullOrEmpty(tmdbId))
ids.Add(tmdbId);
}
return ids;
}
// Each trailer lives in its own "{Movie Title} ({Year})" folder alongside a fake
// movie file and NFO. Removing a trailer always means removing that whole folder.
private void CleanupOldTrailers(Configuration.PluginConfiguration config)
{
if (config.MaxTotalTrailers <= 0)
return;
var folders = Directory.GetDirectories(config.DownloadFolder)
.Select(f => new DirectoryInfo(f))
.OrderBy(d => d.CreationTimeUtc)
.ToList();
if (folders.Count <= config.MaxTotalTrailers)
return;
var toDelete = folders.Take(folders.Count - config.MaxTotalTrailers);
foreach (var folder in toDelete)
{
_logger.LogInformation("|CinemaTrailers4Jellyfins| Deleting oldest trailer to stay under cap: {Folder}", folder.Name);
TryDeleteFolder(folder.FullName);
}
}
private void TryDeleteFolder(string folderPath)
{
try
{
if (Directory.Exists(folderPath))
Directory.Delete(folderPath, recursive: true);
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to delete folder {Folder}", folderPath);
}
}
private readonly record struct MoviePaths(string MovieFolder, string FakeMoviePath, string TrailerPath, string NfoPath);
private static MoviePaths BuildMoviePaths(string title, int? year, Configuration.PluginConfiguration config)
{
var safeTitle = string.Concat(title.Split(Path.GetInvalidFileNameChars())).Trim();
var folderName = year.HasValue ? $"{safeTitle} ({year.Value})" : safeTitle;
var movieFolder = Path.Combine(config.DownloadFolder, folderName);
return new MoviePaths(
MovieFolder: movieFolder,
FakeMoviePath: Path.Combine(movieFolder, $"{folderName}.mp4"),
TrailerPath: Path.Combine(movieFolder, $"{folderName}-trailer.mp4"),
NfoPath: Path.Combine(movieFolder, $"{folderName}.nfo"));
}
}
}

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;
}
}
}
}