SchedulesDirect.cs 33 KB

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