XmlTvListingsProvider.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. }).ConfigureAwait(false);
  71. _fileSystem.CreateDirectory(Path.GetDirectoryName(cacheFile));
  72. using (var stream = _fileSystem.OpenRead(tempFile))
  73. {
  74. using (var reader = new StreamReader(stream, Encoding.UTF8))
  75. {
  76. using (var fileStream = _fileSystem.GetFileStream(cacheFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  77. {
  78. using (var writer = new StreamWriter(fileStream))
  79. {
  80. while (!reader.EndOfStream)
  81. {
  82. writer.WriteLine(reader.ReadLine());
  83. }
  84. }
  85. }
  86. }
  87. }
  88. _logger.Debug("Returning xmltv path {0}", cacheFile);
  89. return cacheFile;
  90. }
  91. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelNumber, string channelName, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  92. {
  93. if (!await EmbyTV.EmbyTVRegistration.Instance.EnableXmlTv().ConfigureAwait(false))
  94. {
  95. var length = endDateUtc - startDateUtc;
  96. if (length.TotalDays > 1)
  97. {
  98. endDateUtc = startDateUtc.AddDays(1);
  99. }
  100. }
  101. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  102. var reader = new XmlTvReader(path, GetLanguage());
  103. var results = reader.GetProgrammes(channelNumber, startDateUtc, endDateUtc, cancellationToken);
  104. return results.Select(p => GetProgramInfo(p, info));
  105. }
  106. private ProgramInfo GetProgramInfo(XmlTvProgram p, ListingsProviderInfo info)
  107. {
  108. var episodeTitle = p.Episode == null ? null : p.Episode.Title;
  109. var programInfo = new ProgramInfo
  110. {
  111. ChannelId = p.ChannelId,
  112. EndDate = GetDate(p.EndDate),
  113. EpisodeNumber = p.Episode == null ? null : p.Episode.Episode,
  114. EpisodeTitle = episodeTitle,
  115. Genres = p.Categories,
  116. Id = String.Format("{0}_{1:O}", p.ChannelId, p.StartDate), // Construct an id from the channel and start date,
  117. StartDate = GetDate(p.StartDate),
  118. Name = p.Title,
  119. Overview = p.Description,
  120. ShortOverview = p.Description,
  121. ProductionYear = !p.CopyrightDate.HasValue ? (int?)null : p.CopyrightDate.Value.Year,
  122. SeasonNumber = p.Episode == null ? null : p.Episode.Series,
  123. IsSeries = p.Episode != null,
  124. IsRepeat = p.IsPreviouslyShown && !p.IsNew,
  125. IsPremiere = p.Premiere != null,
  126. IsKids = p.Categories.Any(c => info.KidsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  127. IsMovie = p.Categories.Any(c => info.MovieCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  128. IsNews = p.Categories.Any(c => info.NewsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  129. IsSports = p.Categories.Any(c => info.SportsCategories.Contains(c, StringComparer.OrdinalIgnoreCase)),
  130. ImageUrl = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source) ? p.Icon.Source : null,
  131. HasImage = p.Icon != null && !String.IsNullOrEmpty(p.Icon.Source),
  132. OfficialRating = p.Rating != null && !String.IsNullOrEmpty(p.Rating.Value) ? p.Rating.Value : null,
  133. CommunityRating = p.StarRating.HasValue ? p.StarRating.Value : (float?)null,
  134. SeriesId = p.Episode != null ? p.Title.GetMD5().ToString("N") : null,
  135. ShowId = ((p.Title ?? string.Empty) + (episodeTitle ?? string.Empty)).GetMD5().ToString("N")
  136. };
  137. if (programInfo.IsMovie)
  138. {
  139. programInfo.IsSeries = false;
  140. programInfo.EpisodeNumber = null;
  141. programInfo.EpisodeTitle = null;
  142. }
  143. return programInfo;
  144. }
  145. private DateTime GetDate(DateTime date)
  146. {
  147. if (date.Kind != DateTimeKind.Utc)
  148. {
  149. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  150. }
  151. return date;
  152. }
  153. public async Task AddMetadata(ListingsProviderInfo info, List<ChannelInfo> channels, CancellationToken cancellationToken)
  154. {
  155. // Add the channel image url
  156. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  157. var reader = new XmlTvReader(path, GetLanguage());
  158. var results = reader.GetChannels().ToList();
  159. if (channels != null)
  160. {
  161. foreach (var c in channels)
  162. {
  163. var channelNumber = info.GetMappedChannel(c.Number);
  164. var match = results.FirstOrDefault(r => string.Equals(r.Id, channelNumber, StringComparison.OrdinalIgnoreCase));
  165. if (match != null && match.Icon != null && !String.IsNullOrEmpty(match.Icon.Source))
  166. {
  167. c.ImageUrl = match.Icon.Source;
  168. }
  169. }
  170. }
  171. }
  172. public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  173. {
  174. // Assume all urls are valid. check files for existence
  175. if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !_fileSystem.FileExists(info.Path))
  176. {
  177. throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path);
  178. }
  179. return Task.FromResult(true);
  180. }
  181. public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  182. {
  183. // In theory this should never be called because there is always only one lineup
  184. var path = await GetXml(info.Path, CancellationToken.None).ConfigureAwait(false);
  185. var reader = new XmlTvReader(path, GetLanguage());
  186. var results = reader.GetChannels();
  187. // Should this method be async?
  188. return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList();
  189. }
  190. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  191. {
  192. // In theory this should never be called because there is always only one lineup
  193. var path = await GetXml(info.Path, cancellationToken).ConfigureAwait(false);
  194. var reader = new XmlTvReader(path, GetLanguage());
  195. var results = reader.GetChannels();
  196. // Should this method be async?
  197. return results.Select(c => new ChannelInfo()
  198. {
  199. Id = c.Id,
  200. Name = c.DisplayName,
  201. ImageUrl = c.Icon != null && !String.IsNullOrEmpty(c.Icon.Source) ? c.Icon.Source : null,
  202. Number = c.Id
  203. }).ToList();
  204. }
  205. }
  206. }