feat: add TV show trailer downloads, episode trailers, and movie/TV trailer separation
All checks were successful
Publish Release / release (push) Successful in 23s

- Download trailers for TV shows from TMDB with separate sources and an
  independent max-count cap (0 disables a category)
- Play trailers before TV episodes via IIntroProvider, limited to the first
  episode a user watches each day
- Tag TV show trailers in their NFO so movies only get movie trailers and
  episodes only get TV show trailers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Martin
2026-06-10 00:41:37 -04:00
parent f769e33b8d
commit f49c32f181
9 changed files with 542 additions and 127 deletions

View File

@@ -56,7 +56,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
/// 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, IReadOnlyList<string>? genres = null, string? mpaa = null)
public void WriteNfo(string nfoPath, string title, int? year, IReadOnlyList<string>? genres = null, string? mpaa = null, IReadOnlyList<string>? tags = null)
{
var settings = new XmlWriterSettings { Indent = true };
using var writer = XmlWriter.Create(nfoPath, settings);
@@ -70,6 +70,9 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
writer.WriteElementString("genre", genre);
if (!string.IsNullOrWhiteSpace(mpaa))
writer.WriteElementString("mpaa", mpaa);
if (tags != null)
foreach (var tag in tags)
writer.WriteElementString("tag", tag);
writer.WriteElementString("lockdata", "true");
writer.WriteEndElement();
writer.WriteEndDocument();

View File

@@ -14,12 +14,12 @@ 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 record TmdbMediaResult(int Id, string Title, string ReleaseDate)
{
public int? Year => DateTime.TryParse(ReleaseDate, out var d) ? d.Year : (int?)null;
}
public record TmdbMovieMetadata(IReadOnlyList<string> Genres, string? Certification);
public record TmdbMediaMetadata(IReadOnlyList<string> Genres, string? Certification);
public class TmdbService : IDisposable
{
@@ -75,7 +75,39 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
/// 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(
public Task<List<TmdbMediaResult>> GetCandidateMoviesAsync(
Configuration.PluginConfiguration config,
CancellationToken ct)
{
var sources = new List<string>();
if (config.SourceNowPlaying) sources.Add("now_playing");
if (config.SourceUpcoming) sources.Add("upcoming");
if (config.SourcePopular) sources.Add("popular");
if (config.SourceTopRated) sources.Add("top_rated");
return GetCandidatesAsync("movie", sources, config, ct);
}
/// <summary>
/// Fetches candidate TV shows from the configured TMDB sources, optionally filtered
/// by a minimum first-air date. Deduplicates across sources by TMDB ID.
/// </summary>
public Task<List<TmdbMediaResult>> GetCandidateTvShowsAsync(
Configuration.PluginConfiguration config,
CancellationToken ct)
{
var sources = new List<string>();
if (config.SourceTvAiringToday) sources.Add("airing_today");
if (config.SourceTvOnTheAir) sources.Add("on_the_air");
if (config.SourceTvPopular) sources.Add("popular");
if (config.SourceTvTopRated) sources.Add("top_rated");
return GetCandidatesAsync("tv", sources, config, ct);
}
private async Task<List<TmdbMediaResult>> GetCandidatesAsync(
string mediaType,
List<string> sourceEndpoints,
Configuration.PluginConfiguration config,
CancellationToken ct)
{
@@ -84,36 +116,36 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
: null;
var seen = new HashSet<int>();
var results = new List<TmdbMovieResult>();
var results = new List<TmdbMediaResult>();
async Task FetchSource(string endpoint)
foreach (var endpoint in sourceEndpoints)
{
var movies = await FetchSourcePagesAsync(endpoint, config.TmdbApiKey, releasedAfter, config.MaxPagesPerSource, ct)
var items = await FetchSourcePagesAsync(mediaType, endpoint, config.TmdbApiKey, releasedAfter, config.MaxPagesPerSource, ct)
.ConfigureAwait(false);
foreach (var m in movies)
foreach (var item in items)
{
if (seen.Add(m.Id))
results.Add(m);
if (seen.Add(item.Id))
results.Add(item);
}
}
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(
private async Task<List<TmdbMediaResult>> FetchSourcePagesAsync(
string mediaType,
string endpoint,
string apiKey,
DateTime? releasedAfter,
int maxPages,
CancellationToken ct)
{
var results = new List<TmdbMovieResult>();
var results = new List<TmdbMediaResult>();
// Movies use "title"/"release_date"; TV shows use "name"/"first_air_date".
var titleField = mediaType == "movie" ? "title" : "name";
var dateField = mediaType == "movie" ? "release_date" : "first_air_date";
for (int page = 1; page <= maxPages; page++)
{
@@ -121,7 +153,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
try
{
var url = $"{BaseUrl}/movie/{endpoint}?language=en-US&page={page}";
var url = $"{BaseUrl}/{mediaType}/{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);
@@ -133,11 +165,11 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
int totalPages = doc.RootElement.GetProperty("total_pages").GetInt32();
bool anyInRange = false;
foreach (var movie in pageResults.EnumerateArray())
foreach (var entry 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();
var releaseDate = entry.TryGetProperty(dateField, out var rd) ? rd.GetString() ?? string.Empty : string.Empty;
var title = entry.TryGetProperty(titleField, out var t) ? t.GetString() ?? string.Empty : string.Empty;
var id = entry.GetProperty("id").GetInt32();
if (releasedAfter.HasValue && DateTime.TryParse(releaseDate, out var parsed))
{
@@ -145,7 +177,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
}
anyInRange = true;
results.Add(new TmdbMovieResult(id, title, releaseDate));
results.Add(new TmdbMediaResult(id, title, releaseDate));
}
if (page >= totalPages || (releasedAfter.HasValue && !anyInRange))
@@ -157,7 +189,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
}
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to fetch TMDB source '{Endpoint}' page {Page}", endpoint, page);
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| Failed to fetch TMDB source '{MediaType}/{Endpoint}' page {Page}", mediaType, endpoint, page);
break;
}
}
@@ -190,17 +222,21 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
}
/// <summary>
/// Returns the genre names and US theatrical certification (G, PG, PG-13, R, NC-17)
/// for a movie. Uses a single /movie/{id}?append_to_response=release_dates call.
/// Returns the genre names and US certification for a movie or TV show
/// (e.g. PG-13 for movies, TV-14 for TV shows). Movies use a single
/// /movie/{id}?append_to_response=release_dates call; TV shows use
/// /tv/{id}?append_to_response=content_ratings.
/// </summary>
public async Task<TmdbMovieMetadata> GetMovieMetadataAsync(
public async Task<TmdbMediaMetadata> GetMediaMetadataAsync(
string mediaType,
string tmdbId,
string apiKey,
CancellationToken ct)
{
try
{
var url = $"{BaseUrl}/movie/{tmdbId}?append_to_response=release_dates&language=en-US";
var appendField = mediaType == "movie" ? "release_dates" : "content_ratings";
var url = $"{BaseUrl}/{mediaType}/{tmdbId}?append_to_response={appendField}&language=en-US";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
ApplyAuth(request, apiKey);
using var response = await _httpClient.SendAsync(request, ct).ConfigureAwait(false);
@@ -222,45 +258,76 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
}
}
string? certification = null;
if (doc.RootElement.TryGetProperty("release_dates", out var releaseDates)
&& releaseDates.TryGetProperty("results", out var rdResults))
{
foreach (var country in rdResults.EnumerateArray())
{
if (!country.TryGetProperty("iso_3166_1", out var iso)
|| !string.Equals(iso.GetString(), "US", StringComparison.OrdinalIgnoreCase))
continue;
string? certification = mediaType == "movie"
? GetMovieCertification(doc)
: GetTvCertification(doc);
if (!country.TryGetProperty("release_dates", out var dates))
break;
foreach (var date in dates.EnumerateArray())
{
if (!date.TryGetProperty("certification", out var cert))
continue;
var certStr = cert.GetString();
if (!string.IsNullOrWhiteSpace(certStr))
{
certification = certStr;
break;
}
}
break;
}
}
return new TmdbMovieMetadata(genres.AsReadOnly(), certification);
return new TmdbMediaMetadata(genres.AsReadOnly(), certification);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| GetMovieMetadata failed for TMDB ID {Id}", tmdbId);
return new TmdbMovieMetadata(Array.Empty<string>(), null);
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| GetMediaMetadata failed for {MediaType} TMDB ID {Id}", mediaType, tmdbId);
return new TmdbMediaMetadata(Array.Empty<string>(), null);
}
}
// Finds the US theatrical certification (G, PG, PG-13, R, NC-17) from release_dates.
private static string? GetMovieCertification(JsonDocument doc)
{
if (!doc.RootElement.TryGetProperty("release_dates", out var releaseDates)
|| !releaseDates.TryGetProperty("results", out var rdResults))
return null;
foreach (var country in rdResults.EnumerateArray())
{
if (!country.TryGetProperty("iso_3166_1", out var iso)
|| !string.Equals(iso.GetString(), "US", StringComparison.OrdinalIgnoreCase))
continue;
if (!country.TryGetProperty("release_dates", out var dates))
return null;
foreach (var date in dates.EnumerateArray())
{
if (!date.TryGetProperty("certification", out var cert))
continue;
var certStr = cert.GetString();
if (!string.IsNullOrWhiteSpace(certStr))
return certStr;
}
return null;
}
return null;
}
// Finds the US TV content rating (TV-Y, TV-PG, TV-14, TV-MA, etc.) from content_ratings.
private static string? GetTvCertification(JsonDocument doc)
{
if (!doc.RootElement.TryGetProperty("content_ratings", out var contentRatings)
|| !contentRatings.TryGetProperty("results", out var crResults))
return null;
foreach (var country in crResults.EnumerateArray())
{
if (!country.TryGetProperty("iso_3166_1", out var iso)
|| !string.Equals(iso.GetString(), "US", StringComparison.OrdinalIgnoreCase))
continue;
if (!country.TryGetProperty("rating", out var rating))
return null;
var ratingStr = rating.GetString();
return string.IsNullOrWhiteSpace(ratingStr) ? null : ratingStr;
}
return null;
}
public async Task<List<TmdbVideo>> GetTrailersAsync(
string mediaType,
string tmdbId,
string apiKey,
IReadOnlySet<string>? allowedLanguages,
@@ -270,7 +337,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
{
// 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";
var url = $"{BaseUrl}/{mediaType}/{tmdbId}/videos";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
ApplyAuth(request, apiKey);
using var response = await _httpClient.SendAsync(request, ct).ConfigureAwait(false);
@@ -311,7 +378,7 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| GetTrailers failed for TMDB ID {Id}", tmdbId);
_logger.LogError(ex, "|CinemaTrailers4Jellyfins| GetTrailers failed for {MediaType} TMDB ID {Id}", mediaType, tmdbId);
return new List<TmdbVideo>();
}
}

View File

@@ -8,6 +8,7 @@ using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging;
@@ -22,6 +23,10 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
private static readonly ConcurrentDictionary<Guid, HashSet<Guid>> _seenByUser = new();
private static readonly object _seenLock = new();
// Per-user date of the last episode that received trailers, so only the
// first episode a user watches each day gets them.
private static readonly ConcurrentDictionary<Guid, DateTime> _lastEpisodeTrailerDateByUser = new();
private readonly ILibraryManager _libraryManager;
private readonly ILogger<TrailerIntroProvider> _logger;
@@ -39,8 +44,32 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
if (config == null || config.TrailersPerMovie <= 0)
return Task.FromResult(Enumerable.Empty<IntroInfo>());
if (item is not Movie)
return Task.FromResult(Enumerable.Empty<IntroInfo>());
// The item used for genre/rating filtering. For episodes this is the
// parent series, since episodes rarely carry their own genre metadata.
BaseItem feature;
bool isEpisode;
switch (item)
{
case Movie:
feature = item;
isEpisode = false;
break;
case Episode episode:
if (!config.TrailersForEpisodes)
return Task.FromResult(Enumerable.Empty<IntroInfo>());
if (!IsFirstEpisodeOfDay(user.Id))
return Task.FromResult(Enumerable.Empty<IntroInfo>());
feature = episode.Series ?? (BaseItem)episode;
isEpisode = true;
break;
default:
return Task.FromResult(Enumerable.Empty<IntroInfo>());
}
var outputFolder = config.DownloadFolder?.TrimEnd(
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
@@ -62,21 +91,24 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
.OfType<Movie>()
.Where(m =>
m.Path?.StartsWith(outputFolder, StringComparison.OrdinalIgnoreCase) == true
&& m.LocalTrailers.Count > 0)
&& m.LocalTrailers.Count > 0
// Keep TV show trailers for episodes and movie trailers for movies separate.
&& m.Tags.Contains(TrailerTags.TvShow, StringComparer.OrdinalIgnoreCase) == isEpisode)
.SelectMany(m => m.LocalTrailers.Select(t => (Movie: m, Trailer: t)))
.ToList();
if (pairs.Count == 0)
{
_logger.LogDebug(
"|CinemaTrailers4Jellyfins| No indexed trailers in {Folder}. "
"|CinemaTrailers4Jellyfins| No indexed {Kind} trailers in {Folder}. "
+ "Ensure the output folder is added as a Jellyfin Movies library and scanned.",
isEpisode ? "TV show" : "movie",
outputFolder);
return Task.FromResult(Enumerable.Empty<IntroInfo>());
}
// Apply enabled filters. If nothing survives, fall back to the full pool.
var filtered = ApplyFilters(pairs, item, config);
var filtered = ApplyFilters(pairs, feature, config);
var pool = filtered.Count > 0 ? filtered : pairs;
// Prefer unseen trailers within the pool; reset the cycle when all have been shown.
@@ -149,6 +181,36 @@ namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
}
}
/// <summary>
/// Returns true (and records today's date) only the first time this is called
/// for a given user on a given day.
/// </summary>
private static bool IsFirstEpisodeOfDay(Guid userId)
{
var today = DateTime.Now.Date;
var isFirst = false;
_lastEpisodeTrailerDateByUser.AddOrUpdate(
userId,
_ =>
{
isFirst = true;
return today;
},
(_, lastDate) =>
{
if (lastDate < today)
{
isFirst = true;
return today;
}
return lastDate;
});
return isFirst;
}
private static void MarkSeen(Guid userId, IEnumerable<Guid> trailerIds)
{
lock (_seenLock)

View File

@@ -0,0 +1,12 @@
namespace Jellyfin.Plugin.CinemaTrailers4Jellyfins.Services
{
/// <summary>
/// Tags written into each downloaded trailer's NFO so <see cref="TrailerIntroProvider"/>
/// can tell movie trailers and TV show trailers apart within the shared output folder.
/// </summary>
public static class TrailerTags
{
/// <summary>Marks a fake-movie folder as containing a TV show trailer.</summary>
public const string TvShow = "ct4j-tvshow";
}
}