SchedulesDirect.cs 33 KB

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