XmlTvListingsProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 programInfo = new ProgramInfo
  119. {
  120. ChannelId = program.ChannelId,
  121. EndDate = program.EndDate.UtcDateTime,
  122. EpisodeNumber = program.Episode?.Episode,
  123. EpisodeTitle = episodeTitle,
  124. Genres = program.Categories,
  125. StartDate = program.StartDate.UtcDateTime,
  126. Name = program.Title,
  127. Overview = program.Description,
  128. ProductionYear = program.CopyrightDate?.Year,
  129. SeasonNumber = program.Episode?.Series,
  130. IsSeries = program.Episode is not null,
  131. IsRepeat = program.IsPreviouslyShown && !program.IsNew,
  132. IsPremiere = program.Premiere is not null,
  133. IsKids = program.Categories.Any(c => info.KidsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  134. IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  135. IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  136. IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  137. ImageUrl = string.IsNullOrEmpty(program.Icon?.Source) ? null : program.Icon.Source,
  138. HasImage = !string.IsNullOrEmpty(program.Icon?.Source),
  139. OfficialRating = string.IsNullOrEmpty(program.Rating?.Value) ? null : program.Rating.Value,
  140. CommunityRating = program.StarRating,
  141. SeriesId = program.Episode is null ? null : program.Title?.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  142. };
  143. if (string.IsNullOrWhiteSpace(program.ProgramId))
  144. {
  145. string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty);
  146. if (programInfo.SeasonNumber.HasValue)
  147. {
  148. uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture);
  149. }
  150. if (programInfo.EpisodeNumber.HasValue)
  151. {
  152. uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
  153. }
  154. programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  155. // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
  156. if (programInfo.IsSeries
  157. && !programInfo.IsRepeat
  158. && (programInfo.EpisodeNumber ?? 0) == 0)
  159. {
  160. programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
  161. }
  162. }
  163. else
  164. {
  165. programInfo.ShowId = program.ProgramId;
  166. }
  167. // Construct an id from the channel and start date
  168. programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDate);
  169. if (programInfo.IsMovie)
  170. {
  171. programInfo.IsSeries = false;
  172. programInfo.EpisodeNumber = null;
  173. programInfo.EpisodeTitle = null;
  174. }
  175. return programInfo;
  176. }
  177. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  178. {
  179. // Assume all urls are valid. check files for existence
  180. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
  181. {
  182. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  183. }
  184. return Task.CompletedTask;
  185. }
  186. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  187. {
  188. // In theory this should never be called because there is always only one lineup
  189. string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false);
  190. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  191. var reader = new XmlTvReader(path, GetLanguage(info));
  192. IEnumerable<XmlTvChannel> results = reader.GetChannels();
  193. // Should this method be async?
  194. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  195. }
  196. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  197. {
  198. // In theory this should never be called because there is always only one lineup
  199. string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
  200. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  201. var reader = new XmlTvReader(path, GetLanguage(info));
  202. var results = reader.GetChannels();
  203. // Should this method be async?
  204. return results.Select(c => new ChannelInfo
  205. {
  206. Id = c.Id,
  207. Name = c.DisplayName,
  208. ImageUrl = string.IsNullOrEmpty(c.Icon.Source) ? null : c.Icon.Source,
  209. Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number
  210. }).ToList();
  211. }
  212. }
  213. }