XmlTvListingsProvider.cs 12 KB

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