XmlTvListingsProvider.cs 12 KB

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