SchedulesDirect.cs 33 KB

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