XmlTvListingsProvider.cs 12 KB

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