SchedulesDirect.cs 33 KB

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