SchedulesDirect.cs 33 KB

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