SchedulesDirect.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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. else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  341. {
  342. return uri;
  343. }
  344. else
  345. {
  346. return apiUrl + "/image/" + uri + "?token=" + token;
  347. }
  348. }
  349. private static double GetAspectRatio(ImageDataDto i)
  350. {
  351. int width = 0;
  352. int height = 0;
  353. if (!string.IsNullOrWhiteSpace(i.Width))
  354. {
  355. _ = int.TryParse(i.Width, out width);
  356. }
  357. if (!string.IsNullOrWhiteSpace(i.Height))
  358. {
  359. _ = int.TryParse(i.Height, out height);
  360. }
  361. if (height == 0 || width == 0)
  362. {
  363. return 0;
  364. }
  365. double result = width;
  366. result /= height;
  367. return result;
  368. }
  369. private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
  370. ListingsProviderInfo info,
  371. IReadOnlyList<string> programIds,
  372. CancellationToken cancellationToken)
  373. {
  374. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  375. if (programIds.Count == 0)
  376. {
  377. return Array.Empty<ShowImagesDto>();
  378. }
  379. StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
  380. foreach (ReadOnlySpan<char> i in programIds)
  381. {
  382. str.Append('"')
  383. .Append(i.Slice(0, 10))
  384. .Append("\",");
  385. }
  386. // Remove last ,
  387. str.Length--;
  388. str.Append(']');
  389. using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
  390. {
  391. Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
  392. };
  393. message.Headers.TryAddWithoutValidation("token", token);
  394. try
  395. {
  396. using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
  397. await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  398. return await JsonSerializer.DeserializeAsync<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  399. }
  400. catch (Exception ex)
  401. {
  402. _logger.LogError(ex, "Error getting image info from schedules direct");
  403. return Array.Empty<ShowImagesDto>();
  404. }
  405. }
  406. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  407. {
  408. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  409. var lineups = new List<NameIdPair>();
  410. if (string.IsNullOrWhiteSpace(token))
  411. {
  412. return lineups;
  413. }
  414. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
  415. options.Headers.TryAddWithoutValidation("token", token);
  416. try
  417. {
  418. using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
  419. await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  420. var root = await JsonSerializer.DeserializeAsync<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  421. if (root is not null)
  422. {
  423. foreach (HeadendsDto headend in root)
  424. {
  425. foreach (LineupDto lineup in headend.Lineups)
  426. {
  427. lineups.Add(new NameIdPair
  428. {
  429. Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name,
  430. Id = lineup.Uri?[18..]
  431. });
  432. }
  433. }
  434. }
  435. else
  436. {
  437. _logger.LogInformation("No lineups available");
  438. }
  439. }
  440. catch (Exception ex)
  441. {
  442. _logger.LogError(ex, "Error getting headends");
  443. }
  444. return lineups;
  445. }
  446. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  447. {
  448. var username = info.Username;
  449. // Reset the token if there's no username
  450. if (string.IsNullOrWhiteSpace(username))
  451. {
  452. return null;
  453. }
  454. var password = info.Password;
  455. if (string.IsNullOrEmpty(password))
  456. {
  457. return null;
  458. }
  459. // Avoid hammering SD
  460. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  461. {
  462. return null;
  463. }
  464. if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
  465. {
  466. savedToken = new NameValuePair();
  467. _tokens.TryAdd(username, savedToken);
  468. }
  469. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  470. {
  471. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
  472. {
  473. // If it's under 24 hours old we can still use it
  474. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  475. {
  476. return savedToken.Name;
  477. }
  478. }
  479. }
  480. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  481. try
  482. {
  483. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  484. savedToken.Name = result;
  485. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  486. return result;
  487. }
  488. catch (HttpRequestException ex)
  489. {
  490. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  491. {
  492. _tokens.Clear();
  493. _lastErrorResponse = DateTime.UtcNow;
  494. }
  495. throw;
  496. }
  497. finally
  498. {
  499. _tokenSemaphore.Release();
  500. }
  501. }
  502. private async Task<HttpResponseMessage> Send(
  503. HttpRequestMessage options,
  504. bool enableRetry,
  505. ListingsProviderInfo providerInfo,
  506. CancellationToken cancellationToken,
  507. HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
  508. {
  509. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  510. .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
  511. if (response.IsSuccessStatusCode)
  512. {
  513. return response;
  514. }
  515. // Response is automatically disposed in the calling function,
  516. // so dispose manually if not returning.
  517. response.Dispose();
  518. if (!enableRetry || (int)response.StatusCode >= 500)
  519. {
  520. throw new HttpRequestException(
  521. string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
  522. null,
  523. response.StatusCode);
  524. }
  525. _tokens.Clear();
  526. options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
  527. return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
  528. }
  529. private async Task<string> GetTokenInternal(
  530. string username,
  531. string password,
  532. CancellationToken cancellationToken)
  533. {
  534. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
  535. #pragma warning disable CA5350 // SchedulesDirect is always SHA1.
  536. var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password));
  537. #pragma warning restore CA5350
  538. // TODO: remove ToLower when Convert.ToHexString supports lowercase
  539. // Schedules Direct requires the hex to be lowercase
  540. string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
  541. options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
  542. using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  543. response.EnsureSuccessStatusCode();
  544. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  545. var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  546. if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
  547. {
  548. _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
  549. return root.Token;
  550. }
  551. throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message);
  552. }
  553. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  554. {
  555. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  556. ArgumentException.ThrowIfNullOrEmpty(token);
  557. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  558. _logger.LogInformation("Adding new LineUp ");
  559. using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
  560. options.Headers.TryAddWithoutValidation("token", token);
  561. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  562. }
  563. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  564. {
  565. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  566. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  567. ArgumentException.ThrowIfNullOrEmpty(token);
  568. _logger.LogInformation("Headends on account ");
  569. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
  570. options.Headers.TryAddWithoutValidation("token", token);
  571. try
  572. {
  573. using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  574. httpResponse.EnsureSuccessStatusCode();
  575. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  576. using var response = httpResponse.Content;
  577. var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  578. return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
  579. }
  580. catch (HttpRequestException ex)
  581. {
  582. // SchedulesDirect returns 400 if no lineups are configured.
  583. if (ex.StatusCode is HttpStatusCode.BadRequest)
  584. {
  585. return false;
  586. }
  587. throw;
  588. }
  589. }
  590. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  591. {
  592. if (validateLogin)
  593. {
  594. ArgumentException.ThrowIfNullOrEmpty(info.Username);
  595. ArgumentException.ThrowIfNullOrEmpty(info.Password);
  596. }
  597. if (validateListings)
  598. {
  599. ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
  600. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  601. if (!hasLineup)
  602. {
  603. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  604. }
  605. }
  606. }
  607. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  608. {
  609. return GetHeadends(info, country, location, CancellationToken.None);
  610. }
  611. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  612. {
  613. var listingsId = info.ListingsId;
  614. ArgumentException.ThrowIfNullOrEmpty(listingsId);
  615. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  616. ArgumentException.ThrowIfNullOrEmpty(token);
  617. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  618. options.Headers.TryAddWithoutValidation("token", token);
  619. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  620. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  621. var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  622. if (root is null)
  623. {
  624. return new List<ChannelInfo>();
  625. }
  626. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count);
  627. _logger.LogInformation("Mapping Stations to Channel");
  628. var allStations = root.Stations;
  629. var map = root.Map;
  630. var list = new List<ChannelInfo>(map.Count);
  631. foreach (var channel in map)
  632. {
  633. var channelNumber = GetChannelNumber(channel);
  634. var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase));
  635. var station = stationIndex == -1
  636. ? new StationDto { StationId = channel.StationId }
  637. : allStations[stationIndex];
  638. var channelInfo = new ChannelInfo
  639. {
  640. Id = station.StationId,
  641. CallSign = station.Callsign,
  642. Number = channelNumber,
  643. Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name
  644. };
  645. if (station.Logo is not null)
  646. {
  647. channelInfo.ImageUrl = station.Logo.Url;
  648. }
  649. list.Add(channelInfo);
  650. }
  651. return list;
  652. }
  653. /// <inheritdoc />
  654. public void Dispose()
  655. {
  656. Dispose(true);
  657. GC.SuppressFinalize(this);
  658. }
  659. /// <summary>
  660. /// Releases unmanaged and optionally managed resources.
  661. /// </summary>
  662. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  663. protected virtual void Dispose(bool disposing)
  664. {
  665. if (_disposed)
  666. {
  667. return;
  668. }
  669. if (disposing)
  670. {
  671. _tokenSemaphore?.Dispose();
  672. }
  673. _disposed = true;
  674. }
  675. }
  676. }