XmlTvListingsProvider.cs 12 KB

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