XmlTvListingsProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #nullable disable
  2. #pragma warning disable CS1591
  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 MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.LiveTv;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.LiveTv;
  22. using Microsoft.Extensions.Logging;
  23. namespace Emby.Server.Implementations.LiveTv.Listings
  24. {
  25. public class XmlTvListingsProvider : IListingsProvider
  26. {
  27. private static readonly TimeSpan _maxCacheAge = TimeSpan.FromHours(1);
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IHttpClientFactory _httpClientFactory;
  30. private readonly ILogger<XmlTvListingsProvider> _logger;
  31. public XmlTvListingsProvider(
  32. IServerConfigurationManager config,
  33. IHttpClientFactory httpClientFactory,
  34. ILogger<XmlTvListingsProvider> logger)
  35. {
  36. _config = config;
  37. _httpClientFactory = httpClientFactory;
  38. _logger = logger;
  39. }
  40. public string Name => "XmlTV";
  41. public string Type => "xmltv";
  42. private string GetLanguage(ListingsProviderInfo info)
  43. {
  44. if (!string.IsNullOrWhiteSpace(info.PreferredLanguage))
  45. {
  46. return info.PreferredLanguage;
  47. }
  48. return _config.Configuration.PreferredMetadataLanguage;
  49. }
  50. private async Task<string> GetXml(ListingsProviderInfo info, CancellationToken cancellationToken)
  51. {
  52. _logger.LogInformation("xmltv path: {Path}", info.Path);
  53. string cacheFilename = info.Id + ".xml";
  54. string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename);
  55. if (File.Exists(cacheFile) && File.GetLastWriteTimeUtc(cacheFile) >= DateTime.UtcNow.Subtract(_maxCacheAge))
  56. {
  57. return cacheFile;
  58. }
  59. // Must check if file exists as parent directory may not exist.
  60. if (File.Exists(cacheFile))
  61. {
  62. File.Delete(cacheFile);
  63. }
  64. else
  65. {
  66. Directory.CreateDirectory(Path.GetDirectoryName(cacheFile));
  67. }
  68. if (info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  69. {
  70. _logger.LogInformation("Downloading xmltv listings from {Path}", info.Path);
  71. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(info.Path, cancellationToken).ConfigureAwait(false);
  72. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  73. return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwait(false);
  74. }
  75. else
  76. {
  77. await using var stream = AsyncFile.OpenRead(info.Path);
  78. return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwait(false);
  79. }
  80. }
  81. private async Task<string> UnzipIfNeededAndCopy(string originalUrl, Stream stream, string file, CancellationToken cancellationToken)
  82. {
  83. await using var fileStream = new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  84. if (Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gz", StringComparison.OrdinalIgnoreCase))
  85. {
  86. try
  87. {
  88. using var reader = new GZipStream(stream, CompressionMode.Decompress);
  89. await reader.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  90. }
  91. catch (Exception ex)
  92. {
  93. _logger.LogError(ex, "Error extracting from gz file {File}", originalUrl);
  94. }
  95. }
  96. else
  97. {
  98. await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  99. }
  100. return file;
  101. }
  102. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  103. {
  104. if (string.IsNullOrWhiteSpace(channelId))
  105. {
  106. throw new ArgumentNullException(nameof(channelId));
  107. }
  108. _logger.LogDebug("Getting xmltv programs for channel {Id}", channelId);
  109. string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
  110. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  111. var reader = new XmlTvReader(path, GetLanguage(info));
  112. return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken)
  113. .Select(p => GetProgramInfo(p, info));
  114. }
  115. private static ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info)
  116. {
  117. string episodeTitle = program.Episode.Title;
  118. var programCategories = program.Categories.Where(c => !string.IsNullOrWhiteSpace(c)).ToList();
  119. var programInfo = new ProgramInfo
  120. {
  121. ChannelId = program.ChannelId,
  122. EndDate = program.EndDate.UtcDateTime,
  123. EpisodeNumber = program.Episode.Episode,
  124. EpisodeTitle = episodeTitle,
  125. Genres = programCategories,
  126. StartDate = program.StartDate.UtcDateTime,
  127. Name = program.Title,
  128. Overview = program.Description,
  129. ProductionYear = program.CopyrightDate?.Year,
  130. SeasonNumber = program.Episode.Series,
  131. IsSeries = program.Episode.Series is not null,
  132. IsRepeat = program.IsPreviouslyShown && !program.IsNew,
  133. IsPremiere = program.Premiere is not null,
  134. IsKids = programCategories.Any(c => info.KidsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  135. IsMovie = programCategories.Any(c => info.MovieCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  136. IsNews = programCategories.Any(c => info.NewsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  137. IsSports = programCategories.Any(c => info.SportsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  138. ImageUrl = string.IsNullOrEmpty(program.Icon?.Source) ? null : program.Icon.Source,
  139. HasImage = !string.IsNullOrEmpty(program.Icon?.Source),
  140. OfficialRating = string.IsNullOrEmpty(program.Rating?.Value) ? null : program.Rating.Value,
  141. CommunityRating = program.StarRating,
  142. SeriesId = program.Episode.Episode is null ? null : program.Title?.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  143. };
  144. if (string.IsNullOrWhiteSpace(program.ProgramId))
  145. {
  146. string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty);
  147. if (programInfo.SeasonNumber.HasValue)
  148. {
  149. uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture);
  150. }
  151. if (programInfo.EpisodeNumber.HasValue)
  152. {
  153. uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
  154. }
  155. programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  156. // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
  157. if (programInfo.IsSeries
  158. && !programInfo.IsRepeat
  159. && (programInfo.EpisodeNumber ?? 0) == 0)
  160. {
  161. programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
  162. }
  163. }
  164. else
  165. {
  166. programInfo.ShowId = program.ProgramId;
  167. }
  168. // Construct an id from the channel and start date
  169. programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDate);
  170. if (programInfo.IsMovie)
  171. {
  172. programInfo.IsSeries = false;
  173. programInfo.EpisodeNumber = null;
  174. programInfo.EpisodeTitle = null;
  175. }
  176. return programInfo;
  177. }
  178. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  179. {
  180. // Assume all urls are valid. check files for existence
  181. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
  182. {
  183. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  184. }
  185. return Task.CompletedTask;
  186. }
  187. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  188. {
  189. // In theory this should never be called because there is always only one lineup
  190. string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false);
  191. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  192. var reader = new XmlTvReader(path, GetLanguage(info));
  193. IEnumerable<XmlTvChannel> results = reader.GetChannels();
  194. // Should this method be async?
  195. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  196. }
  197. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  198. {
  199. // In theory this should never be called because there is always only one lineup
  200. string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
  201. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  202. var reader = new XmlTvReader(path, GetLanguage(info));
  203. var results = reader.GetChannels();
  204. // Should this method be async?
  205. return results.Select(c => new ChannelInfo
  206. {
  207. Id = c.Id,
  208. Name = c.DisplayName,
  209. ImageUrl = string.IsNullOrEmpty(c.Icon?.Source) ? null : c.Icon.Source,
  210. Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number
  211. }).ToList();
  212. }
  213. }
  214. }