XmlTvListingsProvider.cs 9.6 KB

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