XmlTvListingsProvider.cs 12 KB

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