XmlTvListingsProvider.cs 9.0 KB

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