XmlTvListingsProvider.cs 12 KB

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