| | | 1 | | #pragma warning disable CS1591 |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.IO.Compression; |
| | | 8 | | using System.Linq; |
| | | 9 | | using System.Net.Http; |
| | | 10 | | using System.Threading; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | using Jellyfin.Extensions; |
| | | 13 | | using Jellyfin.XmlTv; |
| | | 14 | | using Jellyfin.XmlTv.Entities; |
| | | 15 | | using Jellyfin.XmlTv.Enums; |
| | | 16 | | using MediaBrowser.Common.Extensions; |
| | | 17 | | using MediaBrowser.Common.Net; |
| | | 18 | | using MediaBrowser.Controller.Configuration; |
| | | 19 | | using MediaBrowser.Controller.LiveTv; |
| | | 20 | | using MediaBrowser.Model.Dto; |
| | | 21 | | using MediaBrowser.Model.IO; |
| | | 22 | | using MediaBrowser.Model.LiveTv; |
| | | 23 | | using Microsoft.Extensions.Logging; |
| | | 24 | | |
| | | 25 | | namespace Jellyfin.LiveTv.Listings |
| | | 26 | | { |
| | | 27 | | public class XmlTvListingsProvider : IListingsProvider |
| | | 28 | | { |
| | 0 | 29 | | private static readonly TimeSpan _maxCacheAge = TimeSpan.FromHours(1); |
| | | 30 | | |
| | | 31 | | private readonly IServerConfigurationManager _config; |
| | | 32 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 33 | | private readonly ILogger<XmlTvListingsProvider> _logger; |
| | | 34 | | |
| | | 35 | | public XmlTvListingsProvider( |
| | | 36 | | IServerConfigurationManager config, |
| | | 37 | | IHttpClientFactory httpClientFactory, |
| | | 38 | | ILogger<XmlTvListingsProvider> logger) |
| | | 39 | | { |
| | 25 | 40 | | _config = config; |
| | 25 | 41 | | _httpClientFactory = httpClientFactory; |
| | 25 | 42 | | _logger = logger; |
| | 25 | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | public string Name => "XmlTV"; |
| | | 46 | | |
| | 0 | 47 | | public string Type => "xmltv"; |
| | | 48 | | |
| | | 49 | | private string GetLanguage(ListingsProviderInfo info) |
| | | 50 | | { |
| | 4 | 51 | | if (!string.IsNullOrWhiteSpace(info.PreferredLanguage)) |
| | | 52 | | { |
| | 0 | 53 | | return info.PreferredLanguage; |
| | | 54 | | } |
| | | 55 | | |
| | 4 | 56 | | return _config.Configuration.PreferredMetadataLanguage; |
| | | 57 | | } |
| | | 58 | | |
| | | 59 | | private async Task<string> GetXml(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 60 | | { |
| | 4 | 61 | | _logger.LogInformation("xmltv path: {Path}", info.Path); |
| | | 62 | | |
| | 4 | 63 | | string cacheFilename = info.Id + ".xml"; |
| | 4 | 64 | | string cacheDir = Path.Join(_config.ApplicationPaths.CachePath, "xmltv"); |
| | 4 | 65 | | string cacheFile = Path.Join(cacheDir, cacheFilename); |
| | | 66 | | |
| | 4 | 67 | | if (File.Exists(cacheFile)) |
| | | 68 | | { |
| | 0 | 69 | | if (File.GetLastWriteTimeUtc(cacheFile) >= DateTime.UtcNow.Subtract(_maxCacheAge)) |
| | | 70 | | { |
| | 0 | 71 | | return cacheFile; |
| | | 72 | | } |
| | | 73 | | |
| | 0 | 74 | | File.Delete(cacheFile); |
| | | 75 | | } |
| | | 76 | | else |
| | | 77 | | { |
| | 4 | 78 | | Directory.CreateDirectory(cacheDir); |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | try |
| | | 82 | | { |
| | 4 | 83 | | if (info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) |
| | | 84 | | { |
| | 2 | 85 | | _logger.LogInformation("Downloading xmltv listings from {Path}", info.Path); |
| | | 86 | | |
| | 2 | 87 | | using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(info.Path, |
| | 2 | 88 | | var redirectedUrl = response.RequestMessage?.RequestUri?.ToString() ?? info.Path; |
| | 2 | 89 | | var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | 2 | 90 | | await using (stream.ConfigureAwait(false)) |
| | | 91 | | { |
| | 2 | 92 | | return await UnzipIfNeededAndCopy(redirectedUrl, stream, cacheFile, cancellationToken).Configure |
| | | 93 | | } |
| | 0 | 94 | | } |
| | | 95 | | else |
| | | 96 | | { |
| | 2 | 97 | | var stream = AsyncFile.OpenRead(info.Path); |
| | 2 | 98 | | await using (stream.ConfigureAwait(false)) |
| | | 99 | | { |
| | 2 | 100 | | return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwai |
| | | 101 | | } |
| | | 102 | | } |
| | 0 | 103 | | } |
| | 0 | 104 | | catch (Exception ex) |
| | | 105 | | { |
| | 0 | 106 | | _logger.LogError(ex, "Error downloading or processing XMLTV file from {Path}", info.Path); |
| | | 107 | | |
| | 0 | 108 | | if (File.Exists(cacheFile)) |
| | | 109 | | { |
| | 0 | 110 | | File.Delete(cacheFile); |
| | | 111 | | } |
| | | 112 | | |
| | 0 | 113 | | throw; |
| | | 114 | | } |
| | 4 | 115 | | } |
| | | 116 | | |
| | | 117 | | private async Task<string> UnzipIfNeededAndCopy(string originalUrl, Stream stream, string file, CancellationToke |
| | | 118 | | { |
| | 4 | 119 | | var fileStream = new FileStream( |
| | 4 | 120 | | file, |
| | 4 | 121 | | FileMode.CreateNew, |
| | 4 | 122 | | FileAccess.Write, |
| | 4 | 123 | | FileShare.None, |
| | 4 | 124 | | IODefaults.FileStreamBufferSize, |
| | 4 | 125 | | FileOptions.Asynchronous); |
| | | 126 | | |
| | 4 | 127 | | await using (fileStream.ConfigureAwait(false)) |
| | | 128 | | { |
| | 4 | 129 | | if (Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gz", StringComparison.OrdinalIgnoreCa |
| | 4 | 130 | | Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gzip", StringComparison.OrdinalIgnore |
| | | 131 | | { |
| | | 132 | | try |
| | | 133 | | { |
| | 0 | 134 | | using var reader = new GZipStream(stream, CompressionMode.Decompress); |
| | 0 | 135 | | await reader.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); |
| | 0 | 136 | | } |
| | 0 | 137 | | catch (Exception ex) |
| | | 138 | | { |
| | 0 | 139 | | _logger.LogError(ex, "Error extracting from gz file {File}", originalUrl); |
| | 0 | 140 | | } |
| | | 141 | | } |
| | | 142 | | else |
| | | 143 | | { |
| | 4 | 144 | | await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); |
| | | 145 | | } |
| | | 146 | | } |
| | | 147 | | |
| | 4 | 148 | | var fileInfo = new FileInfo(file); |
| | 4 | 149 | | if (!fileInfo.Exists || fileInfo.Length == 0) |
| | | 150 | | { |
| | 0 | 151 | | if (fileInfo.Exists) |
| | | 152 | | { |
| | 0 | 153 | | File.Delete(file); |
| | | 154 | | } |
| | | 155 | | |
| | 0 | 156 | | throw new InvalidOperationException("Downloaded XMLTV file is empty: " + originalUrl); |
| | | 157 | | } |
| | | 158 | | |
| | 4 | 159 | | return file; |
| | 4 | 160 | | } |
| | | 161 | | |
| | | 162 | | public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTi |
| | | 163 | | { |
| | 4 | 164 | | if (string.IsNullOrWhiteSpace(channelId)) |
| | | 165 | | { |
| | 0 | 166 | | throw new ArgumentNullException(nameof(channelId)); |
| | | 167 | | } |
| | | 168 | | |
| | 4 | 169 | | _logger.LogDebug("Getting xmltv programs for channel {Id}", channelId); |
| | | 170 | | |
| | 4 | 171 | | string path = await GetXml(info, cancellationToken).ConfigureAwait(false); |
| | 4 | 172 | | _logger.LogDebug("Opening XmlTvReader for {Path}", path); |
| | 4 | 173 | | var reader = new XmlTvReader(path, GetLanguage(info)); |
| | | 174 | | |
| | 4 | 175 | | return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) |
| | 4 | 176 | | .Select(p => GetProgramInfo(p, info)); |
| | 4 | 177 | | } |
| | | 178 | | |
| | | 179 | | private static ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) |
| | | 180 | | { |
| | 4 | 181 | | string? episodeTitle = program.Episode?.Title; |
| | 4 | 182 | | var programCategories = program.Categories.Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); |
| | 4 | 183 | | var imageUrl = program.Icons.FirstOrDefault()?.Source; |
| | 4 | 184 | | var episodeImageUrl = program.Images?.FirstOrDefault(m => m.Type == ImageType.Still)?.Path; |
| | 4 | 185 | | var backgroundImageUrl = program.Images?.FirstOrDefault(m => m.Type == ImageType.Backdrop)?.Path; |
| | 4 | 186 | | var rating = program.Ratings.FirstOrDefault()?.Value; |
| | 4 | 187 | | var starRating = program.StarRatings?.FirstOrDefault()?.StarRating; |
| | | 188 | | |
| | 4 | 189 | | var programInfo = new ProgramInfo |
| | 4 | 190 | | { |
| | 4 | 191 | | ChannelId = program.ChannelId, |
| | 4 | 192 | | EndDate = program.EndDate.UtcDateTime, |
| | 4 | 193 | | EpisodeNumber = program.Episode?.Episode, |
| | 4 | 194 | | EpisodeTitle = episodeTitle, |
| | 4 | 195 | | Genres = programCategories, |
| | 4 | 196 | | StartDate = program.StartDate.UtcDateTime, |
| | 4 | 197 | | Name = program.Title, |
| | 4 | 198 | | Overview = program.Description, |
| | 4 | 199 | | ProductionYear = program.CopyrightDate?.Year, |
| | 4 | 200 | | SeasonNumber = program.Episode?.Series, |
| | 4 | 201 | | IsSeries = program.Episode?.Episode is not null, |
| | 4 | 202 | | IsRepeat = program.IsPreviouslyShown && !program.IsNew, |
| | 4 | 203 | | IsPremiere = program.Premiere is not null, |
| | 4 | 204 | | IsLive = program.IsLive, |
| | 4 | 205 | | IsKids = programCategories.Any(c => info.KidsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)) |
| | 4 | 206 | | IsMovie = programCategories.Any(c => info.MovieCategories.Contains(c, StringComparison.OrdinalIgnoreCase |
| | 4 | 207 | | IsNews = programCategories.Any(c => info.NewsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)) |
| | 4 | 208 | | IsSports = programCategories.Any(c => info.SportsCategories.Contains(c, StringComparison.OrdinalIgnoreCa |
| | 4 | 209 | | ImageUrl = string.IsNullOrEmpty(imageUrl) ? null : imageUrl, |
| | 4 | 210 | | HasImage = !string.IsNullOrEmpty(imageUrl), |
| | 4 | 211 | | BackdropImageUrl = string.IsNullOrEmpty(backgroundImageUrl) ? null : backgroundImageUrl, |
| | 4 | 212 | | ThumbImageUrl = string.IsNullOrEmpty(episodeImageUrl) ? null : episodeImageUrl, |
| | 4 | 213 | | OfficialRating = string.IsNullOrEmpty(rating) ? null : rating, |
| | 4 | 214 | | CommunityRating = starRating is null ? null : (float)starRating.Value, |
| | 4 | 215 | | SeriesId = program.Episode?.Episode is null ? null : program.Title?.GetMD5().ToString("N", CultureInfo.I |
| | 4 | 216 | | }; |
| | | 217 | | |
| | 4 | 218 | | if (string.IsNullOrWhiteSpace(program.ProgramId)) |
| | | 219 | | { |
| | 4 | 220 | | string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty); |
| | | 221 | | |
| | 4 | 222 | | if (programInfo.SeasonNumber.HasValue) |
| | | 223 | | { |
| | 0 | 224 | | uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture); |
| | | 225 | | } |
| | | 226 | | |
| | 4 | 227 | | if (programInfo.EpisodeNumber.HasValue) |
| | | 228 | | { |
| | 0 | 229 | | uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture); |
| | | 230 | | } |
| | | 231 | | |
| | 4 | 232 | | programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture); |
| | | 233 | | |
| | | 234 | | // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skip |
| | 4 | 235 | | if (programInfo.IsSeries |
| | 4 | 236 | | && !programInfo.IsRepeat |
| | 4 | 237 | | && (programInfo.EpisodeNumber ?? 0) == 0) |
| | | 238 | | { |
| | 0 | 239 | | programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); |
| | | 240 | | } |
| | | 241 | | } |
| | | 242 | | else |
| | | 243 | | { |
| | 0 | 244 | | programInfo.ShowId = program.ProgramId; |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | // Construct an id from the channel and start date |
| | 4 | 248 | | programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDa |
| | | 249 | | |
| | 4 | 250 | | if (programInfo.IsMovie) |
| | | 251 | | { |
| | 0 | 252 | | programInfo.IsSeries = false; |
| | 0 | 253 | | programInfo.EpisodeNumber = null; |
| | 0 | 254 | | programInfo.EpisodeTitle = null; |
| | | 255 | | } |
| | | 256 | | |
| | 4 | 257 | | return programInfo; |
| | | 258 | | } |
| | | 259 | | |
| | | 260 | | public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) |
| | | 261 | | { |
| | | 262 | | // Assume all urls are valid. check files for existence |
| | 0 | 263 | | if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path)) |
| | | 264 | | { |
| | 0 | 265 | | throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); |
| | | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | return Task.CompletedTask; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location) |
| | | 272 | | { |
| | | 273 | | // In theory this should never be called because there is always only one lineup |
| | 0 | 274 | | string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false); |
| | 0 | 275 | | _logger.LogDebug("Opening XmlTvReader for {Path}", path); |
| | 0 | 276 | | var reader = new XmlTvReader(path, GetLanguage(info)); |
| | 0 | 277 | | IEnumerable<XmlTvChannel> results = reader.GetChannels(); |
| | | 278 | | |
| | | 279 | | // Should this method be async? |
| | 0 | 280 | | return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); |
| | 0 | 281 | | } |
| | | 282 | | |
| | | 283 | | public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 284 | | { |
| | | 285 | | // In theory this should never be called because there is always only one lineup |
| | 0 | 286 | | string path = await GetXml(info, cancellationToken).ConfigureAwait(false); |
| | 0 | 287 | | _logger.LogDebug("Opening XmlTvReader for {Path}", path); |
| | 0 | 288 | | var reader = new XmlTvReader(path, GetLanguage(info)); |
| | 0 | 289 | | var results = reader.GetChannels(); |
| | | 290 | | |
| | | 291 | | // Should this method be async? |
| | 0 | 292 | | return results.Select(c => new ChannelInfo |
| | 0 | 293 | | { |
| | 0 | 294 | | Id = c.Id, |
| | 0 | 295 | | Name = c.DisplayName, |
| | 0 | 296 | | ImageUrl = string.IsNullOrEmpty(c.Icons.FirstOrDefault()?.Source) ? null : c.Icons.FirstOrDefault()!.Sou |
| | 0 | 297 | | Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number |
| | 0 | 298 | | }).ToList(); |
| | 0 | 299 | | } |
| | | 300 | | } |
| | | 301 | | } |