XmlTvListingsProvider.cs 11 KB

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