SchedulesDirect.cs 46 KB

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