SchedulesDirect.cs 31 KB

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