SchedulesDirect.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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 MediaBrowser.Common;
  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 IApplicationHost _appHost;
  33. private readonly ICryptoProvider _cryptoProvider;
  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. IApplicationHost appHost,
  41. ICryptoProvider cryptoProvider)
  42. {
  43. _logger = logger;
  44. _httpClientFactory = httpClientFactory;
  45. _appHost = appHost;
  46. _cryptoProvider = cryptoProvider;
  47. }
  48. /// <inheritdoc />
  49. public string Name => "Schedules Direct";
  50. /// <inheritdoc />
  51. public string Type => nameof(SchedulesDirect);
  52. private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  53. {
  54. var dates = new List<string>();
  55. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  56. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  57. while (start <= end)
  58. {
  59. dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
  60. start = start.AddDays(1);
  61. }
  62. return dates;
  63. }
  64. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  65. {
  66. if (string.IsNullOrEmpty(channelId))
  67. {
  68. throw new ArgumentNullException(nameof(channelId));
  69. }
  70. // Normalize incoming input
  71. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  72. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  73. if (string.IsNullOrEmpty(token))
  74. {
  75. _logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
  76. return Enumerable.Empty<ProgramInfo>();
  77. }
  78. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  79. _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
  80. var requestList = new List<ScheduleDirect.RequestScheduleForChannel>()
  81. {
  82. new ScheduleDirect.RequestScheduleForChannel()
  83. {
  84. stationID = channelId,
  85. date = dates
  86. }
  87. };
  88. var requestString = JsonSerializer.Serialize(requestList, _jsonOptions);
  89. _logger.LogDebug("Request string for schedules is: {RequestString}", requestString);
  90. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
  91. options.Content = new StringContent(requestString, Encoding.UTF8, MediaTypeNames.Application.Json);
  92. options.Headers.TryAddWithoutValidation("token", token);
  93. using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  94. await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  95. var dailySchedules = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Day>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  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 programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct();
  100. programRequestOptions.Content = new StringContent("[\"" + string.Join("\", \"", programsID) + "\"]", Encoding.UTF8, MediaTypeNames.Application.Json);
  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<List<ScheduleDirect.ProgramDetails>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  104. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  105. var programIdsWithImages = programDetails
  106. .Where(p => p.hasImageArtwork).Select(p => p.programID)
  107. .ToList();
  108. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  109. var programsInfo = new List<ProgramInfo>();
  110. foreach (ScheduleDirect.Program schedule in dailySchedules.SelectMany(d => d.programs))
  111. {
  112. // _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
  113. // " which corresponds to channel " + channelNumber + " and program id " +
  114. // schedule.programID + " which says it has images? " +
  115. // programDict[schedule.programID].hasImageArtwork);
  116. if (images != null)
  117. {
  118. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  119. if (imageIndex > -1)
  120. {
  121. var programEntry = programDict[schedule.programID];
  122. var allImages = images[imageIndex].data ?? new List<ScheduleDirect.ImageData>();
  123. var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase));
  124. var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase));
  125. const double DesiredAspect = 2.0 / 3;
  126. programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, DesiredAspect) ??
  127. GetProgramImage(ApiUrl, allImages, true, DesiredAspect);
  128. const double WideAspect = 16.0 / 9;
  129. programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, WideAspect);
  130. // Don't supply the same image twice
  131. if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
  132. {
  133. programEntry.thumbImage = null;
  134. }
  135. programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, WideAspect);
  136. // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  137. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  138. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  139. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  140. }
  141. }
  142. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
  143. }
  144. return programsInfo;
  145. }
  146. private static int GetSizeOrder(ScheduleDirect.ImageData image)
  147. {
  148. if (int.TryParse(image.height, out int value))
  149. {
  150. return value;
  151. }
  152. return 0;
  153. }
  154. private static string GetChannelNumber(ScheduleDirect.Map map)
  155. {
  156. var channelNumber = map.logicalChannelNumber;
  157. if (string.IsNullOrWhiteSpace(channelNumber))
  158. {
  159. channelNumber = map.channel;
  160. }
  161. if (string.IsNullOrWhiteSpace(channelNumber))
  162. {
  163. channelNumber = map.atscMajor + "." + map.atscMinor;
  164. }
  165. return channelNumber.TrimStart('0');
  166. }
  167. private static bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
  168. {
  169. return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase);
  170. }
  171. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  172. {
  173. var startAt = GetDate(programInfo.airDateTime);
  174. var endAt = startAt.AddSeconds(programInfo.duration);
  175. var audioType = ProgramAudio.Stereo;
  176. var programId = programInfo.programID ?? string.Empty;
  177. string newID = programId + "T" + startAt.Ticks + "C" + channelId;
  178. if (programInfo.audioProperties != null)
  179. {
  180. if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
  181. {
  182. audioType = ProgramAudio.Atmos;
  183. }
  184. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  185. {
  186. audioType = ProgramAudio.DolbyDigital;
  187. }
  188. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  189. {
  190. audioType = ProgramAudio.DolbyDigital;
  191. }
  192. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  193. {
  194. audioType = ProgramAudio.Stereo;
  195. }
  196. else
  197. {
  198. audioType = ProgramAudio.Mono;
  199. }
  200. }
  201. string episodeTitle = null;
  202. if (details.episodeTitle150 != null)
  203. {
  204. episodeTitle = details.episodeTitle150;
  205. }
  206. var info = new ProgramInfo
  207. {
  208. ChannelId = channelId,
  209. Id = newID,
  210. StartDate = startAt,
  211. EndDate = endAt,
  212. Name = details.titles[0].title120 ?? "Unknown",
  213. OfficialRating = null,
  214. CommunityRating = null,
  215. EpisodeTitle = episodeTitle,
  216. Audio = audioType,
  217. // IsNew = programInfo.@new ?? false,
  218. IsRepeat = programInfo.@new == null,
  219. IsSeries = string.Equals(details.entityType, "episode", StringComparison.OrdinalIgnoreCase),
  220. ImageUrl = details.primaryImage,
  221. ThumbImageUrl = details.thumbImage,
  222. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  223. IsSports = string.Equals(details.entityType, "sports", StringComparison.OrdinalIgnoreCase),
  224. IsMovie = IsMovie(details),
  225. Etag = programInfo.md5,
  226. IsLive = string.Equals(programInfo.liveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
  227. IsPremiere = programInfo.premiere || (programInfo.isPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
  228. };
  229. var showId = programId;
  230. if (!info.IsSeries)
  231. {
  232. // It's also a series if it starts with SH
  233. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  234. }
  235. // According to SchedulesDirect, these are generic, unidentified episodes
  236. // SH005316560000
  237. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  238. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  239. if (!hasUniqueShowId)
  240. {
  241. showId = newID;
  242. }
  243. info.ShowId = showId;
  244. if (programInfo.videoProperties != null)
  245. {
  246. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  247. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  248. }
  249. if (details.contentRating != null && details.contentRating.Count > 0)
  250. {
  251. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-", StringComparison.Ordinal)
  252. .Replace("--", "-", StringComparison.Ordinal);
  253. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  254. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  255. {
  256. info.OfficialRating = null;
  257. }
  258. }
  259. if (details.descriptions != null)
  260. {
  261. if (details.descriptions.description1000 != null && details.descriptions.description1000.Count > 0)
  262. {
  263. info.Overview = details.descriptions.description1000[0].description;
  264. }
  265. else if (details.descriptions.description100 != null && details.descriptions.description100.Count > 0)
  266. {
  267. info.Overview = details.descriptions.description100[0].description;
  268. }
  269. }
  270. if (info.IsSeries)
  271. {
  272. info.SeriesId = programId.Substring(0, 10);
  273. info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
  274. if (details.metadata != null)
  275. {
  276. foreach (var metadataProgram in details.metadata)
  277. {
  278. var gracenote = metadataProgram.Gracenote;
  279. if (gracenote != null)
  280. {
  281. info.SeasonNumber = gracenote.season;
  282. if (gracenote.episode > 0)
  283. {
  284. info.EpisodeNumber = gracenote.episode;
  285. }
  286. break;
  287. }
  288. }
  289. }
  290. }
  291. if (!string.IsNullOrWhiteSpace(details.originalAirDate))
  292. {
  293. info.OriginalAirDate = DateTime.Parse(details.originalAirDate, CultureInfo.InvariantCulture);
  294. info.ProductionYear = info.OriginalAirDate.Value.Year;
  295. }
  296. if (details.movie != null)
  297. {
  298. if (!string.IsNullOrEmpty(details.movie.year)
  299. && int.TryParse(details.movie.year, out int year))
  300. {
  301. info.ProductionYear = year;
  302. }
  303. }
  304. if (details.genres != null)
  305. {
  306. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  307. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  308. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  309. {
  310. info.IsKids = true;
  311. }
  312. }
  313. return info;
  314. }
  315. private static DateTime GetDate(string value)
  316. {
  317. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  318. if (date.Kind != DateTimeKind.Utc)
  319. {
  320. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  321. }
  322. return date;
  323. }
  324. private string GetProgramImage(string apiUrl, IEnumerable<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
  325. {
  326. var match = images
  327. .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
  328. .ThenByDescending(GetSizeOrder)
  329. .FirstOrDefault();
  330. if (match == null)
  331. {
  332. return null;
  333. }
  334. var uri = match.uri;
  335. if (string.IsNullOrWhiteSpace(uri))
  336. {
  337. return null;
  338. }
  339. else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  340. {
  341. return uri;
  342. }
  343. else
  344. {
  345. return apiUrl + "/image/" + uri;
  346. }
  347. }
  348. private static double GetAspectRatio(ScheduleDirect.ImageData i)
  349. {
  350. int width = 0;
  351. int height = 0;
  352. if (!string.IsNullOrWhiteSpace(i.width))
  353. {
  354. int.TryParse(i.width, out width);
  355. }
  356. if (!string.IsNullOrWhiteSpace(i.height))
  357. {
  358. int.TryParse(i.height, out height);
  359. }
  360. if (height == 0 || width == 0)
  361. {
  362. return 0;
  363. }
  364. double result = width;
  365. result /= height;
  366. return result;
  367. }
  368. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  369. ListingsProviderInfo info,
  370. IReadOnlyList<string> programIds,
  371. CancellationToken cancellationToken)
  372. {
  373. if (programIds.Count == 0)
  374. {
  375. return new List<ScheduleDirect.ShowImages>();
  376. }
  377. StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
  378. foreach (ReadOnlySpan<char> i in programIds)
  379. {
  380. str.Append('"')
  381. .Append(i.Slice(0, 10))
  382. .Append("\",");
  383. }
  384. // Remove last ,
  385. str.Length--;
  386. str.Append(']');
  387. using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
  388. {
  389. Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
  390. };
  391. try
  392. {
  393. using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
  394. await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  395. return await JsonSerializer.DeserializeAsync<List<ScheduleDirect.ShowImages>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  396. }
  397. catch (Exception ex)
  398. {
  399. _logger.LogError(ex, "Error getting image info from schedules direct");
  400. return new List<ScheduleDirect.ShowImages>();
  401. }
  402. }
  403. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  404. {
  405. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  406. var lineups = new List<NameIdPair>();
  407. if (string.IsNullOrWhiteSpace(token))
  408. {
  409. return lineups;
  410. }
  411. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
  412. options.Headers.TryAddWithoutValidation("token", token);
  413. try
  414. {
  415. using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
  416. await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  417. var root = await JsonSerializer.DeserializeAsync<List<ScheduleDirect.Headends>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
  418. if (root != null)
  419. {
  420. foreach (ScheduleDirect.Headends headend in root)
  421. {
  422. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  423. {
  424. lineups.Add(new NameIdPair
  425. {
  426. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  427. Id = lineup.uri.Substring(18)
  428. });
  429. }
  430. }
  431. }
  432. else
  433. {
  434. _logger.LogInformation("No lineups available");
  435. }
  436. }
  437. catch (Exception ex)
  438. {
  439. _logger.LogError(ex, "Error getting headends");
  440. }
  441. return lineups;
  442. }
  443. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  444. {
  445. var username = info.Username;
  446. // Reset the token if there's no username
  447. if (string.IsNullOrWhiteSpace(username))
  448. {
  449. return null;
  450. }
  451. var password = info.Password;
  452. if (string.IsNullOrEmpty(password))
  453. {
  454. return null;
  455. }
  456. // Avoid hammering SD
  457. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  458. {
  459. return null;
  460. }
  461. if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
  462. {
  463. savedToken = new NameValuePair();
  464. _tokens.TryAdd(username, savedToken);
  465. }
  466. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  467. {
  468. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
  469. {
  470. // If it's under 24 hours old we can still use it
  471. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  472. {
  473. return savedToken.Name;
  474. }
  475. }
  476. }
  477. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  478. try
  479. {
  480. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  481. savedToken.Name = result;
  482. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  483. return result;
  484. }
  485. catch (HttpRequestException ex)
  486. {
  487. if (ex.StatusCode.HasValue)
  488. {
  489. if ((int)ex.StatusCode.Value == 400)
  490. {
  491. _tokens.Clear();
  492. _lastErrorResponse = DateTime.UtcNow;
  493. }
  494. }
  495. throw;
  496. }
  497. finally
  498. {
  499. _tokenSemaphore.Release();
  500. }
  501. }
  502. private async Task<HttpResponseMessage> Send(
  503. HttpRequestMessage options,
  504. bool enableRetry,
  505. ListingsProviderInfo providerInfo,
  506. CancellationToken cancellationToken,
  507. HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
  508. {
  509. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  510. .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
  511. if (response.IsSuccessStatusCode)
  512. {
  513. return response;
  514. }
  515. // Response is automatically disposed in the calling function,
  516. // so dispose manually if not returning.
  517. response.Dispose();
  518. if (!enableRetry || (int)response.StatusCode >= 500)
  519. {
  520. throw new HttpRequestException(
  521. string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
  522. null,
  523. response.StatusCode);
  524. }
  525. _tokens.Clear();
  526. options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
  527. return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
  528. }
  529. private async Task<string> GetTokenInternal(
  530. string username,
  531. string password,
  532. CancellationToken cancellationToken)
  533. {
  534. using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
  535. var hashedPasswordBytes = _cryptoProvider.ComputeHash("SHA1", Encoding.ASCII.GetBytes(password), Array.Empty<byte>());
  536. // TODO: remove ToLower when Convert.ToHexString supports lowercase
  537. // Schedules Direct requires the hex to be lowercase
  538. string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
  539. options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
  540. using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  541. response.EnsureSuccessStatusCode();
  542. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  543. var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Token>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  544. if (string.Equals(root.message, "OK", StringComparison.Ordinal))
  545. {
  546. _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
  547. return root.token;
  548. }
  549. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  550. }
  551. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  552. {
  553. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  554. if (string.IsNullOrEmpty(token))
  555. {
  556. throw new ArgumentException("Authentication required.");
  557. }
  558. if (string.IsNullOrEmpty(info.ListingsId))
  559. {
  560. throw new ArgumentException("Listings Id required");
  561. }
  562. _logger.LogInformation("Adding new LineUp ");
  563. using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
  564. options.Headers.TryAddWithoutValidation("token", token);
  565. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  566. }
  567. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  568. {
  569. if (string.IsNullOrEmpty(info.ListingsId))
  570. {
  571. throw new ArgumentException("Listings Id required");
  572. }
  573. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  574. if (string.IsNullOrEmpty(token))
  575. {
  576. throw new Exception("token required");
  577. }
  578. _logger.LogInformation("Headends on account ");
  579. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
  580. options.Headers.TryAddWithoutValidation("token", token);
  581. try
  582. {
  583. using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  584. httpResponse.EnsureSuccessStatusCode();
  585. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  586. using var response = httpResponse.Content;
  587. var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Lineups>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  588. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  589. }
  590. catch (HttpRequestException ex)
  591. {
  592. // SchedulesDirect returns 400 if no lineups are configured.
  593. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  594. {
  595. return false;
  596. }
  597. throw;
  598. }
  599. }
  600. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  601. {
  602. if (validateLogin)
  603. {
  604. if (string.IsNullOrEmpty(info.Username))
  605. {
  606. throw new ArgumentException("Username is required");
  607. }
  608. if (string.IsNullOrEmpty(info.Password))
  609. {
  610. throw new ArgumentException("Password is required");
  611. }
  612. }
  613. if (validateListings)
  614. {
  615. if (string.IsNullOrEmpty(info.ListingsId))
  616. {
  617. throw new ArgumentException("Listings Id required");
  618. }
  619. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  620. if (!hasLineup)
  621. {
  622. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  623. }
  624. }
  625. }
  626. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  627. {
  628. return GetHeadends(info, country, location, CancellationToken.None);
  629. }
  630. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  631. {
  632. var listingsId = info.ListingsId;
  633. if (string.IsNullOrEmpty(listingsId))
  634. {
  635. throw new Exception("ListingsId required");
  636. }
  637. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  638. if (string.IsNullOrEmpty(token))
  639. {
  640. throw new Exception("token required");
  641. }
  642. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  643. options.Headers.TryAddWithoutValidation("token", token);
  644. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  645. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  646. var root = await JsonSerializer.DeserializeAsync<ScheduleDirect.Channel>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  647. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
  648. _logger.LogInformation("Mapping Stations to Channel");
  649. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  650. var map = root.map;
  651. var list = new List<ChannelInfo>(map.Count);
  652. foreach (var channel in map)
  653. {
  654. var channelNumber = GetChannelNumber(channel);
  655. var station = allStations.Find(item => string.Equals(item.stationID, channel.stationID, StringComparison.OrdinalIgnoreCase))
  656. ?? new ScheduleDirect.Station
  657. {
  658. stationID = channel.stationID
  659. };
  660. var channelInfo = new ChannelInfo
  661. {
  662. Id = station.stationID,
  663. CallSign = station.callsign,
  664. Number = channelNumber,
  665. Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
  666. };
  667. if (station.logo != null)
  668. {
  669. channelInfo.ImageUrl = station.logo.URL;
  670. }
  671. list.Add(channelInfo);
  672. }
  673. return list;
  674. }
  675. private static string NormalizeName(string value)
  676. {
  677. return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
  678. }
  679. public class ScheduleDirect
  680. {
  681. public class Token
  682. {
  683. public int code { get; set; }
  684. public string message { get; set; }
  685. public string serverID { get; set; }
  686. public string token { get; set; }
  687. }
  688. public class Lineup
  689. {
  690. public string lineup { get; set; }
  691. public string name { get; set; }
  692. public string transport { get; set; }
  693. public string location { get; set; }
  694. public string uri { get; set; }
  695. }
  696. public class Lineups
  697. {
  698. public int code { get; set; }
  699. public string serverID { get; set; }
  700. public string datetime { get; set; }
  701. public List<Lineup> lineups { get; set; }
  702. }
  703. public class Headends
  704. {
  705. public string headend { get; set; }
  706. public string transport { get; set; }
  707. public string location { get; set; }
  708. public List<Lineup> lineups { get; set; }
  709. }
  710. public class Map
  711. {
  712. public string stationID { get; set; }
  713. public string channel { get; set; }
  714. public string logicalChannelNumber { get; set; }
  715. public int uhfVhf { get; set; }
  716. public int atscMajor { get; set; }
  717. public int atscMinor { get; set; }
  718. }
  719. public class Broadcaster
  720. {
  721. public string city { get; set; }
  722. public string state { get; set; }
  723. public string postalcode { get; set; }
  724. public string country { get; set; }
  725. }
  726. public class Logo
  727. {
  728. public string URL { get; set; }
  729. public int height { get; set; }
  730. public int width { get; set; }
  731. public string md5 { get; set; }
  732. }
  733. public class Station
  734. {
  735. public string stationID { get; set; }
  736. public string name { get; set; }
  737. public string callsign { get; set; }
  738. public List<string> broadcastLanguage { get; set; }
  739. public List<string> descriptionLanguage { get; set; }
  740. public Broadcaster broadcaster { get; set; }
  741. public string affiliate { get; set; }
  742. public Logo logo { get; set; }
  743. public bool? isCommercialFree { get; set; }
  744. }
  745. public class Metadata
  746. {
  747. public string lineup { get; set; }
  748. public string modified { get; set; }
  749. public string transport { get; set; }
  750. }
  751. public class Channel
  752. {
  753. public List<Map> map { get; set; }
  754. public List<Station> stations { get; set; }
  755. public Metadata metadata { get; set; }
  756. }
  757. public class RequestScheduleForChannel
  758. {
  759. public string stationID { get; set; }
  760. public List<string> date { get; set; }
  761. }
  762. public class Rating
  763. {
  764. public string body { get; set; }
  765. public string code { get; set; }
  766. }
  767. public class Multipart
  768. {
  769. public int partNumber { get; set; }
  770. public int totalParts { get; set; }
  771. }
  772. public class Program
  773. {
  774. public string programID { get; set; }
  775. public string airDateTime { get; set; }
  776. public int duration { get; set; }
  777. public string md5 { get; set; }
  778. public List<string> audioProperties { get; set; }
  779. public List<string> videoProperties { get; set; }
  780. public List<Rating> ratings { get; set; }
  781. public bool? @new { get; set; }
  782. public Multipart multipart { get; set; }
  783. public string liveTapeDelay { get; set; }
  784. public bool premiere { get; set; }
  785. public bool repeat { get; set; }
  786. public string isPremiereOrFinale { get; set; }
  787. }
  788. public class MetadataSchedule
  789. {
  790. public string modified { get; set; }
  791. public string md5 { get; set; }
  792. public string startDate { get; set; }
  793. public string endDate { get; set; }
  794. public int days { get; set; }
  795. }
  796. public class Day
  797. {
  798. public string stationID { get; set; }
  799. public List<Program> programs { get; set; }
  800. public MetadataSchedule metadata { get; set; }
  801. public Day()
  802. {
  803. programs = new List<Program>();
  804. }
  805. }
  806. public class Title
  807. {
  808. public string title120 { get; set; }
  809. }
  810. public class EventDetails
  811. {
  812. public string subType { get; set; }
  813. }
  814. public class Description100
  815. {
  816. public string descriptionLanguage { get; set; }
  817. public string description { get; set; }
  818. }
  819. public class Description1000
  820. {
  821. public string descriptionLanguage { get; set; }
  822. public string description { get; set; }
  823. }
  824. public class DescriptionsProgram
  825. {
  826. public List<Description100> description100 { get; set; }
  827. public List<Description1000> description1000 { get; set; }
  828. }
  829. public class Gracenote
  830. {
  831. public int season { get; set; }
  832. public int episode { get; set; }
  833. }
  834. public class MetadataPrograms
  835. {
  836. public Gracenote Gracenote { get; set; }
  837. }
  838. public class ContentRating
  839. {
  840. public string body { get; set; }
  841. public string code { get; set; }
  842. }
  843. public class Cast
  844. {
  845. public string billingOrder { get; set; }
  846. public string role { get; set; }
  847. public string nameId { get; set; }
  848. public string personId { get; set; }
  849. public string name { get; set; }
  850. public string characterName { get; set; }
  851. }
  852. public class Crew
  853. {
  854. public string billingOrder { get; set; }
  855. public string role { get; set; }
  856. public string nameId { get; set; }
  857. public string personId { get; set; }
  858. public string name { get; set; }
  859. }
  860. public class QualityRating
  861. {
  862. public string ratingsBody { get; set; }
  863. public string rating { get; set; }
  864. public string minRating { get; set; }
  865. public string maxRating { get; set; }
  866. public string increment { get; set; }
  867. }
  868. public class Movie
  869. {
  870. public string year { get; set; }
  871. public int duration { get; set; }
  872. public List<QualityRating> qualityRating { get; set; }
  873. }
  874. public class Recommendation
  875. {
  876. public string programID { get; set; }
  877. public string title120 { get; set; }
  878. }
  879. public class ProgramDetails
  880. {
  881. public string audience { get; set; }
  882. public string programID { get; set; }
  883. public List<Title> titles { get; set; }
  884. public EventDetails eventDetails { get; set; }
  885. public DescriptionsProgram descriptions { get; set; }
  886. public string originalAirDate { get; set; }
  887. public List<string> genres { get; set; }
  888. public string episodeTitle150 { get; set; }
  889. public List<MetadataPrograms> metadata { get; set; }
  890. public List<ContentRating> contentRating { get; set; }
  891. public List<Cast> cast { get; set; }
  892. public List<Crew> crew { get; set; }
  893. public string entityType { get; set; }
  894. public string showType { get; set; }
  895. public bool hasImageArtwork { get; set; }
  896. public string primaryImage { get; set; }
  897. public string thumbImage { get; set; }
  898. public string backdropImage { get; set; }
  899. public string bannerImage { get; set; }
  900. public string imageID { get; set; }
  901. public string md5 { get; set; }
  902. public List<string> contentAdvisory { get; set; }
  903. public Movie movie { get; set; }
  904. public List<Recommendation> recommendations { get; set; }
  905. }
  906. public class Caption
  907. {
  908. public string content { get; set; }
  909. public string lang { get; set; }
  910. }
  911. public class ImageData
  912. {
  913. public string width { get; set; }
  914. public string height { get; set; }
  915. public string uri { get; set; }
  916. public string size { get; set; }
  917. public string aspect { get; set; }
  918. public string category { get; set; }
  919. public string text { get; set; }
  920. public string primary { get; set; }
  921. public string tier { get; set; }
  922. public Caption caption { get; set; }
  923. }
  924. public class ShowImages
  925. {
  926. public string programID { get; set; }
  927. public List<ImageData> data { get; set; }
  928. }
  929. }
  930. }
  931. }