XmlTvListingsProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 IHttpClient _httpClient;
  27. private readonly ILogger<XmlTvListingsProvider> _logger;
  28. private readonly IFileSystem _fileSystem;
  29. private readonly IZipClient _zipClient;
  30. public XmlTvListingsProvider(
  31. IServerConfigurationManager config,
  32. IHttpClient httpClient,
  33. ILogger<XmlTvListingsProvider> logger,
  34. IFileSystem fileSystem,
  35. IZipClient zipClient)
  36. {
  37. _config = config;
  38. _httpClient = httpClient;
  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 res = await _httpClient.SendAsync(
  69. new HttpRequestOptions
  70. {
  71. CancellationToken = cancellationToken,
  72. Url = path,
  73. DecompressionMethod = CompressionMethods.Gzip,
  74. },
  75. HttpMethod.Get).ConfigureAwait(false))
  76. using (var stream = res.Content)
  77. using (var fileStream = new FileStream(cacheFile, FileMode.CreateNew))
  78. {
  79. if (res.ContentHeaders.ContentEncoding.Contains("gzip"))
  80. {
  81. using (var gzStream = new GZipStream(stream, CompressionMode.Decompress))
  82. {
  83. await gzStream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  84. }
  85. }
  86. else
  87. {
  88. await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
  89. }
  90. }
  91. return UnzipIfNeeded(path, cacheFile);
  92. }
  93. private string UnzipIfNeeded(string originalUrl, string file)
  94. {
  95. string ext = Path.GetExtension(originalUrl.Split('?')[0]);
  96. if (string.Equals(ext, ".gz", StringComparison.OrdinalIgnoreCase))
  97. {
  98. try
  99. {
  100. string tempFolder = ExtractGz(file);
  101. return FindXmlFile(tempFolder);
  102. }
  103. catch (Exception ex)
  104. {
  105. _logger.LogError(ex, "Error extracting from gz file {File}", file);
  106. }
  107. try
  108. {
  109. string tempFolder = ExtractFirstFileFromGz(file);
  110. return FindXmlFile(tempFolder);
  111. }
  112. catch (Exception ex)
  113. {
  114. _logger.LogError(ex, "Error extracting from zip file {File}", file);
  115. }
  116. }
  117. return file;
  118. }
  119. private string ExtractFirstFileFromGz(string file)
  120. {
  121. using (var stream = File.OpenRead(file))
  122. {
  123. string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
  124. Directory.CreateDirectory(tempFolder);
  125. _zipClient.ExtractFirstFileFromGz(stream, tempFolder, "data.xml");
  126. return tempFolder;
  127. }
  128. }
  129. private string ExtractGz(string file)
  130. {
  131. using (var stream = File.OpenRead(file))
  132. {
  133. string tempFolder = Path.Combine(_config.ApplicationPaths.TempDirectory, Guid.NewGuid().ToString());
  134. Directory.CreateDirectory(tempFolder);
  135. _zipClient.ExtractAllFromGz(stream, tempFolder, true);
  136. return tempFolder;
  137. }
  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.Path, 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, StringComparer.OrdinalIgnoreCase)),
  178. IsMovie = program.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  179. IsNews = program.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  180. IsSports = program.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.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.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("{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.Path, 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.Path, 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. }