XmlTvListingsProvider.cs 12 KB

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