SchedulesDirect.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Http.Json;
  11. using System.Net.Mime;
  12. using System.Security.Cryptography;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos;
  18. using Jellyfin.Extensions;
  19. using Jellyfin.Extensions.Json;
  20. using MediaBrowser.Common.Net;
  21. using MediaBrowser.Controller.Authentication;
  22. using MediaBrowser.Controller.LiveTv;
  23. using MediaBrowser.Model.Dto;
  24. using MediaBrowser.Model.Entities;
  25. using MediaBrowser.Model.LiveTv;
  26. using Microsoft.Extensions.Logging;
  27. namespace Emby.Server.Implementations.LiveTv.Listings
  28. {
  29. public class SchedulesDirect : IListingsProvider, IDisposable
  30. {
  31. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  32. private readonly ILogger<SchedulesDirect> _logger;
  33. private readonly IHttpClientFactory _httpClientFactory;
  34. private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
  35. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  36. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  37. private DateTime _lastErrorResponse;
  38. private bool _disposed = false;
  39. public SchedulesDirect(
  40. ILogger<SchedulesDirect> logger,
  41. IHttpClientFactory httpClientFactory)
  42. {
  43. _logger = logger;
  44. _httpClientFactory = httpClientFactory;
  45. }
  46. /// <inheritdoc />
  47. public string Name => "Schedules Direct";
  48. /// <inheritdoc />
  49. public string Type => nameof(SchedulesDirect);
  50. private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  51. {
  52. var dates = new List<string>();
  53. var start = new[] { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  54. var end = new[] { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  55. while (start <= end)
  56. {
  57. dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
  58. start = start.AddDays(1);
  59. }
  60. return dates;
  61. }
  62. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  63. {
  64. if (string.IsNullOrEmpty(channelId))
  65. {
  66. throw new ArgumentNullException(nameof(channelId));
  67. }
  68. // Normalize incoming input
  69. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  70. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  71. if (string.IsNullOrEmpty(token))
  72. {
  73. _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
  74. return Enumerable.Empty<ProgramInfo>();
  75. }
  76. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  77. _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
  78. var requestList = new List<RequestScheduleForChannelDto>()
  79. {
  80. new RequestScheduleForChannelDto()
  81. {
  82. StationId = channelId,
  83. Date = dates
  84. }
  85. };
  86. _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList);
  87. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
  88. options.Content = JsonContent.Create(requestList, options: _jsonOptions);
  89. options.Headers.TryAddWithoutValidation("token", token);
  90. using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  91. await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  92. var dailySchedules = await JsonSerializer.DeserializeAsync<IReadOnlyList<DayDto>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  93. if (dailySchedules is null)
  94. {
  95. return Array.Empty<ProgramInfo>();
  96. }
  97. _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
  98. using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs");
  99. programRequestOptions.Headers.TryAddWithoutValidation("token", token);
  100. var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();
  101. programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions);
  102. using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
  103. await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  104. var programDetails = await JsonSerializer.DeserializeAsync<IReadOnlyList<ProgramDetailsDto>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  105. if (programDetails is null)
  106. {
  107. return Array.Empty<ProgramInfo>();
  108. }
  109. var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y);
  110. var programIdsWithImages = programDetails
  111. .Where(p => p.HasImageArtwork).Select(p => p.ProgramId)
  112. .ToList();
  113. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  114. var programsInfo = new List<ProgramInfo>();
  115. foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs))
  116. {
  117. // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
  118. // " which corresponds to channel " + channelNumber + " and program id " +
  119. // schedule.ProgramId + " which says it has images? " +
  120. // programDict[schedule.ProgramId].hasImageArtwork);
  121. if (string.IsNullOrEmpty(schedule.ProgramId))
  122. {
  123. continue;
  124. }
  125. if (images is not null)
  126. {
  127. var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
  128. if (imageIndex > -1)
  129. {
  130. var programEntry = programDict[schedule.ProgramId];
  131. var allImages = images[imageIndex].Data;
  132. var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
  133. var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
  134. const double DesiredAspect = 2.0 / 3;
  135. programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ??
  136. GetProgramImage(ApiUrl, allImages, DesiredAspect, token);
  137. const double WideAspect = 16.0 / 9;
  138. programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token);
  139. // Don't supply the same image twice
  140. if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal))
  141. {
  142. programEntry.ThumbImage = null;
  143. }
  144. programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token);
  145. // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  146. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  147. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  148. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  149. }
  150. }
  151. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId]));
  152. }
  153. return programsInfo;
  154. }
  155. private static int GetSizeOrder(ImageDataDto image)
  156. {
  157. if (int.TryParse(image.Height, out int value))
  158. {
  159. return value;
  160. }
  161. return 0;
  162. }
  163. private static string GetChannelNumber(MapDto map)
  164. {
  165. var channelNumber = map.LogicalChannelNumber;
  166. if (string.IsNullOrWhiteSpace(channelNumber))
  167. {
  168. channelNumber = map.Channel;
  169. }
  170. if (string.IsNullOrWhiteSpace(channelNumber))
  171. {
  172. channelNumber = map.AtscMajor + "." + map.AtscMinor;
  173. }
  174. return channelNumber.TrimStart('0');
  175. }
  176. private static bool IsMovie(ProgramDetailsDto programInfo)
  177. {
  178. return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase);
  179. }
  180. private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details)
  181. {
  182. if (programInfo.AirDateTime is null)
  183. {
  184. return null;
  185. }
  186. var startAt = programInfo.AirDateTime.Value;
  187. var endAt = startAt.AddSeconds(programInfo.Duration);
  188. var audioType = ProgramAudio.Stereo;
  189. var programId = programInfo.ProgramId ?? string.Empty;
  190. string newID = programId + "T" + startAt.Ticks + "C" + channelId;
  191. if (programInfo.AudioProperties.Count != 0)
  192. {
  193. if (programInfo.AudioProperties.Contains("atmos", StringComparison.OrdinalIgnoreCase))
  194. {
  195. audioType = ProgramAudio.Atmos;
  196. }
  197. else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparison.OrdinalIgnoreCase))
  198. {
  199. audioType = ProgramAudio.DolbyDigital;
  200. }
  201. else if (programInfo.AudioProperties.Contains("dd", StringComparison.OrdinalIgnoreCase))
  202. {
  203. audioType = ProgramAudio.DolbyDigital;
  204. }
  205. else if (programInfo.AudioProperties.Contains("stereo", StringComparison.OrdinalIgnoreCase))
  206. {
  207. audioType = ProgramAudio.Stereo;
  208. }
  209. else
  210. {
  211. audioType = ProgramAudio.Mono;
  212. }
  213. }
  214. string episodeTitle = null;
  215. if (details.EpisodeTitle150 is not null)
  216. {
  217. episodeTitle = details.EpisodeTitle150;
  218. }
  219. var info = new ProgramInfo
  220. {
  221. ChannelId = channelId,
  222. Id = newID,
  223. StartDate = startAt,
  224. EndDate = endAt,
  225. Name = details.Titles[0].Title120 ?? "Unknown",
  226. OfficialRating = null,
  227. CommunityRating = null,
  228. EpisodeTitle = episodeTitle,
  229. Audio = audioType,
  230. // IsNew = programInfo.@new ?? false,
  231. IsRepeat = programInfo.New is null,
  232. IsSeries = string.Equals(details.EntityType, "episode", StringComparison.OrdinalIgnoreCase),
  233. ImageUrl = details.PrimaryImage,
  234. ThumbImageUrl = details.ThumbImage,
  235. IsKids = string.Equals(details.Audience, "children", StringComparison.OrdinalIgnoreCase),
  236. IsSports = string.Equals(details.EntityType, "sports", StringComparison.OrdinalIgnoreCase),
  237. IsMovie = IsMovie(details),
  238. Etag = programInfo.Md5,
  239. IsLive = string.Equals(programInfo.LiveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
  240. IsPremiere = programInfo.Premiere || (programInfo.IsPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
  241. };
  242. var showId = programId;
  243. if (!info.IsSeries)
  244. {
  245. // It's also a series if it starts with SH
  246. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  247. }
  248. // According to SchedulesDirect, these are generic, unidentified episodes
  249. // SH005316560000
  250. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  251. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  252. if (!hasUniqueShowId)
  253. {
  254. showId = newID;
  255. }
  256. info.ShowId = showId;
  257. if (programInfo.VideoProperties is not null)
  258. {
  259. info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase);
  260. info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase);
  261. }
  262. if (details.ContentRating is not null && details.ContentRating.Count > 0)
  263. {
  264. info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal)
  265. .Replace("--", "-", StringComparison.Ordinal);
  266. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  267. if (invalid.Contains(info.OfficialRating, StringComparison.OrdinalIgnoreCase))
  268. {
  269. info.OfficialRating = null;
  270. }
  271. }
  272. if (details.Descriptions is not null)
  273. {
  274. if (details.Descriptions.Description1000 is not null && details.Descriptions.Description1000.Count > 0)
  275. {
  276. info.Overview = details.Descriptions.Description1000[0].Description;
  277. }
  278. else if (details.Descriptions.Description100 is not null && details.Descriptions.Description100.Count > 0)
  279. {
  280. info.Overview = details.Descriptions.Description100[0].Description;
  281. }
  282. }
  283. if (info.IsSeries)
  284. {
  285. info.SeriesId = programId.Substring(0, 10);
  286. info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
  287. if (details.Metadata is not null)
  288. {
  289. foreach (var metadataProgram in details.Metadata)
  290. {
  291. var gracenote = metadataProgram.Gracenote;
  292. if (gracenote is not null)
  293. {
  294. info.SeasonNumber = gracenote.Season;
  295. if (gracenote.Episode > 0)
  296. {
  297. info.EpisodeNumber = gracenote.Episode;
  298. }
  299. break;
  300. }
  301. }
  302. }
  303. }
  304. if (details.OriginalAirDate is not null)
  305. {
  306. info.OriginalAirDate = details.OriginalAirDate;
  307. info.ProductionYear = info.OriginalAirDate.Value.Year;
  308. }
  309. if (details.Movie is not null)
  310. {
  311. if (!string.IsNullOrEmpty(details.Movie.Year)
  312. && int.TryParse(details.Movie.Year, out int year))
  313. {
  314. info.ProductionYear = year;
  315. }
  316. }
  317. if (details.Genres is not null)
  318. {
  319. info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  320. info.IsNews = details.Genres.Contains("news", StringComparison.OrdinalIgnoreCase);
  321. if (info.Genres.Contains("children", StringComparison.OrdinalIgnoreCase))
  322. {
  323. info.IsKids = true;
  324. }
  325. }
  326. return info;
  327. }
  328. private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, string token)
  329. {
  330. var match = images
  331. .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
  332. .ThenByDescending(i => GetSizeOrder(i))
  333. .FirstOrDefault();
  334. if (match is null)
  335. {
  336. return null;
  337. }
  338. var uri = match.Uri;
  339. if (string.IsNullOrWhiteSpace(uri))
  340. {
  341. return null;
  342. }
  343. else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  344. {
  345. return uri;
  346. }
  347. else
  348. {
  349. return apiUrl + "/image/" + uri + "?token=" + token;
  350. }
  351. }
  352. private static double GetAspectRatio(ImageDataDto i)
  353. {
  354. int width = 0;
  355. int height = 0;
  356. if (!string.IsNullOrWhiteSpace(i.Width))
  357. {
  358. _ = int.TryParse(i.Width, out width);
  359. }
  360. if (!string.IsNullOrWhiteSpace(i.Height))
  361. {
  362. _ = int.TryParse(i.Height, out height);
  363. }
  364. if (height == 0 || width == 0)
  365. {
  366. return 0;
  367. }
  368. double result = width;
  369. result /= height;
  370. return result;
  371. }
  372. private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
  373. ListingsProviderInfo info,
  374. IReadOnlyList<string> programIds,
  375. CancellationToken cancellationToken)
  376. {
  377. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  378. if (programIds.Count == 0)
  379. {
  380. return Array.Empty<ShowImagesDto>();
  381. }
  382. StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
  383. foreach (ReadOnlySpan<char> i in programIds)
  384. {
  385. str.Append('"')
  386. .Append(i.Slice(0, 10))
  387. .Append("\",");
  388. }
  389. // Remove last ,
  390. str.Length--;
  391. str.Append(']');
  392. using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
  393. {
  394. Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
  395. };
  396. message.Headers.TryAddWithoutValidation("token", token);
  397. try
  398. {
  399. using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
  400. await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  401. return await JsonSerializer.DeserializeAsync<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  402. }
  403. catch (Exception ex)
  404. {
  405. _logger.LogError(ex, "Error getting image info from schedules direct");
  406. return Array.Empty<ShowImagesDto>();
  407. }
  408. }
  409. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  410. {
  411. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  412. var lineups = new List<NameIdPair>();
  413. if (string.IsNullOrWhiteSpace(token))
  414. {
  415. return lineups;
  416. }
  417. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
  418. options.Headers.TryAddWithoutValidation("token", token);
  419. try
  420. {
  421. using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
  422. await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  423. var root = await JsonSerializer.DeserializeAsync<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  424. if (root is not null)
  425. {
  426. foreach (HeadendsDto headend in root)
  427. {
  428. foreach (LineupDto lineup in headend.Lineups)
  429. {
  430. lineups.Add(new NameIdPair
  431. {
  432. Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name,
  433. Id = lineup.Uri?[18..]
  434. });
  435. }
  436. }
  437. }
  438. else
  439. {
  440. _logger.LogInformation("No lineups available");
  441. }
  442. }
  443. catch (Exception ex)
  444. {
  445. _logger.LogError(ex, "Error getting headends");
  446. }
  447. return lineups;
  448. }
  449. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  450. {
  451. var username = info.Username;
  452. // Reset the token if there's no username
  453. if (string.IsNullOrWhiteSpace(username))
  454. {
  455. return null;
  456. }
  457. var password = info.Password;
  458. if (string.IsNullOrEmpty(password))
  459. {
  460. return null;
  461. }
  462. // Avoid hammering SD
  463. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  464. {
  465. return null;
  466. }
  467. if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
  468. {
  469. savedToken = new NameValuePair();
  470. _tokens.TryAdd(username, savedToken);
  471. }
  472. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  473. {
  474. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
  475. {
  476. // If it's under 24 hours old we can still use it
  477. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  478. {
  479. return savedToken.Name;
  480. }
  481. }
  482. }
  483. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  484. try
  485. {
  486. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  487. savedToken.Name = result;
  488. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  489. return result;
  490. }
  491. catch (HttpRequestException ex)
  492. {
  493. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  494. {
  495. _tokens.Clear();
  496. _lastErrorResponse = DateTime.UtcNow;
  497. }
  498. throw;
  499. }
  500. finally
  501. {
  502. _tokenSemaphore.Release();
  503. }
  504. }
  505. private async Task<HttpResponseMessage> Send(
  506. HttpRequestMessage options,
  507. bool enableRetry,
  508. ListingsProviderInfo providerInfo,
  509. CancellationToken cancellationToken,
  510. HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
  511. {
  512. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  513. .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
  514. if (response.IsSuccessStatusCode)
  515. {
  516. return response;
  517. }
  518. // Response is automatically disposed in the calling function,
  519. // so dispose manually if not returning.
  520. response.Dispose();
  521. if (!enableRetry || (int)response.StatusCode >= 500)
  522. {
  523. throw new HttpRequestException(
  524. string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
  525. null,
  526. response.StatusCode);
  527. }
  528. _tokens.Clear();
  529. options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
  530. return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
  531. }
  532. private async Task<string> GetTokenInternal(
  533. string username,
  534. string password,
  535. CancellationToken cancellationToken)
  536. {
  537. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
  538. #pragma warning disable CA5350 // SchedulesDirect is always SHA1.
  539. var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password));
  540. #pragma warning restore CA5350
  541. // TODO: remove ToLower when Convert.ToHexString supports lowercase
  542. // Schedules Direct requires the hex to be lowercase
  543. string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
  544. options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
  545. using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  546. response.EnsureSuccessStatusCode();
  547. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  548. var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  549. if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
  550. {
  551. _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
  552. return root.Token;
  553. }
  554. throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message);
  555. }
  556. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  557. {
  558. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  559. if (string.IsNullOrEmpty(token))
  560. {
  561. throw new ArgumentException("Authentication required.");
  562. }
  563. if (string.IsNullOrEmpty(info.ListingsId))
  564. {
  565. throw new ArgumentException("Listings Id required");
  566. }
  567. _logger.LogInformation("Adding new LineUp ");
  568. using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
  569. options.Headers.TryAddWithoutValidation("token", token);
  570. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  571. }
  572. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  573. {
  574. if (string.IsNullOrEmpty(info.ListingsId))
  575. {
  576. throw new ArgumentException("Listings Id required");
  577. }
  578. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  579. if (string.IsNullOrEmpty(token))
  580. {
  581. throw new ArgumentException("token required");
  582. }
  583. _logger.LogInformation("Headends on account ");
  584. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
  585. options.Headers.TryAddWithoutValidation("token", token);
  586. try
  587. {
  588. using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  589. httpResponse.EnsureSuccessStatusCode();
  590. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  591. using var response = httpResponse.Content;
  592. var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  593. return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
  594. }
  595. catch (HttpRequestException ex)
  596. {
  597. // SchedulesDirect returns 400 if no lineups are configured.
  598. if (ex.StatusCode is HttpStatusCode.BadRequest)
  599. {
  600. return false;
  601. }
  602. throw;
  603. }
  604. }
  605. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  606. {
  607. if (validateLogin)
  608. {
  609. if (string.IsNullOrEmpty(info.Username))
  610. {
  611. throw new ArgumentException("Username is required");
  612. }
  613. if (string.IsNullOrEmpty(info.Password))
  614. {
  615. throw new ArgumentException("Password is required");
  616. }
  617. }
  618. if (validateListings)
  619. {
  620. if (string.IsNullOrEmpty(info.ListingsId))
  621. {
  622. throw new ArgumentException("Listings Id required");
  623. }
  624. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  625. if (!hasLineup)
  626. {
  627. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  628. }
  629. }
  630. }
  631. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  632. {
  633. return GetHeadends(info, country, location, CancellationToken.None);
  634. }
  635. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  636. {
  637. var listingsId = info.ListingsId;
  638. if (string.IsNullOrEmpty(listingsId))
  639. {
  640. throw new ArgumentException("ListingsId required");
  641. }
  642. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  643. if (string.IsNullOrEmpty(token))
  644. {
  645. throw new ArgumentException("token required");
  646. }
  647. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  648. options.Headers.TryAddWithoutValidation("token", token);
  649. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  650. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  651. var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  652. if (root is null)
  653. {
  654. return new List<ChannelInfo>();
  655. }
  656. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count);
  657. _logger.LogInformation("Mapping Stations to Channel");
  658. var allStations = root.Stations;
  659. var map = root.Map;
  660. var list = new List<ChannelInfo>(map.Count);
  661. foreach (var channel in map)
  662. {
  663. var channelNumber = GetChannelNumber(channel);
  664. var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase));
  665. var station = stationIndex == -1
  666. ? new StationDto { StationId = channel.StationId }
  667. : allStations[stationIndex];
  668. var channelInfo = new ChannelInfo
  669. {
  670. Id = station.StationId,
  671. CallSign = station.Callsign,
  672. Number = channelNumber,
  673. Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name
  674. };
  675. if (station.Logo is not null)
  676. {
  677. channelInfo.ImageUrl = station.Logo.Url;
  678. }
  679. list.Add(channelInfo);
  680. }
  681. return list;
  682. }
  683. /// <inheritdoc />
  684. public void Dispose()
  685. {
  686. Dispose(true);
  687. GC.SuppressFinalize(this);
  688. }
  689. /// <summary>
  690. /// Releases unmanaged and optionally managed resources.
  691. /// </summary>
  692. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  693. protected virtual void Dispose(bool disposing)
  694. {
  695. if (_disposed)
  696. {
  697. return;
  698. }
  699. if (disposing)
  700. {
  701. _tokenSemaphore?.Dispose();
  702. }
  703. _disposed = true;
  704. }
  705. }
  706. }