diff --git a/CHANGELOG.md b/CHANGELOG.md index 783e2c7fb..b29e67ae4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - When enabled, embedded text subtitles will be periodically extracted, and considered for playback - Add `sub_language` and `sub_language_tag` fields to search index - Add `/iptv` request logging to streaming log category at debug level +- Add channel guide (XMLTV) template system + - Templates should be copied from `_channel.sbntxt`, `_movie.sbntxt`, or `_episode.sbntxt` which are located in the config subfolder `templates/channel-guide` + - Copy the file, remove the leading underscore from the name, and only make edits to the copied file + - The default templates will be extracted and overwritten every time ErsatzTV is started + - The templates use [scribian](https://github.com/scriban/scriban/tree/master/doc) template syntax + - The templates contain comments describing which fields are available for use in the templates ### Fixed - Fix antiforgery error caused by reusing existing browser tabs across docker container restarts diff --git a/ErsatzTV.Application/Channels/Commands/RefreshChannelDataHandler.cs b/ErsatzTV.Application/Channels/Commands/RefreshChannelDataHandler.cs index ae9822efa..201527b6d 100644 --- a/ErsatzTV.Application/Channels/Commands/RefreshChannelDataHandler.cs +++ b/ErsatzTV.Application/Channels/Commands/RefreshChannelDataHandler.cs @@ -12,6 +12,8 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.IO; using Newtonsoft.Json; +using Scriban; +using WebMarkupMin.Core; namespace ErsatzTV.Application.Channels; @@ -38,6 +40,27 @@ public class RefreshChannelDataHandler : IRequestHandler { _localFileSystem.EnsureFolderExists(FileSystemLayout.ChannelGuideCacheFolder); + string movieTemplateFileName = GetMovieTemplateFileName(); + string episodeTemplateFileName = GetEpisodeTemplateFileName(); + if (movieTemplateFileName is null || episodeTemplateFileName is null) + { + return; + } + + var minifier = new XmlMinifier( + new XmlMinificationSettings + { + MinifyWhitespace = true, + RemoveXmlComments = true, + CollapseTagsWithoutContent = true + }); + + string movieText = await File.ReadAllTextAsync(movieTemplateFileName, cancellationToken); + var movieTemplate = Template.Parse(movieText, movieTemplateFileName); + + string episodeText = await File.ReadAllTextAsync(episodeTemplateFileName, cancellationToken); + var episodeTemplate = Template.Parse(episodeText, episodeTemplateFileName); + await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken); List playouts = await dbContext.Playouts @@ -46,6 +69,7 @@ public class RefreshChannelDataHandler : IRequestHandler .Include(p => p.Items) .ThenInclude(i => i.MediaItem) .ThenInclude(i => (i as Episode).EpisodeMetadata) + .ThenInclude(em => em.Guids) .Include(p => p.Items) .ThenInclude(i => i.MediaItem) .ThenInclude(i => (i as Episode).Season) @@ -57,7 +81,13 @@ public class RefreshChannelDataHandler : IRequestHandler .ThenInclude(i => (i as Episode).Season) .ThenInclude(s => s.Show) .ThenInclude(s => s.ShowMetadata) - .ThenInclude(em => em.Genres) + .ThenInclude(sm => sm.Genres) + .Include(p => p.Items) + .ThenInclude(i => i.MediaItem) + .ThenInclude(i => (i as Episode).Season) + .ThenInclude(s => s.Show) + .ThenInclude(s => s.ShowMetadata) + .ThenInclude(sm => sm.Guids) .Include(p => p.Items) .ThenInclude(i => i.MediaItem) .ThenInclude(i => (i as Movie).MovieMetadata) @@ -68,6 +98,10 @@ public class RefreshChannelDataHandler : IRequestHandler .ThenInclude(mm => mm.Genres) .Include(p => p.Items) .ThenInclude(i => i.MediaItem) + .ThenInclude(i => (i as Movie).MovieMetadata) + .ThenInclude(mm => mm.Guids) + .Include(p => p.Items) + .ThenInclude(i => i.MediaItem) .ThenInclude(i => (i as MusicVideo).MusicVideoMetadata) .ThenInclude(mm => mm.Artwork) .Include(p => p.Items) @@ -167,6 +201,97 @@ public class RefreshChannelDataHandler : IRequestHandler string description = GetDescription(displayItem); Option contentRating = GetContentRating(displayItem); + if (displayItem.MediaItem is Movie templateMovie) + { + foreach (MovieMetadata metadata in templateMovie.MovieMetadata.HeadOrNone()) + { + metadata.Genres ??= []; + metadata.Guids ??= []; + + string poster = Optional(metadata.Artwork).Flatten() + .Filter(a => a.ArtworkKind == ArtworkKind.Poster) + .HeadOrNone() + .Match(a => GetArtworkUrl(a, ArtworkKind.Poster), () => string.Empty); + + string result = await movieTemplate.RenderAsync( + new + { + ProgrammeStart = start, + ProgrammeStop = stop, + ChannelNumber = request.ChannelNumber, + HasCustomTitle = hasCustomTitle, + CustomTitle = displayItem.CustomTitle, + MovieTitle = title, + MovieHasPlot = !string.IsNullOrWhiteSpace(metadata.Plot), + MoviePlot = metadata.Plot, + MovieHasYear = metadata.Year.HasValue, + MovieYear = metadata.Year, + MovieGenres = metadata.Genres.Map(g => g.Name).OrderBy(n => n), + MovieHasArtwork = !string.IsNullOrWhiteSpace(poster), + MovieArtworkUrl = poster, + MovieHasContentRating = !string.IsNullOrWhiteSpace(metadata.ContentRating), + MovieContentRating = metadata.ContentRating, + MovieGuids = metadata.Guids.Map(g => g.Guid) + }); + + MarkupMinificationResult minified = minifier.Minify(result); + await xml.WriteRawAsync(minified.MinifiedContent); + } + + i++; + continue; + } + + if (displayItem.MediaItem is Episode templateEpisode) + { + foreach (EpisodeMetadata metadata in templateEpisode.EpisodeMetadata.HeadOrNone()) + { + metadata.Genres ??= []; + metadata.Guids ??= []; + + foreach (ShowMetadata showMetadata in Optional( + templateEpisode.Season?.Show?.ShowMetadata.HeadOrNone()).Flatten()) + { + showMetadata.Genres ??= []; + showMetadata.Guids ??= []; + + string artworkPath = GetPrioritizedArtworkPath(metadata); + + string result = await episodeTemplate.RenderAsync( + new + { + ProgrammeStart = start, + ProgrammeStop = stop, + ChannelNumber = request.ChannelNumber, + HasCustomTitle = hasCustomTitle, + CustomTitle = displayItem.CustomTitle, + ShowTitle = title, + EpisodeHasTitle = !string.IsNullOrWhiteSpace(subtitle), + EpisodeTitle = subtitle, + EpisodeHasPlot = !string.IsNullOrWhiteSpace(metadata.Plot), + EpisodePlot = metadata.Plot, + ShowHasYear = showMetadata.Year.HasValue, + ShowYear = showMetadata.Year, + ShowGenres = showMetadata.Genres.Map(g => g.Name).OrderBy(n => n), + EpisodeHasArtwork = !string.IsNullOrWhiteSpace(artworkPath), + EpisodeArtworkUrl = artworkPath, + SeasonNumber = templateEpisode.Season?.SeasonNumber ?? 0, + EpisodeNumber = metadata.EpisodeNumber, + ShowHasContentRating = !string.IsNullOrWhiteSpace(showMetadata.ContentRating), + ShowContentRating = showMetadata.ContentRating, + ShowGuids = showMetadata.Guids.Map(g => g.Guid), + EpisodeGuids = metadata.Guids.Map(g => g.Guid) + }); + + MarkupMinificationResult minified = minifier.Minify(result); + await xml.WriteRawAsync(minified.MinifiedContent); + } + } + + i++; + continue; + } + await xml.WriteStartElementAsync(null, "programme", null); await xml.WriteAttributeStringAsync(null, "start", null, start); await xml.WriteAttributeStringAsync(null, "stop", null, stop); @@ -381,6 +506,52 @@ public class RefreshChannelDataHandler : IRequestHandler File.Move(tempFile, targetFile, true); } + private string GetMovieTemplateFileName() + { + string templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "movie.sbntxt"); + + // fall back to default template + if (!_localFileSystem.FileExists(templateFileName)) + { + templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "_movie.sbntxt"); + } + + // fail if file doesn't exist + if (!_localFileSystem.FileExists(templateFileName)) + { + _logger.LogError( + "Unable to generate movie XMLTV fragment without template file {File}; please restart ErsatzTV", + templateFileName); + + return null; + } + + return templateFileName; + } + + private string GetEpisodeTemplateFileName() + { + string templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "episode.sbntxt"); + + // fall back to default template + if (!_localFileSystem.FileExists(templateFileName)) + { + templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "_episode.sbntxt"); + } + + // fail if file doesn't exist + if (!_localFileSystem.FileExists(templateFileName)) + { + _logger.LogError( + "Unable to generate episode XMLTV fragment without template file {File}; please restart ErsatzTV", + templateFileName); + + return null; + } + + return templateFileName; + } + private static string GetArtworkUrl(Artwork artwork, ArtworkKind artworkKind) { string artworkPath = artwork.Path; diff --git a/ErsatzTV.Application/Channels/Commands/RefreshChannelListHandler.cs b/ErsatzTV.Application/Channels/Commands/RefreshChannelListHandler.cs index e7b9b0003..766425041 100644 --- a/ErsatzTV.Application/Channels/Commands/RefreshChannelListHandler.cs +++ b/ErsatzTV.Application/Channels/Commands/RefreshChannelListHandler.cs @@ -5,7 +5,10 @@ using ErsatzTV.Core; using ErsatzTV.Core.Interfaces.Metadata; using ErsatzTV.Infrastructure.Data; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; using Microsoft.IO; +using Scriban; +using WebMarkupMin.Core; namespace ErsatzTV.Application.Channels; @@ -13,16 +16,19 @@ public class RefreshChannelListHandler : IRequestHandler { private readonly IDbContextFactory _dbContextFactory; private readonly ILocalFileSystem _localFileSystem; + private readonly ILogger _logger; private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager; public RefreshChannelListHandler( RecyclableMemoryStreamManager recyclableMemoryStreamManager, IDbContextFactory dbContextFactory, - ILocalFileSystem localFileSystem) + ILocalFileSystem localFileSystem, + ILogger logger) { _recyclableMemoryStreamManager = recyclableMemoryStreamManager; _dbContextFactory = dbContextFactory; _localFileSystem = localFileSystem; + _logger = logger; } public async Task Handle(RefreshChannelList request, CancellationToken cancellationToken) @@ -31,6 +37,35 @@ public class RefreshChannelListHandler : IRequestHandler await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken); + string templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "channel.sbntxt"); + + // fall back to default template + if (!_localFileSystem.FileExists(templateFileName)) + { + templateFileName = Path.Combine(FileSystemLayout.ChannelGuideTemplatesFolder, "_channel.sbntxt"); + } + + // fail if file doesn't exist + if (!_localFileSystem.FileExists(templateFileName)) + { + _logger.LogError( + "Unable to generate channel list without template file {File}; please restart ErsatzTV", + templateFileName); + + return; + } + + var minifier = new XmlMinifier( + new XmlMinificationSettings + { + MinifyWhitespace = true, + RemoveXmlComments = true, + CollapseTagsWithoutContent = true + }); + + string text = await File.ReadAllTextAsync(templateFileName, cancellationToken); + var template = Template.Parse(text, templateFileName); + await using RecyclableMemoryStream ms = _recyclableMemoryStreamManager.GetStream(); await using var xml = XmlWriter.Create( ms, @@ -38,34 +73,18 @@ public class RefreshChannelListHandler : IRequestHandler await foreach (ChannelResult channel in GetChannels(dbContext).WithCancellation(cancellationToken)) { - await xml.WriteStartElementAsync(null, "channel", null); - await xml.WriteAttributeStringAsync(null, "id", null, $"{channel.Number}.etv"); + string result = await template.RenderAsync( + new + { + ChannelNumber = channel.Number, + ChannelName = channel.Name, + ChannelCategories = GetCategories(channel.Categories), + ChannelHasArtwork = !string.IsNullOrWhiteSpace(channel.ArtworkPath), + ChannelArtworkPath = channel.ArtworkPath + }); - await xml.WriteStartElementAsync(null, "display-name", null); - await xml.WriteStringAsync($"{channel.Number} {channel.Name}"); - await xml.WriteEndElementAsync(); // display-name (number and name) - - await xml.WriteStartElementAsync(null, "display-name", null); - await xml.WriteStringAsync(channel.Number); - await xml.WriteEndElementAsync(); // display-name (number) - - await xml.WriteStartElementAsync(null, "display-name", null); - await xml.WriteStringAsync(channel.Name); - await xml.WriteEndElementAsync(); // display-name (name) - - foreach (string category in GetCategories(channel.Categories)) - { - await xml.WriteStartElementAsync(null, "category", null); - await xml.WriteAttributeStringAsync(null, "lang", null, "en"); - await xml.WriteStringAsync(category); - await xml.WriteEndElementAsync(); // category - } - - await xml.WriteStartElementAsync(null, "icon", null); - await xml.WriteAttributeStringAsync(null, "src", null, GetIconUrl(channel)); - await xml.WriteEndElementAsync(); // icon - - await xml.WriteEndElementAsync(); // channel + MarkupMinificationResult minified = minifier.Minify(result); + await xml.WriteRawAsync(minified.MinifiedContent); } await xml.FlushAsync(); diff --git a/ErsatzTV.Application/ErsatzTV.Application.csproj b/ErsatzTV.Application/ErsatzTV.Application.csproj index 10a1286d1..e4b6cf969 100644 --- a/ErsatzTV.Application/ErsatzTV.Application.csproj +++ b/ErsatzTV.Application/ErsatzTV.Application.csproj @@ -21,6 +21,7 @@ + diff --git a/ErsatzTV.Core/FileSystemLayout.cs b/ErsatzTV.Core/FileSystemLayout.cs index 126e3b554..440f42e0b 100644 --- a/ErsatzTV.Core/FileSystemLayout.cs +++ b/ErsatzTV.Core/FileSystemLayout.cs @@ -53,6 +53,8 @@ public static class FileSystemLayout public static readonly string MusicVideoCreditsTemplatesFolder = Path.Combine(TemplatesFolder, "music-video-credits"); + public static readonly string ChannelGuideTemplatesFolder = Path.Combine(TemplatesFolder, "channel-guide"); + public static readonly string ScriptsFolder = Path.Combine(AppDataFolder, "scripts"); public static readonly string MultiEpisodeShuffleTemplatesFolder = diff --git a/ErsatzTV/ErsatzTV.csproj b/ErsatzTV/ErsatzTV.csproj index bc83a47a7..42e51c8d3 100644 --- a/ErsatzTV/ErsatzTV.csproj +++ b/ErsatzTV/ErsatzTV.csproj @@ -73,6 +73,9 @@ + + + diff --git a/ErsatzTV/Resources/Templates/_channel.sbntxt b/ErsatzTV/Resources/Templates/_channel.sbntxt new file mode 100644 index 000000000..00063b232 --- /dev/null +++ b/ErsatzTV/Resources/Templates/_channel.sbntxt @@ -0,0 +1,30 @@ +{{ ## + +Available values: + - channel_number + - channel_name + - channel_categories + - channel_has_artwork + - channel_artwork_path + +{RequestBase} and {AccessTokenUri} are replaced dynamically when XMLTV is requested, +and must remain as-is in this template to work properly with ETV URLs. +External URLs do not require these placeholders. + +The resulting XML will be minified by ErsatzTV - so feel free to keep things nicely formatted here. + +## }} + + + {{ channel_number }} {{ channel_name }} + {{ channel_number }} + {{ channel_name }} + {{ for category in channel_categories }} + {{ category }} + {{ end }} + {{ if channel_has_artwork }} + + {{ else }} + + {{ end }} + diff --git a/ErsatzTV/Resources/Templates/_episode.sbntxt b/ErsatzTV/Resources/Templates/_episode.sbntxt new file mode 100644 index 000000000..df5bb4c48 --- /dev/null +++ b/ErsatzTV/Resources/Templates/_episode.sbntxt @@ -0,0 +1,63 @@ +{{ ## + +Available values: + - programme_start + - programme_stop + - channel_number + - has_custom_title + - custom_title + - show_title + - episode_has_title + - episode_title + - episode_has_plot + - episode_plot + - show_has_year + - show_year + - show_genres + - episode_has_artwork + - episode_artwork_url + - season_number + - episode_number + - show_has_content_rating + - show_content_rating + - show_guids + - episode_guids + +The resulting XML will be minified by ErsatzTV - so feel free to keep things nicely formatted here. + +## }} + + + {{ if has_custom_title }} + {{ custom_title }} + {{ else }} + {{ show_title }} + {{ if episode_has_title }} + {{ episode_title }} + {{ end }} + {{ if episode_has_plot }} + {{ episode_plot }} + {{ end }} + Series + {{ for genre in show_genres }} + {{ genre }} + {{ end }} + {{ if episode_has_artwork }} + + {{ end }} + {{ end }} + S{{ season_number | math.format '00' }}E{{ episode_number | math.format '00' }} + {{ season_number - 1 }}.{{ episode_number - 1 }}.0/1 + {{ if show_has_content_rating }} + {{ for rating in show_content_rating | string.split '/' }} + {{ if rating | string.downcase | string.starts_with 'us:' }} + + {{ else }} + + {{ end }} + {{ rating | string.replace 'us:' '' | string.replace 'US:' '' }} + + {{ end }} + {{ end }} + + diff --git a/ErsatzTV/Resources/Templates/_movie.sbntxt b/ErsatzTV/Resources/Templates/_movie.sbntxt new file mode 100644 index 000000000..501365f5b --- /dev/null +++ b/ErsatzTV/Resources/Templates/_movie.sbntxt @@ -0,0 +1,56 @@ +{{ ## + +Available values: + - programme_start + - programme_stop + - channel_number + - has_custom_title + - custom_title + - movie_title + - movie_has_plot + - movie_plot + - movie_has_year + - movie_year + - movie_genres + - movie_has_artwork + - movie_artwork_url + - movie_has_content_rating + - movie_content_rating + - movie_guids + +The resulting XML will be minified by ErsatzTV - so feel free to keep things nicely formatted here. + +## }} + + + {{ if has_custom_title }} + {{ custom_title }} + {{ else }} + {{ movie_title }} + {{ if movie_has_plot }} + {{ movie_plot }} + {{ end }} + {{ if movie_has_year }} + {{ movie_year }} + {{ end }} + Movie + {{ for genre in movie_genres }} + {{ genre }} + {{ end }} + {{ if movie_has_artwork }} + + {{ end }} + {{ end }} + {{ if movie_has_content_rating }} + {{ for rating in movie_content_rating | string.split '/' }} + {{ if rating | string.starts_with 'us:' }} + + {{ else }} + + {{ end }} + {{ rating | string.replace 'us:' '' }} + + {{ end }} + {{ end }} + + diff --git a/ErsatzTV/Services/RunOnce/ResourceExtractorService.cs b/ErsatzTV/Services/RunOnce/ResourceExtractorService.cs index bd00b03e8..7fe1b110c 100644 --- a/ErsatzTV/Services/RunOnce/ResourceExtractorService.cs +++ b/ErsatzTV/Services/RunOnce/ResourceExtractorService.cs @@ -42,6 +42,24 @@ public class ResourceExtractorService : BackgroundService "_ArtistTitleAlbum_CenterTop.sbntxt", FileSystemLayout.MusicVideoCreditsTemplatesFolder, stoppingToken); + + await ExtractTemplateResource( + assembly, + "_channel.sbntxt", + FileSystemLayout.ChannelGuideTemplatesFolder, + stoppingToken); + + await ExtractTemplateResource( + assembly, + "_movie.sbntxt", + FileSystemLayout.ChannelGuideTemplatesFolder, + stoppingToken); + + await ExtractTemplateResource( + assembly, + "_episode.sbntxt", + FileSystemLayout.ChannelGuideTemplatesFolder, + stoppingToken); await ExtractScriptResource( assembly, diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index d0a9efbd0..c713bd21a 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -327,49 +327,26 @@ public class Startup "https://github.com/ErsatzTV/ErsatzTV", "https://discord.gg/hHaJm3yGy6"); - if (!Directory.Exists(FileSystemLayout.AppDataFolder)) - { - Directory.CreateDirectory(FileSystemLayout.AppDataFolder); - } + List directoriesToCreate = + [ + FileSystemLayout.AppDataFolder, + FileSystemLayout.TranscodeFolder, + FileSystemLayout.TempFilePoolFolder, + FileSystemLayout.FontsCacheFolder, + FileSystemLayout.TemplatesFolder, + FileSystemLayout.MusicVideoCreditsTemplatesFolder, + FileSystemLayout.ChannelGuideTemplatesFolder, + FileSystemLayout.ScriptsFolder, + FileSystemLayout.MultiEpisodeShuffleTemplatesFolder, + FileSystemLayout.AudioStreamSelectorScriptsFolder + ]; - if (!Directory.Exists(FileSystemLayout.TranscodeFolder)) + foreach (string directory in directoriesToCreate) { - Directory.CreateDirectory(FileSystemLayout.TranscodeFolder); - } - - if (!Directory.Exists(FileSystemLayout.TempFilePoolFolder)) - { - Directory.CreateDirectory(FileSystemLayout.TempFilePoolFolder); - } - - if (!Directory.Exists(FileSystemLayout.FontsCacheFolder)) - { - Directory.CreateDirectory(FileSystemLayout.FontsCacheFolder); - } - - if (!Directory.Exists(FileSystemLayout.TemplatesFolder)) - { - Directory.CreateDirectory(FileSystemLayout.TemplatesFolder); - } - - if (!Directory.Exists(FileSystemLayout.MusicVideoCreditsTemplatesFolder)) - { - Directory.CreateDirectory(FileSystemLayout.MusicVideoCreditsTemplatesFolder); - } - - if (!Directory.Exists(FileSystemLayout.ScriptsFolder)) - { - Directory.CreateDirectory(FileSystemLayout.ScriptsFolder); - } - - if (!Directory.Exists(FileSystemLayout.MultiEpisodeShuffleTemplatesFolder)) - { - Directory.CreateDirectory(FileSystemLayout.MultiEpisodeShuffleTemplatesFolder); - } - - if (!Directory.Exists(FileSystemLayout.AudioStreamSelectorScriptsFolder)) - { - Directory.CreateDirectory(FileSystemLayout.AudioStreamSelectorScriptsFolder); + if (directory is not null && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } } // until we add a setting for a file-specific scheme://host:port to access