XmlTvListingsProvider.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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.Linq;
  9. using System.Net;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Emby.XmlTv.Classes;
  14. using Emby.XmlTv.Entities;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Model.Logging;
  19. namespace MediaBrowser.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. public XmlTvListingsProvider(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger)
  27. {
  28. _config = config;
  29. _httpClient = httpClient;
  30. _logger = logger;
  31. }
  32. public string Name
  33. {
  34. get { return "XmlTV"; }
  35. }
  36. public string Type
  37. {
  38. get { return "xmltv"; }
  39. }
  40. private string GetLanguage()
  41. {
  42. return _config.Configuration.PreferredMetadataLanguage;
  43. }
  44. private async Task<string> GetXml(string path, CancellationToken cancellationToken)
  45. {
  46. _logger.Info("xmltv path: {0}", path);
  47. if (!path.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  48. {
  49. return path;
  50. }
  51. var cacheFilename = DateTime.UtcNow.DayOfYear.ToString(CultureInfo.InvariantCulture) + "-" + DateTime.UtcNow.Hour.ToString(CultureInfo.InvariantCulture) + ".xml";
  52. var cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename);
  53. if (File.Exists(cacheFile))
  54. {
  55. return cacheFile;
  56. }
  57. _logger.Info("Downloading xmltv listings from {0}", path);
  58. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  59. {
  60. CancellationToken = cancellationToken,
  61. Url = path,
  62. Progress = new Progress<Double>(),
  63. DecompressionMethod = DecompressionMethods.GZip,
  64. // It's going to come back gzipped regardless of this value
  65. // So we need to make sure the decompression method is set to gzip
  66. EnableHttpCompression = true
  67. }).ConfigureAwait(false);
  68. Directory.CreateDirectory(Path.GetDirectoryName(cacheFile));
  69. using (var stream = File.OpenRead(tempFile))
  70. {
  71. using (var reader = new StreamReader(stream, Encoding.UTF8))
  72. {
  73. using (var fileStream = File.OpenWrite(cacheFile))
  74. {
  75. using (var writer = new StreamWriter(fileStream))
  76. {
  77. while (!reader.EndOfStream)
  78. {
  79. writer.WriteLine(reader.ReadLine());
  80. }
  81. }
  82. }
  83. }
  84. }
  85. _logger.Debug("Returning xmltv path {0}", cacheFile);
  86. return cacheFile;
  87. }
  88. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelNumber, string channelName, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  89. {
  90. if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false))
  91. {
  92. var length = endDateUtc - startDateUtc;
  93. if (length.TotalDays > 1)
  94. {
  95. endDateUtc = startDateUtc.AddDays(1);
  96. }
  97. }
  98. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  99. var reader = new XmlTvReader(path, GetLanguage(), null);
  100. var results = reader.GetProgrammes(channelNumber, startDateUtc, endDateUtc, cancellationToken);
  101. return results.Select(p => GetProgramInfo(p, info));
  102. }
  103. private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info)
  104. {
  105. var programInfo = new ProgramInfo
  106. {
  107. ChannelId = p.ChannelId,
  108. EndDate = GetDate(p.EndDate),
  109. EpisodeNumber = p.Episode == null ? null : p.Episode.Episode,
  110. EpisodeTitle = p.Episode == null ? null : p.Episode.Title,
  111. Genres = p.Categories,
  112. Id = String.Format("{0}_{1:O}", p.ChannelId, p.StartDate), // Construct an id from the channel and start date,
  113. StartDate = GetDate(p.StartDate),
  114. Name = p.Title,
  115. Overview = p.Description,
  116. ShortOverview = p.Description,
  117. ProductionYear = !p.CopyrightDate.HasValue ? (int?)null : p.CopyrightDate.Value.Year,
  118. SeasonNumber = p.Episode == null ? null : p.Episode.Series,
  119. IsSeries = p.Episode != null,
  120. IsRepeat = p.IsRepeat,
  121. IsPremiere = p.Premiere != null,
  122. IsKids = p.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  123. IsMovie = p.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  124. IsNews = p.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  125. IsSports = p.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  126. ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null,
  127. HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source),
  128. OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null,
  129. CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null,
  130. SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null
  131. };
  132. if (programInfo.IsMovie)
  133. {
  134. programInfo.IsSeries = false;
  135. programInfo.EpisodeNumber = null;
  136. programInfo.EpisodeTitle = null;
  137. }
  138. return programInfo;
  139. }
  140. private DateTime GetDate(DateTime date)
  141. {
  142. if (date.Kind != DateTimeKind.Utc)
  143. {
  144. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  145. }
  146. return date;
  147. }
  148. public async Task AddMetadata(ListingsProviderInfo info, List<ChannelInfo> channels, CancellationToken cancellationToken)
  149. {
  150. // Add the channel image url
  151. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  152. var reader = new XmlTvReader(path, GetLanguage(), null);
  153. var results = reader.GetChannels().ToList();
  154. if (channels != null)
  155. {
  156. channels.ForEach(c =>
  157. {
  158. var channelNumber = info.GetMappedChannel(c.Number);
  159. var match = results.FirstOrDefault(r => string.Equals(r.Id, channelNumber, StringComparison.OrdinalIgnoreCase));
  160. if (match != null && match.Icon != null && !String.IsNullOrEmpty(match.Icon.Source))
  161. {
  162. c.ImageUrl = match.Icon.Source;
  163. }
  164. });
  165. }
  166. }
  167. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  168. {
  169. // Assume all urls are valid. check files for existence
  170. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
  171. {
  172. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  173. }
  174. return Task.FromResult(true);
  175. }
  176. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  177. {
  178. // In theory this should never be called because there is always only one lineup
  179. var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false);
  180. var reader = new XmlTvReader(path, GetLanguage(), null);
  181. var results = reader.GetChannels();
  182. // Should this method be async?
  183. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  184. }
  185. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  186. {
  187. // In theory this should never be called because there is always only one lineup
  188. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  189. var reader = new XmlTvReader(path, GetLanguage(), null);
  190. var results = reader.GetChannels();
  191. // Should this method be async?
  192. return results.Select(c => new ChannelInfo()
  193. {
  194. Id = c.Id,
  195. Name = c.DisplayName,
  196. ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null,
  197. Number = c.Id
  198. }).ToList();
  199. }
  200. }
  201. }