SchedulesDirect.cs 33 KB

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