SchedulesDirect.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. ArgumentException.ThrowIfNullOrEmpty(channelId);
  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<RequestScheduleForChannelDto>()
  76. {
  77. new RequestScheduleForChannelDto()
  78. {
  79. StationId = channelId,
  80. Date = dates
  81. }
  82. };
  83. _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList);
  84. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
  85. options.Content = JsonContent.Create(requestList, options: _jsonOptions);
  86. options.Headers.TryAddWithoutValidation("token", token);
  87. using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  88. await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  89. var dailySchedules = await JsonSerializer.DeserializeAsync<IReadOnlyList<DayDto>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  90. if (dailySchedules is null)
  91. {
  92. return Array.Empty<ProgramInfo>();
  93. }
  94. _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
  95. using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs");
  96. programRequestOptions.Headers.TryAddWithoutValidation("token", token);
  97. var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();
  98. programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions);
  99. using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
  100. await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  101. var programDetails = await JsonSerializer.DeserializeAsync<IReadOnlyList<ProgramDetailsDto>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  102. if (programDetails is null)
  103. {
  104. return Array.Empty<ProgramInfo>();
  105. }
  106. var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y);
  107. var programIdsWithImages = programDetails
  108. .Where(p => p.HasImageArtwork).Select(p => p.ProgramId)
  109. .ToList();
  110. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  111. var programsInfo = new List<ProgramInfo>();
  112. foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs))
  113. {
  114. // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
  115. // " which corresponds to channel " + channelNumber + " and program id " +
  116. // schedule.ProgramId + " which says it has images? " +
  117. // programDict[schedule.ProgramId].hasImageArtwork);
  118. if (string.IsNullOrEmpty(schedule.ProgramId))
  119. {
  120. continue;
  121. }
  122. if (images is not null)
  123. {
  124. var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
  125. if (imageIndex > -1)
  126. {
  127. var programEntry = programDict[schedule.ProgramId];
  128. var allImages = images[imageIndex].Data;
  129. var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
  130. var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
  131. const double DesiredAspect = 2.0 / 3;
  132. programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ??
  133. GetProgramImage(ApiUrl, allImages, DesiredAspect, token);
  134. const double WideAspect = 16.0 / 9;
  135. programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token);
  136. // Don't supply the same image twice
  137. if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal))
  138. {
  139. programEntry.ThumbImage = null;
  140. }
  141. programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token);
  142. // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  143. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  144. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  145. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  146. }
  147. }
  148. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId]));
  149. }
  150. return programsInfo;
  151. }
  152. private static int GetSizeOrder(ImageDataDto image)
  153. {
  154. if (int.TryParse(image.Height, out int value))
  155. {
  156. return value;
  157. }
  158. return 0;
  159. }
  160. private static string GetChannelNumber(MapDto map)
  161. {
  162. var channelNumber = map.LogicalChannelNumber;
  163. if (string.IsNullOrWhiteSpace(channelNumber))
  164. {
  165. channelNumber = map.Channel;
  166. }
  167. if (string.IsNullOrWhiteSpace(channelNumber))
  168. {
  169. channelNumber = map.AtscMajor + "." + map.AtscMinor;
  170. }
  171. return channelNumber.TrimStart('0');
  172. }
  173. private static bool IsMovie(ProgramDetailsDto programInfo)
  174. {
  175. return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase);
  176. }
  177. private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details)
  178. {
  179. if (programInfo.AirDateTime is null)
  180. {
  181. return null;
  182. }
  183. var startAt = programInfo.AirDateTime.Value;
  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.Count != 0)
  189. {
  190. if (programInfo.AudioProperties.Contains("atmos", StringComparison.OrdinalIgnoreCase))
  191. {
  192. audioType = ProgramAudio.Atmos;
  193. }
  194. else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparison.OrdinalIgnoreCase))
  195. {
  196. audioType = ProgramAudio.DolbyDigital;
  197. }
  198. else if (programInfo.AudioProperties.Contains("dd", StringComparison.OrdinalIgnoreCase))
  199. {
  200. audioType = ProgramAudio.DolbyDigital;
  201. }
  202. else if (programInfo.AudioProperties.Contains("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 is not 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 ?? "Unknown",
  223. OfficialRating = null,
  224. CommunityRating = null,
  225. EpisodeTitle = episodeTitle,
  226. Audio = audioType,
  227. // IsNew = programInfo.@new ?? false,
  228. IsRepeat = programInfo.New is 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 is not null)
  255. {
  256. info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase);
  257. info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase);
  258. }
  259. if (details.ContentRating is not null && details.ContentRating.Count > 0)
  260. {
  261. info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal)
  262. .Replace("--", "-", StringComparison.Ordinal);
  263. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  264. if (invalid.Contains(info.OfficialRating, StringComparison.OrdinalIgnoreCase))
  265. {
  266. info.OfficialRating = null;
  267. }
  268. }
  269. if (details.Descriptions is not null)
  270. {
  271. if (details.Descriptions.Description1000 is not null && details.Descriptions.Description1000.Count > 0)
  272. {
  273. info.Overview = details.Descriptions.Description1000[0].Description;
  274. }
  275. else if (details.Descriptions.Description100 is not null && details.Descriptions.Description100.Count > 0)
  276. {
  277. info.Overview = details.Descriptions.Description100[0].Description;
  278. }
  279. }
  280. if (info.IsSeries)
  281. {
  282. info.SeriesId = programId.Substring(0, 10);
  283. info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
  284. if (details.Metadata is not null)
  285. {
  286. foreach (var metadataProgram in details.Metadata)
  287. {
  288. var gracenote = metadataProgram.Gracenote;
  289. if (gracenote is not null)
  290. {
  291. info.SeasonNumber = gracenote.Season;
  292. if (gracenote.Episode > 0)
  293. {
  294. info.EpisodeNumber = gracenote.Episode;
  295. }
  296. break;
  297. }
  298. }
  299. }
  300. }
  301. if (details.OriginalAirDate is not null)
  302. {
  303. info.OriginalAirDate = details.OriginalAirDate;
  304. info.ProductionYear = info.OriginalAirDate.Value.Year;
  305. }
  306. if (details.Movie is not null)
  307. {
  308. if (!string.IsNullOrEmpty(details.Movie.Year)
  309. && int.TryParse(details.Movie.Year, out int year))
  310. {
  311. info.ProductionYear = year;
  312. }
  313. }
  314. if (details.Genres is not null)
  315. {
  316. info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  317. info.IsNews = details.Genres.Contains("news", StringComparison.OrdinalIgnoreCase);
  318. if (info.Genres.Contains("children", StringComparison.OrdinalIgnoreCase))
  319. {
  320. info.IsKids = true;
  321. }
  322. }
  323. return info;
  324. }
  325. private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, string token)
  326. {
  327. var match = images
  328. .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
  329. .ThenByDescending(i => GetSizeOrder(i))
  330. .FirstOrDefault();
  331. if (match is null)
  332. {
  333. return null;
  334. }
  335. var uri = match.Uri;
  336. if (string.IsNullOrWhiteSpace(uri))
  337. {
  338. return null;
  339. }
  340. if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  341. {
  342. return uri;
  343. }
  344. return apiUrl + "/image/" + uri + "?token=" + token;
  345. }
  346. private static double GetAspectRatio(ImageDataDto i)
  347. {
  348. int width = 0;
  349. int height = 0;
  350. if (!string.IsNullOrWhiteSpace(i.Width))
  351. {
  352. _ = int.TryParse(i.Width, out width);
  353. }
  354. if (!string.IsNullOrWhiteSpace(i.Height))
  355. {
  356. _ = int.TryParse(i.Height, out height);
  357. }
  358. if (height == 0 || width == 0)
  359. {
  360. return 0;
  361. }
  362. double result = width;
  363. result /= height;
  364. return result;
  365. }
  366. private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
  367. ListingsProviderInfo info,
  368. IReadOnlyList<string> programIds,
  369. CancellationToken cancellationToken)
  370. {
  371. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  372. if (programIds.Count == 0)
  373. {
  374. return Array.Empty<ShowImagesDto>();
  375. }
  376. StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
  377. foreach (ReadOnlySpan<char> i in programIds)
  378. {
  379. str.Append('"')
  380. .Append(i.Slice(0, 10))
  381. .Append("\",");
  382. }
  383. // Remove last ,
  384. str.Length--;
  385. str.Append(']');
  386. using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
  387. {
  388. Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
  389. };
  390. message.Headers.TryAddWithoutValidation("token", token);
  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<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  396. }
  397. catch (Exception ex)
  398. {
  399. _logger.LogError(ex, "Error getting image info from schedules direct");
  400. return Array.Empty<ShowImagesDto>();
  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<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  418. if (root is not null)
  419. {
  420. foreach (HeadendsDto headend in root)
  421. {
  422. foreach (LineupDto 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?[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)
  467. && long.TryParse(savedToken.Value, CultureInfo.InvariantCulture, out long ticks))
  468. {
  469. // If it's under 24 hours old we can still use it
  470. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  471. {
  472. return savedToken.Name;
  473. }
  474. }
  475. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  476. try
  477. {
  478. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  479. savedToken.Name = result;
  480. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  481. return result;
  482. }
  483. catch (HttpRequestException ex)
  484. {
  485. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  486. {
  487. _tokens.Clear();
  488. _lastErrorResponse = DateTime.UtcNow;
  489. }
  490. throw;
  491. }
  492. finally
  493. {
  494. _tokenSemaphore.Release();
  495. }
  496. }
  497. private async Task<HttpResponseMessage> Send(
  498. HttpRequestMessage options,
  499. bool enableRetry,
  500. ListingsProviderInfo providerInfo,
  501. CancellationToken cancellationToken,
  502. HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
  503. {
  504. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  505. .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
  506. if (response.IsSuccessStatusCode)
  507. {
  508. return response;
  509. }
  510. // Response is automatically disposed in the calling function,
  511. // so dispose manually if not returning.
  512. response.Dispose();
  513. if (!enableRetry || (int)response.StatusCode >= 500)
  514. {
  515. throw new HttpRequestException(
  516. string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
  517. null,
  518. response.StatusCode);
  519. }
  520. _tokens.Clear();
  521. options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
  522. return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
  523. }
  524. private async Task<string> GetTokenInternal(
  525. string username,
  526. string password,
  527. CancellationToken cancellationToken)
  528. {
  529. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
  530. #pragma warning disable CA5350 // SchedulesDirect is always SHA1.
  531. var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password));
  532. #pragma warning restore CA5350
  533. // TODO: remove ToLower when Convert.ToHexString supports lowercase
  534. // Schedules Direct requires the hex to be lowercase
  535. string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
  536. options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
  537. using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  538. response.EnsureSuccessStatusCode();
  539. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  540. var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  541. if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
  542. {
  543. _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
  544. return root.Token;
  545. }
  546. throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message);
  547. }
  548. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  549. {
  550. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  551. ArgumentException.ThrowIfNullOrEmpty(token);
  552. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  553. _logger.LogInformation("Adding new LineUp ");
  554. using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
  555. options.Headers.TryAddWithoutValidation("token", token);
  556. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  557. }
  558. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  559. {
  560. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  561. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  562. ArgumentException.ThrowIfNullOrEmpty(token);
  563. _logger.LogInformation("Headends on account ");
  564. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
  565. options.Headers.TryAddWithoutValidation("token", token);
  566. try
  567. {
  568. using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  569. httpResponse.EnsureSuccessStatusCode();
  570. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  571. using var response = httpResponse.Content;
  572. var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  573. return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
  574. }
  575. catch (HttpRequestException ex)
  576. {
  577. // SchedulesDirect returns 400 if no lineups are configured.
  578. if (ex.StatusCode is HttpStatusCode.BadRequest)
  579. {
  580. return false;
  581. }
  582. throw;
  583. }
  584. }
  585. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  586. {
  587. if (validateLogin)
  588. {
  589. ArgumentException.ThrowIfNullOrEmpty(info.Username);
  590. ArgumentException.ThrowIfNullOrEmpty(info.Password);
  591. }
  592. if (validateListings)
  593. {
  594. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  595. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  596. if (!hasLineup)
  597. {
  598. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  599. }
  600. }
  601. }
  602. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  603. {
  604. return GetHeadends(info, country, location, CancellationToken.None);
  605. }
  606. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  607. {
  608. var listingsId = info.ListingsId;
  609. ArgumentException.ThrowIfNullOrEmpty(listingsId);
  610. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  611. ArgumentException.ThrowIfNullOrEmpty(token);
  612. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  613. options.Headers.TryAddWithoutValidation("token", token);
  614. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  615. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  616. var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  617. if (root is null)
  618. {
  619. return new List<ChannelInfo>();
  620. }
  621. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count);
  622. _logger.LogInformation("Mapping Stations to Channel");
  623. var allStations = root.Stations;
  624. var map = root.Map;
  625. var list = new List<ChannelInfo>(map.Count);
  626. foreach (var channel in map)
  627. {
  628. var channelNumber = GetChannelNumber(channel);
  629. var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase));
  630. var station = stationIndex == -1
  631. ? new StationDto { StationId = channel.StationId }
  632. : allStations[stationIndex];
  633. var channelInfo = new ChannelInfo
  634. {
  635. Id = station.StationId,
  636. CallSign = station.Callsign,
  637. Number = channelNumber,
  638. Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name
  639. };
  640. if (station.Logo is not null)
  641. {
  642. channelInfo.ImageUrl = station.Logo.Url;
  643. }
  644. list.Add(channelInfo);
  645. }
  646. return list;
  647. }
  648. /// <inheritdoc />
  649. public void Dispose()
  650. {
  651. Dispose(true);
  652. GC.SuppressFinalize(this);
  653. }
  654. /// <summary>
  655. /// Releases unmanaged and optionally managed resources.
  656. /// </summary>
  657. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  658. protected virtual void Dispose(bool disposing)
  659. {
  660. if (_disposed)
  661. {
  662. return;
  663. }
  664. if (disposing)
  665. {
  666. _tokenSemaphore?.Dispose();
  667. }
  668. _disposed = true;
  669. }
  670. }
  671. }