SchedulesDirect.cs 43 KB

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