XmlTvListingsProvider.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 => new ProgramInfo()
  102. {
  103. ChannelId = p.ChannelId,
  104. EndDate = GetDate(p.EndDate),
  105. EpisodeNumber = p.Episode == null ? null : p.Episode.Episode,
  106. EpisodeTitle = p.Episode == null ? null : p.Episode.Title,
  107. Genres = p.Categories,
  108. Id = String.Format("{0}_{1:O}", p.ChannelId, p.StartDate), // Construct an id from the channel and start date,
  109. StartDate = GetDate(p.StartDate),
  110. Name = p.Title,
  111. Overview = p.Description,
  112. ShortOverview = p.Description,
  113. ProductionYear = !p.CopyrightDate.HasValue ? (int?)null : p.CopyrightDate.Value.Year,
  114. SeasonNumber = p.Episode == null ? null : p.Episode.Series,
  115. IsSeries = p.Episode != null,
  116. IsRepeat = p.IsRepeat,
  117. IsPremiere = p.Premiere != null,
  118. IsKids = p.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  119. IsMovie = p.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  120. IsNews = p.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  121. IsSports = p.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.InvariantCultureIgnoreCase)),
  122. ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null,
  123. HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source),
  124. OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null,
  125. CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null,
  126. SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null
  127. });
  128. }
  129. private DateTime GetDate(DateTime date)
  130. {
  131. if (date.Kind != DateTimeKind.Utc)
  132. {
  133. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  134. }
  135. return date;
  136. }
  137. public async Task AddMetadata(ListingsProviderInfo info, List<ChannelInfo> channels, CancellationToken cancellationToken)
  138. {
  139. // Add the channel image url
  140. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  141. var reader = new XmlTvReader(path, GetLanguage(), null);
  142. var results = reader.GetChannels().ToList();
  143. if (channels != null)
  144. {
  145. channels.ForEach(c =>
  146. {
  147. var channelNumber = info.GetMappedChannel(c.Number);
  148. var match = results.FirstOrDefault(r => string.Equals(r.Id, channelNumber, StringComparison.OrdinalIgnoreCase));
  149. if (match != null && match.Icon != null && !String.IsNullOrEmpty(match.Icon.Source))
  150. {
  151. c.ImageUrl = match.Icon.Source;
  152. }
  153. });
  154. }
  155. }
  156. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  157. {
  158. // Assume all urls are valid. check files for existence
  159. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path))
  160. {
  161. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  162. }
  163. return Task.FromResult(true);
  164. }
  165. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  166. {
  167. // In theory this should never be called because there is always only one lineup
  168. var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false);
  169. var reader = new XmlTvReader(path, GetLanguage(), null);
  170. var results = reader.GetChannels();
  171. // Should this method be async?
  172. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  173. }
  174. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  175. {
  176. // In theory this should never be called because there is always only one lineup
  177. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  178. var reader = new XmlTvReader(path, GetLanguage(), null);
  179. var results = reader.GetChannels();
  180. // Should this method be async?
  181. return results.Select(c => new ChannelInfo()
  182. {
  183. Id = c.Id,
  184. Name = c.DisplayName,
  185. ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null,
  186. Number = c.Id
  187. }).ToList();
  188. }
  189. }
  190. }