SchedulesDirect.cs 43 KB

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