XmlTvListingsProvider.cs 12 KB

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