XmlTvListingsProvider.cs 11 KB

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