SchedulesDirect.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. using System.Net;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.LiveTv;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.LiveTv;
  7. using Microsoft.Extensions.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using MediaBrowser.Model.Extensions;
  19. using MediaBrowser.Controller.Entities.TV;
  20. using MediaBrowser.Controller.Providers;
  21. using MediaBrowser.Model.Entities;
  22. namespace Emby.Server.Implementations.LiveTv.Listings
  23. {
  24. public class SchedulesDirect : IListingsProvider
  25. {
  26. private readonly ILogger _logger;
  27. private readonly IJsonSerializer _jsonSerializer;
  28. private readonly IHttpClient _httpClient;
  29. private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
  30. private readonly IApplicationHost _appHost;
  31. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  32. private readonly Dictionary<string, Dictionary<string, ScheduleDirect.Station>> _channelPairingCache =
  33. new Dictionary<string, Dictionary<string, ScheduleDirect.Station>>(StringComparer.OrdinalIgnoreCase);
  34. public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
  35. {
  36. _logger = logger;
  37. _jsonSerializer = jsonSerializer;
  38. _httpClient = httpClient;
  39. _appHost = appHost;
  40. }
  41. private string UserAgent
  42. {
  43. get { return "Emby/" + _appHost.ApplicationVersion; }
  44. }
  45. private List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  46. {
  47. List<string> dates = new List<string>();
  48. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  49. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  50. while (start <= end)
  51. {
  52. dates.Add(start.ToString("yyyy-MM-dd"));
  53. start = start.AddDays(1);
  54. }
  55. return dates;
  56. }
  57. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  58. {
  59. if (string.IsNullOrEmpty(channelId))
  60. {
  61. throw new ArgumentNullException("channelId");
  62. }
  63. // Normalize incoming input
  64. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  65. List<ProgramInfo> programsInfo = new List<ProgramInfo>();
  66. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  67. if (string.IsNullOrEmpty(token))
  68. {
  69. _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
  70. return programsInfo;
  71. }
  72. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  73. string stationID = channelId;
  74. _logger.LogInformation("Channel Station ID is: " + stationID);
  75. List<ScheduleDirect.RequestScheduleForChannel> requestList =
  76. new List<ScheduleDirect.RequestScheduleForChannel>()
  77. {
  78. new ScheduleDirect.RequestScheduleForChannel()
  79. {
  80. stationID = stationID,
  81. date = dates
  82. }
  83. };
  84. var requestString = _jsonSerializer.SerializeToString(requestList);
  85. _logger.LogDebug("Request string for schedules is: " + requestString);
  86. var httpOptions = new HttpRequestOptions()
  87. {
  88. Url = ApiUrl + "/schedules",
  89. UserAgent = UserAgent,
  90. CancellationToken = cancellationToken,
  91. // The data can be large so give it some extra time
  92. TimeoutMs = 60000,
  93. LogErrorResponseBody = true
  94. };
  95. httpOptions.RequestHeaders["token"] = token;
  96. httpOptions.RequestContent = requestString;
  97. using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
  98. {
  99. StreamReader reader = new StreamReader(response.Content);
  100. string responseString = reader.ReadToEnd();
  101. var dailySchedules = _jsonSerializer.DeserializeFromString<List<ScheduleDirect.Day>>(responseString);
  102. _logger.LogDebug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect");
  103. httpOptions = new HttpRequestOptions()
  104. {
  105. Url = ApiUrl + "/programs",
  106. UserAgent = UserAgent,
  107. CancellationToken = cancellationToken,
  108. LogErrorResponseBody = true,
  109. // The data can be large so give it some extra time
  110. TimeoutMs = 60000
  111. };
  112. httpOptions.RequestHeaders["token"] = token;
  113. List<string> programsID = new List<string>();
  114. programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList();
  115. var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]";
  116. httpOptions.RequestContent = requestBody;
  117. double wideAspect = 1.77777778;
  118. var primaryImageCategory = "Logo";
  119. using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
  120. {
  121. StreamReader innerReader = new StreamReader(innerResponse.Content);
  122. responseString = innerReader.ReadToEnd();
  123. var programDetails =
  124. _jsonSerializer.DeserializeFromString<List<ScheduleDirect.ProgramDetails>>(
  125. responseString);
  126. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  127. var programIdsWithImages =
  128. programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID)
  129. .ToList();
  130. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  131. var schedules = dailySchedules.SelectMany(d => d.programs);
  132. foreach (ScheduleDirect.Program schedule in schedules)
  133. {
  134. //_logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
  135. // " which corresponds to channel " + channelNumber + " and program id " +
  136. // schedule.programID + " which says it has images? " +
  137. // programDict[schedule.programID].hasImageArtwork);
  138. if (images != null)
  139. {
  140. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  141. if (imageIndex > -1)
  142. {
  143. var programEntry = programDict[schedule.programID];
  144. var allImages = (images[imageIndex].data ?? new List<ScheduleDirect.ImageData>()).ToList();
  145. var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
  146. var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
  147. double desiredAspect = 0.666666667;
  148. programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ??
  149. GetProgramImage(ApiUrl, allImages, true, desiredAspect);
  150. programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect);
  151. // Don't supply the same image twice
  152. if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
  153. {
  154. programEntry.thumbImage = null;
  155. }
  156. programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, wideAspect);
  157. //programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  158. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  159. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  160. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  161. }
  162. }
  163. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
  164. }
  165. }
  166. }
  167. return programsInfo;
  168. }
  169. private int GetSizeOrder(ScheduleDirect.ImageData image)
  170. {
  171. if (!string.IsNullOrWhiteSpace(image.height))
  172. {
  173. int value;
  174. if (int.TryParse(image.height, out value))
  175. {
  176. return value;
  177. }
  178. }
  179. return 0;
  180. }
  181. private string GetChannelNumber(ScheduleDirect.Map map)
  182. {
  183. var channelNumber = map.logicalChannelNumber;
  184. if (string.IsNullOrWhiteSpace(channelNumber))
  185. {
  186. channelNumber = map.channel;
  187. }
  188. if (string.IsNullOrWhiteSpace(channelNumber))
  189. {
  190. channelNumber = map.atscMajor + "." + map.atscMinor;
  191. }
  192. channelNumber = channelNumber.TrimStart('0');
  193. return channelNumber;
  194. }
  195. private bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
  196. {
  197. return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase);
  198. }
  199. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  200. {
  201. DateTime startAt = GetDate(programInfo.airDateTime);
  202. DateTime endAt = startAt.AddSeconds(programInfo.duration);
  203. ProgramAudio audioType = ProgramAudio.Stereo;
  204. var programId = programInfo.programID ?? string.Empty;
  205. string newID = programId + "T" + startAt.Ticks + "C" + channelId;
  206. if (programInfo.audioProperties != null)
  207. {
  208. if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
  209. {
  210. audioType = ProgramAudio.Atmos;
  211. }
  212. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  213. {
  214. audioType = ProgramAudio.DolbyDigital;
  215. }
  216. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  217. {
  218. audioType = ProgramAudio.DolbyDigital;
  219. }
  220. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  221. {
  222. audioType = ProgramAudio.Stereo;
  223. }
  224. else
  225. {
  226. audioType = ProgramAudio.Mono;
  227. }
  228. }
  229. string episodeTitle = null;
  230. if (details.episodeTitle150 != null)
  231. {
  232. episodeTitle = details.episodeTitle150;
  233. }
  234. var info = new ProgramInfo
  235. {
  236. ChannelId = channelId,
  237. Id = newID,
  238. StartDate = startAt,
  239. EndDate = endAt,
  240. Name = details.titles[0].title120 ?? "Unkown",
  241. OfficialRating = null,
  242. CommunityRating = null,
  243. EpisodeTitle = episodeTitle,
  244. Audio = audioType,
  245. //IsNew = programInfo.@new ?? false,
  246. IsRepeat = programInfo.@new == null,
  247. IsSeries = string.Equals(details.entityType, "episode", StringComparison.OrdinalIgnoreCase),
  248. ImageUrl = details.primaryImage,
  249. ThumbImageUrl = details.thumbImage,
  250. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  251. IsSports = string.Equals(details.entityType, "sports", StringComparison.OrdinalIgnoreCase),
  252. IsMovie = IsMovie(details),
  253. Etag = programInfo.md5,
  254. IsLive = string.Equals(programInfo.liveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
  255. IsPremiere = programInfo.premiere || (programInfo.isPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
  256. };
  257. var showId = programId;
  258. if (!info.IsSeries)
  259. {
  260. // It's also a series if it starts with SH
  261. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  262. }
  263. // According to SchedulesDirect, these are generic, unidentified episodes
  264. // SH005316560000
  265. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  266. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  267. if (!hasUniqueShowId)
  268. {
  269. showId = newID;
  270. }
  271. info.ShowId = showId;
  272. if (programInfo.videoProperties != null)
  273. {
  274. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  275. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  276. }
  277. if (details.contentRating != null && details.contentRating.Count > 0)
  278. {
  279. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
  280. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  281. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  282. {
  283. info.OfficialRating = null;
  284. }
  285. }
  286. if (details.descriptions != null)
  287. {
  288. if (details.descriptions.description1000 != null && details.descriptions.description1000.Count > 0)
  289. {
  290. info.Overview = details.descriptions.description1000[0].description;
  291. }
  292. else if (details.descriptions.description100 != null && details.descriptions.description100.Count > 0)
  293. {
  294. info.Overview = details.descriptions.description100[0].description;
  295. }
  296. }
  297. if (info.IsSeries)
  298. {
  299. info.SeriesId = programId.Substring(0, 10);
  300. info.SeriesProviderIds[MetadataProviders.Zap2It.ToString()] = info.SeriesId;
  301. if (details.metadata != null)
  302. {
  303. foreach (var metadataProgram in details.metadata)
  304. {
  305. var gracenote = metadataProgram.Gracenote;
  306. if (gracenote != null)
  307. {
  308. info.SeasonNumber = gracenote.season;
  309. if (gracenote.episode > 0)
  310. {
  311. info.EpisodeNumber = gracenote.episode;
  312. }
  313. break;
  314. }
  315. }
  316. }
  317. }
  318. if (!string.IsNullOrWhiteSpace(details.originalAirDate))
  319. {
  320. info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
  321. info.ProductionYear = info.OriginalAirDate.Value.Year;
  322. }
  323. if (details.movie != null)
  324. {
  325. int year;
  326. if (!string.IsNullOrEmpty(details.movie.year) && int.TryParse(details.movie.year, out year))
  327. {
  328. info.ProductionYear = year;
  329. }
  330. }
  331. if (details.genres != null)
  332. {
  333. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  334. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  335. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  336. {
  337. info.IsKids = true;
  338. }
  339. }
  340. return info;
  341. }
  342. private DateTime GetDate(string value)
  343. {
  344. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  345. if (date.Kind != DateTimeKind.Utc)
  346. {
  347. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  348. }
  349. return date;
  350. }
  351. private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
  352. {
  353. string url = null;
  354. var matches = images;
  355. matches = matches
  356. .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i)))
  357. .ThenByDescending(GetSizeOrder)
  358. .ToList();
  359. var match = matches.FirstOrDefault();
  360. if (match == null)
  361. {
  362. return null;
  363. }
  364. var uri = match.uri;
  365. if (!string.IsNullOrWhiteSpace(uri))
  366. {
  367. if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  368. {
  369. url = uri;
  370. }
  371. else
  372. {
  373. url = apiUrl + "/image/" + uri;
  374. }
  375. }
  376. //_logger.LogDebug("URL for image is : " + url);
  377. return url;
  378. }
  379. private double GetApsectRatio(ScheduleDirect.ImageData i)
  380. {
  381. int width = 0;
  382. int height = 0;
  383. if (!string.IsNullOrWhiteSpace(i.width))
  384. {
  385. int.TryParse(i.width, out width);
  386. }
  387. if (!string.IsNullOrWhiteSpace(i.height))
  388. {
  389. int.TryParse(i.height, out height);
  390. }
  391. if (height == 0 || width == 0)
  392. {
  393. return 0;
  394. }
  395. double result = width;
  396. result /= height;
  397. return result;
  398. }
  399. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  400. ListingsProviderInfo info,
  401. List<string> programIds,
  402. CancellationToken cancellationToken)
  403. {
  404. if (programIds.Count == 0)
  405. {
  406. return new List<ScheduleDirect.ShowImages>();
  407. }
  408. var imageIdString = "[";
  409. foreach (var i in programIds)
  410. {
  411. var imageId = i.Substring(0, 10);
  412. if (!imageIdString.Contains(imageId))
  413. {
  414. imageIdString += "\"" + imageId + "\",";
  415. }
  416. }
  417. imageIdString = imageIdString.TrimEnd(',') + "]";
  418. var httpOptions = new HttpRequestOptions()
  419. {
  420. Url = ApiUrl + "/metadata/programs",
  421. UserAgent = UserAgent,
  422. CancellationToken = cancellationToken,
  423. RequestContent = imageIdString,
  424. LogErrorResponseBody = true,
  425. // The data can be large so give it some extra time
  426. TimeoutMs = 60000
  427. };
  428. try
  429. {
  430. using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
  431. {
  432. return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(
  433. innerResponse2.Content).ConfigureAwait(false);
  434. }
  435. }
  436. catch (Exception ex)
  437. {
  438. _logger.LogError(ex, "Error getting image info from schedules direct");
  439. return new List<ScheduleDirect.ShowImages>();
  440. }
  441. }
  442. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  443. {
  444. var token = await GetToken(info, cancellationToken);
  445. var lineups = new List<NameIdPair>();
  446. if (string.IsNullOrWhiteSpace(token))
  447. {
  448. return lineups;
  449. }
  450. var options = new HttpRequestOptions()
  451. {
  452. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  453. UserAgent = UserAgent,
  454. CancellationToken = cancellationToken,
  455. LogErrorResponseBody = true
  456. };
  457. options.RequestHeaders["token"] = token;
  458. try
  459. {
  460. using (var httpResponse = await Get(options, false, info).ConfigureAwait(false))
  461. using (Stream responce = httpResponse.Content)
  462. {
  463. var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false);
  464. if (root != null)
  465. {
  466. foreach (ScheduleDirect.Headends headend in root)
  467. {
  468. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  469. {
  470. lineups.Add(new NameIdPair
  471. {
  472. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  473. Id = lineup.uri.Substring(18)
  474. });
  475. }
  476. }
  477. }
  478. else
  479. {
  480. _logger.LogInformation("No lineups available");
  481. }
  482. }
  483. }
  484. catch (Exception ex)
  485. {
  486. _logger.LogError(ex, "Error getting headends");
  487. }
  488. return lineups;
  489. }
  490. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  491. private DateTime _lastErrorResponse;
  492. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  493. {
  494. var username = info.Username;
  495. // Reset the token if there's no username
  496. if (string.IsNullOrWhiteSpace(username))
  497. {
  498. return null;
  499. }
  500. var password = info.Password;
  501. if (string.IsNullOrEmpty(password))
  502. {
  503. return null;
  504. }
  505. // Avoid hammering SD
  506. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  507. {
  508. return null;
  509. }
  510. NameValuePair savedToken = null;
  511. if (!_tokens.TryGetValue(username, out savedToken))
  512. {
  513. savedToken = new NameValuePair();
  514. _tokens.TryAdd(username, savedToken);
  515. }
  516. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  517. {
  518. long ticks;
  519. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
  520. {
  521. // If it's under 24 hours old we can still use it
  522. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  523. {
  524. return savedToken.Name;
  525. }
  526. }
  527. }
  528. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  529. try
  530. {
  531. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  532. savedToken.Name = result;
  533. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  534. return result;
  535. }
  536. catch (HttpException ex)
  537. {
  538. if (ex.StatusCode.HasValue)
  539. {
  540. if ((int)ex.StatusCode.Value == 400)
  541. {
  542. _tokens.Clear();
  543. _lastErrorResponse = DateTime.UtcNow;
  544. }
  545. }
  546. throw;
  547. }
  548. finally
  549. {
  550. _tokenSemaphore.Release();
  551. }
  552. }
  553. private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
  554. bool enableRetry,
  555. ListingsProviderInfo providerInfo)
  556. {
  557. // Schedules direct requires that the client support compression and will return a 400 response without it
  558. options.EnableHttpCompression = true;
  559. // On windows 7 under .net core, this header is not getting added
  560. #if NETSTANDARD2_0
  561. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  562. {
  563. options.RequestHeaders["Accept-Encoding"] = "deflate";
  564. }
  565. #endif
  566. try
  567. {
  568. return await _httpClient.Post(options).ConfigureAwait(false);
  569. }
  570. catch (HttpException ex)
  571. {
  572. _tokens.Clear();
  573. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  574. {
  575. enableRetry = false;
  576. }
  577. if (!enableRetry)
  578. {
  579. throw;
  580. }
  581. }
  582. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  583. options.RequestHeaders["token"] = newToken;
  584. return await Post(options, false, providerInfo).ConfigureAwait(false);
  585. }
  586. private async Task<HttpResponseInfo> Get(HttpRequestOptions options,
  587. bool enableRetry,
  588. ListingsProviderInfo providerInfo)
  589. {
  590. // Schedules direct requires that the client support compression and will return a 400 response without it
  591. options.EnableHttpCompression = true;
  592. // On windows 7 under .net core, this header is not getting added
  593. #if NETSTANDARD2_0
  594. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  595. {
  596. options.RequestHeaders["Accept-Encoding"] = "deflate";
  597. }
  598. #endif
  599. try
  600. {
  601. return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false);
  602. }
  603. catch (HttpException ex)
  604. {
  605. _tokens.Clear();
  606. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  607. {
  608. enableRetry = false;
  609. }
  610. if (!enableRetry)
  611. {
  612. throw;
  613. }
  614. }
  615. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  616. options.RequestHeaders["token"] = newToken;
  617. return await Get(options, false, providerInfo).ConfigureAwait(false);
  618. }
  619. private async Task<string> GetTokenInternal(string username, string password,
  620. CancellationToken cancellationToken)
  621. {
  622. var httpOptions = new HttpRequestOptions()
  623. {
  624. Url = ApiUrl + "/token",
  625. UserAgent = UserAgent,
  626. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  627. CancellationToken = cancellationToken,
  628. LogErrorResponseBody = true
  629. };
  630. //_logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  631. // httpOptions.RequestContent);
  632. using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false))
  633. {
  634. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(responce.Content).ConfigureAwait(false);
  635. if (root.message == "OK")
  636. {
  637. _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
  638. return root.token;
  639. }
  640. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  641. }
  642. }
  643. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  644. {
  645. var token = await GetToken(info, cancellationToken);
  646. if (string.IsNullOrEmpty(token))
  647. {
  648. throw new ArgumentException("Authentication required.");
  649. }
  650. if (string.IsNullOrEmpty(info.ListingsId))
  651. {
  652. throw new ArgumentException("Listings Id required");
  653. }
  654. _logger.LogInformation("Adding new LineUp ");
  655. var httpOptions = new HttpRequestOptions()
  656. {
  657. Url = ApiUrl + "/lineups/" + info.ListingsId,
  658. UserAgent = UserAgent,
  659. CancellationToken = cancellationToken,
  660. LogErrorResponseBody = true,
  661. BufferContent = false
  662. };
  663. httpOptions.RequestHeaders["token"] = token;
  664. using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
  665. {
  666. }
  667. }
  668. public string Name
  669. {
  670. get { return "Schedules Direct"; }
  671. }
  672. public static string TypeName = "SchedulesDirect";
  673. public string Type
  674. {
  675. get { return TypeName; }
  676. }
  677. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  678. {
  679. if (string.IsNullOrEmpty(info.ListingsId))
  680. {
  681. throw new ArgumentException("Listings Id required");
  682. }
  683. var token = await GetToken(info, cancellationToken);
  684. if (string.IsNullOrEmpty(token))
  685. {
  686. throw new Exception("token required");
  687. }
  688. _logger.LogInformation("Headends on account ");
  689. var options = new HttpRequestOptions()
  690. {
  691. Url = ApiUrl + "/lineups",
  692. UserAgent = UserAgent,
  693. CancellationToken = cancellationToken,
  694. LogErrorResponseBody = true
  695. };
  696. options.RequestHeaders["token"] = token;
  697. try
  698. {
  699. using (var httpResponse = await Get(options, false, null).ConfigureAwait(false))
  700. {
  701. using (var response = httpResponse.Content)
  702. {
  703. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false);
  704. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  705. }
  706. }
  707. }
  708. catch (HttpException ex)
  709. {
  710. // Apparently we're supposed to swallow this
  711. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  712. {
  713. return false;
  714. }
  715. throw;
  716. }
  717. }
  718. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  719. {
  720. if (validateLogin)
  721. {
  722. if (string.IsNullOrEmpty(info.Username))
  723. {
  724. throw new ArgumentException("Username is required");
  725. }
  726. if (string.IsNullOrEmpty(info.Password))
  727. {
  728. throw new ArgumentException("Password is required");
  729. }
  730. }
  731. if (validateListings)
  732. {
  733. if (string.IsNullOrEmpty(info.ListingsId))
  734. {
  735. throw new ArgumentException("Listings Id required");
  736. }
  737. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  738. if (!hasLineup)
  739. {
  740. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  741. }
  742. }
  743. }
  744. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  745. {
  746. return GetHeadends(info, country, location, CancellationToken.None);
  747. }
  748. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  749. {
  750. var listingsId = info.ListingsId;
  751. if (string.IsNullOrEmpty(listingsId))
  752. {
  753. throw new Exception("ListingsId required");
  754. }
  755. var token = await GetToken(info, cancellationToken);
  756. if (string.IsNullOrEmpty(token))
  757. {
  758. throw new Exception("token required");
  759. }
  760. var httpOptions = new HttpRequestOptions()
  761. {
  762. Url = ApiUrl + "/lineups/" + listingsId,
  763. UserAgent = UserAgent,
  764. CancellationToken = cancellationToken,
  765. LogErrorResponseBody = true,
  766. // The data can be large so give it some extra time
  767. TimeoutMs = 60000
  768. };
  769. httpOptions.RequestHeaders["token"] = token;
  770. var list = new List<ChannelInfo>();
  771. using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false))
  772. {
  773. using (var response = httpResponse.Content)
  774. {
  775. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false);
  776. _logger.LogInformation("Found " + root.map.Count + " channels on the lineup on ScheduleDirect");
  777. _logger.LogInformation("Mapping Stations to Channel");
  778. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  779. foreach (ScheduleDirect.Map map in root.map)
  780. {
  781. var channelNumber = GetChannelNumber(map);
  782. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  783. if (station == null)
  784. {
  785. station = new ScheduleDirect.Station
  786. {
  787. stationID = map.stationID
  788. };
  789. }
  790. var name = channelNumber;
  791. var channelInfo = new ChannelInfo
  792. {
  793. Number = channelNumber,
  794. Name = name
  795. };
  796. if (station != null)
  797. {
  798. if (!string.IsNullOrWhiteSpace(station.name))
  799. {
  800. channelInfo.Name = station.name;
  801. }
  802. channelInfo.Id = station.stationID;
  803. channelInfo.CallSign = station.callsign;
  804. if (station.logo != null)
  805. {
  806. channelInfo.ImageUrl = station.logo.URL;
  807. }
  808. }
  809. list.Add(channelInfo);
  810. }
  811. }
  812. }
  813. return list;
  814. }
  815. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  816. {
  817. if (!string.IsNullOrWhiteSpace(channelName))
  818. {
  819. channelName = NormalizeName(channelName);
  820. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  821. if (result != null)
  822. {
  823. return result;
  824. }
  825. }
  826. if (!string.IsNullOrWhiteSpace(channelNumber))
  827. {
  828. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  829. }
  830. return null;
  831. }
  832. private string NormalizeName(string value)
  833. {
  834. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  835. }
  836. public class ScheduleDirect
  837. {
  838. public class Token
  839. {
  840. public int code { get; set; }
  841. public string message { get; set; }
  842. public string serverID { get; set; }
  843. public string token { get; set; }
  844. }
  845. public class Lineup
  846. {
  847. public string lineup { get; set; }
  848. public string name { get; set; }
  849. public string transport { get; set; }
  850. public string location { get; set; }
  851. public string uri { get; set; }
  852. }
  853. public class Lineups
  854. {
  855. public int code { get; set; }
  856. public string serverID { get; set; }
  857. public string datetime { get; set; }
  858. public List<Lineup> lineups { get; set; }
  859. }
  860. public class Headends
  861. {
  862. public string headend { get; set; }
  863. public string transport { get; set; }
  864. public string location { get; set; }
  865. public List<Lineup> lineups { get; set; }
  866. }
  867. public class Map
  868. {
  869. public string stationID { get; set; }
  870. public string channel { get; set; }
  871. public string logicalChannelNumber { get; set; }
  872. public int uhfVhf { get; set; }
  873. public int atscMajor { get; set; }
  874. public int atscMinor { get; set; }
  875. }
  876. public class Broadcaster
  877. {
  878. public string city { get; set; }
  879. public string state { get; set; }
  880. public string postalcode { get; set; }
  881. public string country { get; set; }
  882. }
  883. public class Logo
  884. {
  885. public string URL { get; set; }
  886. public int height { get; set; }
  887. public int width { get; set; }
  888. public string md5 { get; set; }
  889. }
  890. public class Station
  891. {
  892. public string stationID { get; set; }
  893. public string name { get; set; }
  894. public string callsign { get; set; }
  895. public List<string> broadcastLanguage { get; set; }
  896. public List<string> descriptionLanguage { get; set; }
  897. public Broadcaster broadcaster { get; set; }
  898. public string affiliate { get; set; }
  899. public Logo logo { get; set; }
  900. public bool? isCommercialFree { get; set; }
  901. }
  902. public class Metadata
  903. {
  904. public string lineup { get; set; }
  905. public string modified { get; set; }
  906. public string transport { get; set; }
  907. }
  908. public class Channel
  909. {
  910. public List<Map> map { get; set; }
  911. public List<Station> stations { get; set; }
  912. public Metadata metadata { get; set; }
  913. }
  914. public class RequestScheduleForChannel
  915. {
  916. public string stationID { get; set; }
  917. public List<string> date { get; set; }
  918. }
  919. public class Rating
  920. {
  921. public string body { get; set; }
  922. public string code { get; set; }
  923. }
  924. public class Multipart
  925. {
  926. public int partNumber { get; set; }
  927. public int totalParts { get; set; }
  928. }
  929. public class Program
  930. {
  931. public string programID { get; set; }
  932. public string airDateTime { get; set; }
  933. public int duration { get; set; }
  934. public string md5 { get; set; }
  935. public List<string> audioProperties { get; set; }
  936. public List<string> videoProperties { get; set; }
  937. public List<Rating> ratings { get; set; }
  938. public bool? @new { get; set; }
  939. public Multipart multipart { get; set; }
  940. public string liveTapeDelay { get; set; }
  941. public bool premiere { get; set; }
  942. public bool repeat { get; set; }
  943. public string isPremiereOrFinale { get; set; }
  944. }
  945. public class MetadataSchedule
  946. {
  947. public string modified { get; set; }
  948. public string md5 { get; set; }
  949. public string startDate { get; set; }
  950. public string endDate { get; set; }
  951. public int days { get; set; }
  952. }
  953. public class Day
  954. {
  955. public string stationID { get; set; }
  956. public List<Program> programs { get; set; }
  957. public MetadataSchedule metadata { get; set; }
  958. public Day()
  959. {
  960. programs = new List<Program>();
  961. }
  962. }
  963. //
  964. public class Title
  965. {
  966. public string title120 { get; set; }
  967. }
  968. public class EventDetails
  969. {
  970. public string subType { get; set; }
  971. }
  972. public class Description100
  973. {
  974. public string descriptionLanguage { get; set; }
  975. public string description { get; set; }
  976. }
  977. public class Description1000
  978. {
  979. public string descriptionLanguage { get; set; }
  980. public string description { get; set; }
  981. }
  982. public class DescriptionsProgram
  983. {
  984. public List<Description100> description100 { get; set; }
  985. public List<Description1000> description1000 { get; set; }
  986. }
  987. public class Gracenote
  988. {
  989. public int season { get; set; }
  990. public int episode { get; set; }
  991. }
  992. public class MetadataPrograms
  993. {
  994. public Gracenote Gracenote { get; set; }
  995. }
  996. public class ContentRating
  997. {
  998. public string body { get; set; }
  999. public string code { get; set; }
  1000. }
  1001. public class Cast
  1002. {
  1003. public string billingOrder { get; set; }
  1004. public string role { get; set; }
  1005. public string nameId { get; set; }
  1006. public string personId { get; set; }
  1007. public string name { get; set; }
  1008. public string characterName { get; set; }
  1009. }
  1010. public class Crew
  1011. {
  1012. public string billingOrder { get; set; }
  1013. public string role { get; set; }
  1014. public string nameId { get; set; }
  1015. public string personId { get; set; }
  1016. public string name { get; set; }
  1017. }
  1018. public class QualityRating
  1019. {
  1020. public string ratingsBody { get; set; }
  1021. public string rating { get; set; }
  1022. public string minRating { get; set; }
  1023. public string maxRating { get; set; }
  1024. public string increment { get; set; }
  1025. }
  1026. public class Movie
  1027. {
  1028. public string year { get; set; }
  1029. public int duration { get; set; }
  1030. public List<QualityRating> qualityRating { get; set; }
  1031. }
  1032. public class Recommendation
  1033. {
  1034. public string programID { get; set; }
  1035. public string title120 { get; set; }
  1036. }
  1037. public class ProgramDetails
  1038. {
  1039. public string audience { get; set; }
  1040. public string programID { get; set; }
  1041. public List<Title> titles { get; set; }
  1042. public EventDetails eventDetails { get; set; }
  1043. public DescriptionsProgram descriptions { get; set; }
  1044. public string originalAirDate { get; set; }
  1045. public List<string> genres { get; set; }
  1046. public string episodeTitle150 { get; set; }
  1047. public List<MetadataPrograms> metadata { get; set; }
  1048. public List<ContentRating> contentRating { get; set; }
  1049. public List<Cast> cast { get; set; }
  1050. public List<Crew> crew { get; set; }
  1051. public string entityType { get; set; }
  1052. public string showType { get; set; }
  1053. public bool hasImageArtwork { get; set; }
  1054. public string primaryImage { get; set; }
  1055. public string thumbImage { get; set; }
  1056. public string backdropImage { get; set; }
  1057. public string bannerImage { get; set; }
  1058. public string imageID { get; set; }
  1059. public string md5 { get; set; }
  1060. public List<string> contentAdvisory { get; set; }
  1061. public Movie movie { get; set; }
  1062. public List<Recommendation> recommendations { get; set; }
  1063. }
  1064. public class Caption
  1065. {
  1066. public string content { get; set; }
  1067. public string lang { get; set; }
  1068. }
  1069. public class ImageData
  1070. {
  1071. public string width { get; set; }
  1072. public string height { get; set; }
  1073. public string uri { get; set; }
  1074. public string size { get; set; }
  1075. public string aspect { get; set; }
  1076. public string category { get; set; }
  1077. public string text { get; set; }
  1078. public string primary { get; set; }
  1079. public string tier { get; set; }
  1080. public Caption caption { get; set; }
  1081. }
  1082. public class ShowImages
  1083. {
  1084. public string programID { get; set; }
  1085. public List<ImageData> data { get; set; }
  1086. }
  1087. }
  1088. }
  1089. }