2
0

XmlTvListingsProvider.cs 12 KB

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