SchedulesDirect.cs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Controller.LiveTv;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.LiveTv;
  18. using MediaBrowser.Model.Net;
  19. using MediaBrowser.Model.Serialization;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.LiveTv.Listings
  22. {
  23. public class SchedulesDirect : IListingsProvider
  24. {
  25. private readonly ILogger<SchedulesDirect> _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(
  32. ILogger<SchedulesDirect> logger,
  33. IJsonSerializer jsonSerializer,
  34. IHttpClient httpClient,
  35. IApplicationHost appHost)
  36. {
  37. _logger = logger;
  38. _jsonSerializer = jsonSerializer;
  39. _httpClient = httpClient;
  40. _appHost = appHost;
  41. }
  42. private string UserAgent => _appHost.ApplicationUserAgent;
  43. /// <inheritdoc />
  44. public string Name => "Schedules Direct";
  45. /// <inheritdoc />
  46. public string Type => nameof(SchedulesDirect);
  47. private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  48. {
  49. var dates = new List<string>();
  50. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  51. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  52. while (start <= end)
  53. {
  54. dates.Add(start.ToString("yyyy-MM-dd"));
  55. start = start.AddDays(1);
  56. }
  57. return dates;
  58. }
  59. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  60. {
  61. if (string.IsNullOrEmpty(channelId))
  62. {
  63. throw new ArgumentNullException(nameof(channelId));
  64. }
  65. // Normalize incoming input
  66. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  67. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  68. if (string.IsNullOrEmpty(token))
  69. {
  70. _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
  71. return Enumerable.Empty<ProgramInfo>();
  72. }
  73. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  74. _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
  75. var requestList = new List<ScheduleDirect.RequestScheduleForChannel>()
  76. {
  77. new ScheduleDirect.RequestScheduleForChannel()
  78. {
  79. stationID = channelId,
  80. date = dates
  81. }
  82. };
  83. var requestString = _jsonSerializer.SerializeToString(requestList);
  84. _logger.LogDebug("Request string for schedules is: {RequestString}", requestString);
  85. var httpOptions = new HttpRequestOptions()
  86. {
  87. Url = ApiUrl + "/schedules",
  88. UserAgent = UserAgent,
  89. CancellationToken = cancellationToken,
  90. LogErrorResponseBody = true,
  91. RequestContent = requestString
  92. };
  93. httpOptions.RequestHeaders["token"] = token;
  94. using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
  95. {
  96. var dailySchedules = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(response.Content).ConfigureAwait(false);
  97. _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
  98. httpOptions = new HttpRequestOptions()
  99. {
  100. Url = ApiUrl + "/programs",
  101. UserAgent = UserAgent,
  102. CancellationToken = cancellationToken,
  103. LogErrorResponseBody = true
  104. };
  105. httpOptions.RequestHeaders["token"] = token;
  106. var programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct();
  107. httpOptions.RequestContent = "[\"" + string.Join("\", \"", programsID) + "\"]";
  108. using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
  109. {
  110. var programDetails = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponse.Content).ConfigureAwait(false);
  111. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  112. var programIdsWithImages =
  113. programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID)
  114. .ToList();
  115. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  116. var programsInfo = new List<ProgramInfo>();
  117. foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs))
  118. {
  119. // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
  120. // " which corresponds to channel " + channelNumber + " and program id " +
  121. // schedule.programID + " which says it has images? " +
  122. // programDict[schedule.programID].hasImageArtwork);
  123. if (images != null)
  124. {
  125. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  126. if (imageIndex > -1)
  127. {
  128. var programEntry = programDict[schedule.programID];
  129. var allImages = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>();
  130. var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase));
  131. var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase));
  132. const double DesiredAspect = 2.0 / 3;
  133. programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, DesiredAspect) ??
  134. GetProgramImage(ApiUrl, allImages, true, DesiredAspect);
  135. const double WideAspect = 16.0 / 9;
  136. programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, WideAspect);
  137. // Don't supply the same image twice
  138. if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
  139. {
  140. programEntry.thumbImage = null;
  141. }
  142. programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, WideAspect);
  143. // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  144. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  145. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  146. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  147. }
  148. }
  149. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
  150. }
  151. return programsInfo;
  152. }
  153. }
  154. }
  155. private static int GetSizeOrder(ScheduleDirect.ImageData image)
  156. {
  157. if (!string.IsNullOrWhiteSpace(image.height)
  158. && int.TryParse(image.height, out int value))
  159. {
  160. return value;
  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[MetadataProvider.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. };
  403. try
  404. {
  405. using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
  406. {
  407. return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(
  408. innerResponse2.Content).ConfigureAwait(false);
  409. }
  410. }
  411. catch (Exception ex)
  412. {
  413. _logger.LogError(ex, "Error getting image info from schedules direct");
  414. return new List<ScheduleDirect.ShowImages>();
  415. }
  416. }
  417. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  418. {
  419. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  420. var lineups = new List<NameIdPair>();
  421. if (string.IsNullOrWhiteSpace(token))
  422. {
  423. return lineups;
  424. }
  425. var options = new HttpRequestOptions()
  426. {
  427. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  428. UserAgent = UserAgent,
  429. CancellationToken = cancellationToken,
  430. LogErrorResponseBody = true
  431. };
  432. options.RequestHeaders["token"] = token;
  433. try
  434. {
  435. using (var httpResponse = await Get(options, false, info).ConfigureAwait(false))
  436. using (Stream responce = httpResponse.Content)
  437. {
  438. var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(responce).ConfigureAwait(false);
  439. if (root != null)
  440. {
  441. foreach (ScheduleDirect.Headends headend in root)
  442. {
  443. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  444. {
  445. lineups.Add(new NameIdPair
  446. {
  447. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  448. Id = lineup.uri.Substring(18)
  449. });
  450. }
  451. }
  452. }
  453. else
  454. {
  455. _logger.LogInformation("No lineups available");
  456. }
  457. }
  458. }
  459. catch (Exception ex)
  460. {
  461. _logger.LogError(ex, "Error getting headends");
  462. }
  463. return lineups;
  464. }
  465. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  466. private DateTime _lastErrorResponse;
  467. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  468. {
  469. var username = info.Username;
  470. // Reset the token if there's no username
  471. if (string.IsNullOrWhiteSpace(username))
  472. {
  473. return null;
  474. }
  475. var password = info.Password;
  476. if (string.IsNullOrEmpty(password))
  477. {
  478. return null;
  479. }
  480. // Avoid hammering SD
  481. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  482. {
  483. return null;
  484. }
  485. NameValuePair savedToken = null;
  486. if (!_tokens.TryGetValue(username, out savedToken))
  487. {
  488. savedToken = new NameValuePair();
  489. _tokens.TryAdd(username, savedToken);
  490. }
  491. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  492. {
  493. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
  494. {
  495. // If it's under 24 hours old we can still use it
  496. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  497. {
  498. return savedToken.Name;
  499. }
  500. }
  501. }
  502. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  503. try
  504. {
  505. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  506. savedToken.Name = result;
  507. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  508. return result;
  509. }
  510. catch (HttpException ex)
  511. {
  512. if (ex.StatusCode.HasValue)
  513. {
  514. if ((int)ex.StatusCode.Value == 400)
  515. {
  516. _tokens.Clear();
  517. _lastErrorResponse = DateTime.UtcNow;
  518. }
  519. }
  520. throw;
  521. }
  522. finally
  523. {
  524. _tokenSemaphore.Release();
  525. }
  526. }
  527. private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
  528. bool enableRetry,
  529. ListingsProviderInfo providerInfo)
  530. {
  531. // Schedules direct requires that the client support compression and will return a 400 response without it
  532. options.DecompressionMethod = CompressionMethods.Deflate;
  533. try
  534. {
  535. return await _httpClient.Post(options).ConfigureAwait(false);
  536. }
  537. catch (HttpException ex)
  538. {
  539. _tokens.Clear();
  540. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  541. {
  542. enableRetry = false;
  543. }
  544. if (!enableRetry)
  545. {
  546. throw;
  547. }
  548. }
  549. options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  550. return await Post(options, false, providerInfo).ConfigureAwait(false);
  551. }
  552. private async Task<HttpResponseInfo> Get(HttpRequestOptions options,
  553. bool enableRetry,
  554. ListingsProviderInfo providerInfo)
  555. {
  556. // Schedules direct requires that the client support compression and will return a 400 response without it
  557. options.DecompressionMethod = CompressionMethods.Deflate;
  558. try
  559. {
  560. return await _httpClient.SendAsync(options, HttpMethod.Get).ConfigureAwait(false);
  561. }
  562. catch (HttpException ex)
  563. {
  564. _tokens.Clear();
  565. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  566. {
  567. enableRetry = false;
  568. }
  569. if (!enableRetry)
  570. {
  571. throw;
  572. }
  573. }
  574. options.RequestHeaders["token"] = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  575. return await Get(options, false, providerInfo).ConfigureAwait(false);
  576. }
  577. private async Task<string> GetTokenInternal(string username, string password,
  578. CancellationToken cancellationToken)
  579. {
  580. var httpOptions = new HttpRequestOptions()
  581. {
  582. Url = ApiUrl + "/token",
  583. UserAgent = UserAgent,
  584. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  585. CancellationToken = cancellationToken,
  586. LogErrorResponseBody = true
  587. };
  588. // _logger.LogInformation("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  589. // httpOptions.RequestContent);
  590. using (var response = await Post(httpOptions, false, null).ConfigureAwait(false))
  591. {
  592. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(response.Content).ConfigureAwait(false);
  593. if (root.message == "OK")
  594. {
  595. _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
  596. return root.token;
  597. }
  598. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  599. }
  600. }
  601. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  602. {
  603. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  604. if (string.IsNullOrEmpty(token))
  605. {
  606. throw new ArgumentException("Authentication required.");
  607. }
  608. if (string.IsNullOrEmpty(info.ListingsId))
  609. {
  610. throw new ArgumentException("Listings Id required");
  611. }
  612. _logger.LogInformation("Adding new LineUp ");
  613. var httpOptions = new HttpRequestOptions()
  614. {
  615. Url = ApiUrl + "/lineups/" + info.ListingsId,
  616. UserAgent = UserAgent,
  617. CancellationToken = cancellationToken,
  618. LogErrorResponseBody = true,
  619. BufferContent = false
  620. };
  621. httpOptions.RequestHeaders["token"] = token;
  622. using (await _httpClient.SendAsync(httpOptions, HttpMethod.Put).ConfigureAwait(false))
  623. {
  624. }
  625. }
  626. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  627. {
  628. if (string.IsNullOrEmpty(info.ListingsId))
  629. {
  630. throw new ArgumentException("Listings Id required");
  631. }
  632. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  633. if (string.IsNullOrEmpty(token))
  634. {
  635. throw new Exception("token required");
  636. }
  637. _logger.LogInformation("Headends on account ");
  638. var options = new HttpRequestOptions()
  639. {
  640. Url = ApiUrl + "/lineups",
  641. UserAgent = UserAgent,
  642. CancellationToken = cancellationToken,
  643. LogErrorResponseBody = true
  644. };
  645. options.RequestHeaders["token"] = token;
  646. try
  647. {
  648. using (var httpResponse = await Get(options, false, null).ConfigureAwait(false))
  649. using (var response = httpResponse.Content)
  650. {
  651. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(response).ConfigureAwait(false);
  652. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  653. }
  654. }
  655. catch (HttpException ex)
  656. {
  657. // Apparently we're supposed to swallow this
  658. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  659. {
  660. return false;
  661. }
  662. throw;
  663. }
  664. }
  665. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  666. {
  667. if (validateLogin)
  668. {
  669. if (string.IsNullOrEmpty(info.Username))
  670. {
  671. throw new ArgumentException("Username is required");
  672. }
  673. if (string.IsNullOrEmpty(info.Password))
  674. {
  675. throw new ArgumentException("Password is required");
  676. }
  677. }
  678. if (validateListings)
  679. {
  680. if (string.IsNullOrEmpty(info.ListingsId))
  681. {
  682. throw new ArgumentException("Listings Id required");
  683. }
  684. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  685. if (!hasLineup)
  686. {
  687. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  688. }
  689. }
  690. }
  691. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  692. {
  693. return GetHeadends(info, country, location, CancellationToken.None);
  694. }
  695. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  696. {
  697. var listingsId = info.ListingsId;
  698. if (string.IsNullOrEmpty(listingsId))
  699. {
  700. throw new Exception("ListingsId required");
  701. }
  702. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  703. if (string.IsNullOrEmpty(token))
  704. {
  705. throw new Exception("token required");
  706. }
  707. var httpOptions = new HttpRequestOptions()
  708. {
  709. Url = ApiUrl + "/lineups/" + listingsId,
  710. UserAgent = UserAgent,
  711. CancellationToken = cancellationToken,
  712. LogErrorResponseBody = true,
  713. };
  714. httpOptions.RequestHeaders["token"] = token;
  715. var list = new List<ChannelInfo>();
  716. using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false))
  717. using (var response = httpResponse.Content)
  718. {
  719. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(response).ConfigureAwait(false);
  720. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
  721. _logger.LogInformation("Mapping Stations to Channel");
  722. var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>();
  723. foreach (ScheduleDirect.Map map in root.map)
  724. {
  725. var channelNumber = GetChannelNumber(map);
  726. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  727. if (station == null)
  728. {
  729. station = new ScheduleDirect.Station
  730. {
  731. stationID = map.stationID
  732. };
  733. }
  734. var channelInfo = new ChannelInfo
  735. {
  736. Id = station.stationID,
  737. CallSign = station.callsign,
  738. Number = channelNumber,
  739. Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
  740. };
  741. if (station.logo != null)
  742. {
  743. channelInfo.ImageUrl = station.logo.URL;
  744. }
  745. list.Add(channelInfo);
  746. }
  747. }
  748. return list;
  749. }
  750. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  751. {
  752. if (!string.IsNullOrWhiteSpace(channelName))
  753. {
  754. channelName = NormalizeName(channelName);
  755. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  756. if (result != null)
  757. {
  758. return result;
  759. }
  760. }
  761. if (!string.IsNullOrWhiteSpace(channelNumber))
  762. {
  763. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  764. }
  765. return null;
  766. }
  767. private static string NormalizeName(string value)
  768. {
  769. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  770. }
  771. public class ScheduleDirect
  772. {
  773. public class Token
  774. {
  775. public int code { get; set; }
  776. public string message { get; set; }
  777. public string serverID { get; set; }
  778. public string token { get; set; }
  779. }
  780. public class Lineup
  781. {
  782. public string lineup { get; set; }
  783. public string name { get; set; }
  784. public string transport { get; set; }
  785. public string location { get; set; }
  786. public string uri { get; set; }
  787. }
  788. public class Lineups
  789. {
  790. public int code { get; set; }
  791. public string serverID { get; set; }
  792. public string datetime { get; set; }
  793. public List<Lineup> lineups { get; set; }
  794. }
  795. public class Headends
  796. {
  797. public string headend { get; set; }
  798. public string transport { get; set; }
  799. public string location { get; set; }
  800. public List<Lineup> lineups { get; set; }
  801. }
  802. public class Map
  803. {
  804. public string stationID { get; set; }
  805. public string channel { get; set; }
  806. public string logicalChannelNumber { get; set; }
  807. public int uhfVhf { get; set; }
  808. public int atscMajor { get; set; }
  809. public int atscMinor { get; set; }
  810. }
  811. public class Broadcaster
  812. {
  813. public string city { get; set; }
  814. public string state { get; set; }
  815. public string postalcode { get; set; }
  816. public string country { get; set; }
  817. }
  818. public class Logo
  819. {
  820. public string URL { get; set; }
  821. public int height { get; set; }
  822. public int width { get; set; }
  823. public string md5 { get; set; }
  824. }
  825. public class Station
  826. {
  827. public string stationID { get; set; }
  828. public string name { get; set; }
  829. public string callsign { get; set; }
  830. public List<string> broadcastLanguage { get; set; }
  831. public List<string> descriptionLanguage { get; set; }
  832. public Broadcaster broadcaster { get; set; }
  833. public string affiliate { get; set; }
  834. public Logo logo { get; set; }
  835. public bool? isCommercialFree { get; set; }
  836. }
  837. public class Metadata
  838. {
  839. public string lineup { get; set; }
  840. public string modified { get; set; }
  841. public string transport { get; set; }
  842. }
  843. public class Channel
  844. {
  845. public List<Map> map { get; set; }
  846. public List<Station> stations { get; set; }
  847. public Metadata metadata { get; set; }
  848. }
  849. public class RequestScheduleForChannel
  850. {
  851. public string stationID { get; set; }
  852. public List<string> date { get; set; }
  853. }
  854. public class Rating
  855. {
  856. public string body { get; set; }
  857. public string code { get; set; }
  858. }
  859. public class Multipart
  860. {
  861. public int partNumber { get; set; }
  862. public int totalParts { get; set; }
  863. }
  864. public class Program
  865. {
  866. public string programID { get; set; }
  867. public string airDateTime { get; set; }
  868. public int duration { get; set; }
  869. public string md5 { get; set; }
  870. public List<string> audioProperties { get; set; }
  871. public List<string> videoProperties { get; set; }
  872. public List<Rating> ratings { get; set; }
  873. public bool? @new { get; set; }
  874. public Multipart multipart { get; set; }
  875. public string liveTapeDelay { get; set; }
  876. public bool premiere { get; set; }
  877. public bool repeat { get; set; }
  878. public string isPremiereOrFinale { get; set; }
  879. }
  880. public class MetadataSchedule
  881. {
  882. public string modified { get; set; }
  883. public string md5 { get; set; }
  884. public string startDate { get; set; }
  885. public string endDate { get; set; }
  886. public int days { get; set; }
  887. }
  888. public class Day
  889. {
  890. public string stationID { get; set; }
  891. public List<Program> programs { get; set; }
  892. public MetadataSchedule metadata { get; set; }
  893. public Day()
  894. {
  895. programs = new List<Program>();
  896. }
  897. }
  898. //
  899. public class Title
  900. {
  901. public string title120 { get; set; }
  902. }
  903. public class EventDetails
  904. {
  905. public string subType { get; set; }
  906. }
  907. public class Description100
  908. {
  909. public string descriptionLanguage { get; set; }
  910. public string description { get; set; }
  911. }
  912. public class Description1000
  913. {
  914. public string descriptionLanguage { get; set; }
  915. public string description { get; set; }
  916. }
  917. public class DescriptionsProgram
  918. {
  919. public List<Description100> description100 { get; set; }
  920. public List<Description1000> description1000 { get; set; }
  921. }
  922. public class Gracenote
  923. {
  924. public int season { get; set; }
  925. public int episode { get; set; }
  926. }
  927. public class MetadataPrograms
  928. {
  929. public Gracenote Gracenote { get; set; }
  930. }
  931. public class ContentRating
  932. {
  933. public string body { get; set; }
  934. public string code { get; set; }
  935. }
  936. public class Cast
  937. {
  938. public string billingOrder { get; set; }
  939. public string role { get; set; }
  940. public string nameId { get; set; }
  941. public string personId { get; set; }
  942. public string name { get; set; }
  943. public string characterName { get; set; }
  944. }
  945. public class Crew
  946. {
  947. public string billingOrder { get; set; }
  948. public string role { get; set; }
  949. public string nameId { get; set; }
  950. public string personId { get; set; }
  951. public string name { get; set; }
  952. }
  953. public class QualityRating
  954. {
  955. public string ratingsBody { get; set; }
  956. public string rating { get; set; }
  957. public string minRating { get; set; }
  958. public string maxRating { get; set; }
  959. public string increment { get; set; }
  960. }
  961. public class Movie
  962. {
  963. public string year { get; set; }
  964. public int duration { get; set; }
  965. public List<QualityRating> qualityRating { get; set; }
  966. }
  967. public class Recommendation
  968. {
  969. public string programID { get; set; }
  970. public string title120 { get; set; }
  971. }
  972. public class ProgramDetails
  973. {
  974. public string audience { get; set; }
  975. public string programID { get; set; }
  976. public List<Title> titles { get; set; }
  977. public EventDetails eventDetails { get; set; }
  978. public DescriptionsProgram descriptions { get; set; }
  979. public string originalAirDate { get; set; }
  980. public List<string> genres { get; set; }
  981. public string episodeTitle150 { get; set; }
  982. public List<MetadataPrograms> metadata { get; set; }
  983. public List<ContentRating> contentRating { get; set; }
  984. public List<Cast> cast { get; set; }
  985. public List<Crew> crew { get; set; }
  986. public string entityType { get; set; }
  987. public string showType { get; set; }
  988. public bool hasImageArtwork { get; set; }
  989. public string primaryImage { get; set; }
  990. public string thumbImage { get; set; }
  991. public string backdropImage { get; set; }
  992. public string bannerImage { get; set; }
  993. public string imageID { get; set; }
  994. public string md5 { get; set; }
  995. public List<string> contentAdvisory { get; set; }
  996. public Movie movie { get; set; }
  997. public List<Recommendation> recommendations { get; set; }
  998. }
  999. public class Caption
  1000. {
  1001. public string content { get; set; }
  1002. public string lang { get; set; }
  1003. }
  1004. public class ImageData
  1005. {
  1006. public string width { get; set; }
  1007. public string height { get; set; }
  1008. public string uri { get; set; }
  1009. public string size { get; set; }
  1010. public string aspect { get; set; }
  1011. public string category { get; set; }
  1012. public string text { get; set; }
  1013. public string primary { get; set; }
  1014. public string tier { get; set; }
  1015. public Caption caption { get; set; }
  1016. }
  1017. public class ShowImages
  1018. {
  1019. public string programID { get; set; }
  1020. public List<ImageData> data { get; set; }
  1021. }
  1022. }
  1023. }
  1024. }