SchedulesDirect.cs 45 KB

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