XmlTvListingsProvider.cs 12 KB

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