XmlTvListingsProvider.cs 12 KB

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