XmlTvListingsProvider.cs 9.8 KB

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