XmlTvListingsProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  73. await using (stream.ConfigureAwait(false))
  74. {
  75. return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwait(false);
  76. }
  77. }
  78. else
  79. {
  80. var stream = AsyncFile.OpenRead(info.Path);
  81. await using (stream.ConfigureAwait(false))
  82. {
  83. return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwait(false);
  84. }
  85. }
  86. }
  87. private async Task<string> UnzipIfNeededAndCopy(string originalUrl, Stream stream, string file, CancellationToken cancellationToken)
  88. {
  89. var fileStream = new FileStream(
  90. file,
  91. FileMode.CreateNew,
  92. FileAccess.Write,
  93. FileShare.None,
  94. IODefaults.FileStreamBufferSize,
  95. FileOptions.Asynchronous);
  96. await using (fileStream.ConfigureAwait(false))
  97. {
  98. if (Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gz", StringComparison.OrdinalIgnoreCase))
  99. {
  100. try
  101. {
  102. using var reader = new GZipStream(stream, CompressionMode.Decompress);
  103. await reader.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  104. }
  105. catch (Exception ex)
  106. {
  107. _logger.LogError(ex, "Error extracting from gz file {File}", originalUrl);
  108. }
  109. }
  110. else
  111. {
  112. await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  113. }
  114. return file;
  115. }
  116. }
  117. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  118. {
  119. if (string.IsNullOrWhiteSpace(channelId))
  120. {
  121. throw new ArgumentNullException(nameof(channelId));
  122. }
  123. _logger.LogDebug("Getting xmltv programs for channel {Id}", channelId);
  124. string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
  125. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  126. var reader = new XmlTvReader(path, GetLanguage(info));
  127. return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken)
  128. .Select(p => GetProgramInfo(p, info));
  129. }
  130. private static ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info)
  131. {
  132. string episodeTitle = program.Episode.Title;
  133. var programCategories = program.Categories.Where(c => !string.IsNullOrWhiteSpace(c)).ToList();
  134. var programInfo = new ProgramInfo
  135. {
  136. ChannelId = program.ChannelId,
  137. EndDate = program.EndDate.UtcDateTime,
  138. EpisodeNumber = program.Episode.Episode,
  139. EpisodeTitle = episodeTitle,
  140. Genres = programCategories,
  141. StartDate = program.StartDate.UtcDateTime,
  142. Name = program.Title,
  143. Overview = program.Description,
  144. ProductionYear = program.CopyrightDate?.Year,
  145. SeasonNumber = program.Episode.Series,
  146. IsSeries = program.Episode.Series is not null,
  147. IsRepeat = program.IsPreviouslyShown && !program.IsNew,
  148. IsPremiere = program.Premiere is not null,
  149. IsKids = programCategories.Any(c => info.KidsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  150. IsMovie = programCategories.Any(c => info.MovieCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  151. IsNews = programCategories.Any(c => info.NewsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  152. IsSports = programCategories.Any(c => info.SportsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)),
  153. ImageUrl = string.IsNullOrEmpty(program.Icon?.Source) ? null : program.Icon.Source,
  154. HasImage = !string.IsNullOrEmpty(program.Icon?.Source),
  155. OfficialRating = string.IsNullOrEmpty(program.Rating?.Value) ? null : program.Rating.Value,
  156. CommunityRating = program.StarRating,
  157. SeriesId = program.Episode.Episode is null ? null : program.Title?.GetMD5().ToString("N", CultureInfo.InvariantCulture)
  158. };
  159. if (string.IsNullOrWhiteSpace(program.ProgramId))
  160. {
  161. string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty);
  162. if (programInfo.SeasonNumber.HasValue)
  163. {
  164. uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture);
  165. }
  166. if (programInfo.EpisodeNumber.HasValue)
  167. {
  168. uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture);
  169. }
  170. programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  171. // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped
  172. if (programInfo.IsSeries
  173. && !programInfo.IsRepeat
  174. && (programInfo.EpisodeNumber ?? 0) == 0)
  175. {
  176. programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture);
  177. }
  178. }
  179. else
  180. {
  181. programInfo.ShowId = program.ProgramId;
  182. }
  183. // Construct an id from the channel and start date
  184. programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDate);
  185. if (programInfo.IsMovie)
  186. {
  187. programInfo.IsSeries = false;
  188. programInfo.EpisodeNumber = null;
  189. programInfo.EpisodeTitle = null;
  190. }
  191. return programInfo;
  192. }
  193. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  194. {
  195. // Assume all urls are valid. check files for existence
  196. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
  197. {
  198. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  199. }
  200. return Task.CompletedTask;
  201. }
  202. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  203. {
  204. // In theory this should never be called because there is always only one lineup
  205. string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false);
  206. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  207. var reader = new XmlTvReader(path, GetLanguage(info));
  208. IEnumerable<XmlTvChannel> results = reader.GetChannels();
  209. // Should this method be async?
  210. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  211. }
  212. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  213. {
  214. // In theory this should never be called because there is always only one lineup
  215. string path = await GetXml(info, cancellationToken).ConfigureAwait(false);
  216. _logger.LogDebug("Opening XmlTvReader for {Path}", path);
  217. var reader = new XmlTvReader(path, GetLanguage(info));
  218. var results = reader.GetChannels();
  219. // Should this method be async?
  220. return results.Select(c => new ChannelInfo
  221. {
  222. Id = c.Id,
  223. Name = c.DisplayName,
  224. ImageUrl = string.IsNullOrEmpty(c.Icon?.Source) ? null : c.Icon.Source,
  225. Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number
  226. }).ToList();
  227. }
  228. }
  229. }