SchedulesDirect.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Common;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller.LiveTv;
  16. using MediaBrowser.Model.Cryptography;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.LiveTv;
  20. using MediaBrowser.Model.Serialization;
  21. using Microsoft.Extensions.Logging;
  22. namespace Emby.Server.Implementations.LiveTv.Listings
  23. {
  24. public class SchedulesDirect : IListingsProvider
  25. {
  26. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  27. private readonly ILogger<SchedulesDirect> _logger;
  28. private readonly IJsonSerializer _jsonSerializer;
  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 DateTime _lastErrorResponse;
  35. public SchedulesDirect(
  36. ILogger<SchedulesDirect> logger,
  37. IJsonSerializer jsonSerializer,
  38. IHttpClientFactory httpClientFactory,
  39. IApplicationHost appHost,
  40. ICryptoProvider cryptoProvider)
  41. {
  42. _logger = logger;
  43. _jsonSerializer = jsonSerializer;
  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.SerializeToString(requestList);
  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.DeserializeFromStreamAsync<List<ScheduleDirect.Day>>(responseStream).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.DeserializeFromStreamAsync<List<ScheduleDirect.ProgramDetails>>(innerResponseStream).ConfigureAwait(false);
  104. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  105. var programIdsWithImages =
  106. programDetails.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 (!string.IsNullOrWhiteSpace(image.height)
  149. && int.TryParse(image.height, out int value))
  150. {
  151. return value;
  152. }
  153. return 0;
  154. }
  155. private static string GetChannelNumber(ScheduleDirect.Map map)
  156. {
  157. var channelNumber = map.logicalChannelNumber;
  158. if (string.IsNullOrWhiteSpace(channelNumber))
  159. {
  160. channelNumber = map.channel;
  161. }
  162. if (string.IsNullOrWhiteSpace(channelNumber))
  163. {
  164. channelNumber = map.atscMajor + "." + map.atscMinor;
  165. }
  166. return channelNumber.TrimStart('0');
  167. }
  168. private static bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
  169. {
  170. return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase);
  171. }
  172. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  173. {
  174. var startAt = GetDate(programInfo.airDateTime);
  175. var endAt = startAt.AddSeconds(programInfo.duration);
  176. var audioType = ProgramAudio.Stereo;
  177. var programId = programInfo.programID ?? string.Empty;
  178. string newID = programId + "T" + startAt.Ticks + "C" + channelId;
  179. if (programInfo.audioProperties != null)
  180. {
  181. if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
  182. {
  183. audioType = ProgramAudio.Atmos;
  184. }
  185. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  186. {
  187. audioType = ProgramAudio.DolbyDigital;
  188. }
  189. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  190. {
  191. audioType = ProgramAudio.DolbyDigital;
  192. }
  193. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  194. {
  195. audioType = ProgramAudio.Stereo;
  196. }
  197. else
  198. {
  199. audioType = ProgramAudio.Mono;
  200. }
  201. }
  202. string episodeTitle = null;
  203. if (details.episodeTitle150 != null)
  204. {
  205. episodeTitle = details.episodeTitle150;
  206. }
  207. var info = new ProgramInfo
  208. {
  209. ChannelId = channelId,
  210. Id = newID,
  211. StartDate = startAt,
  212. EndDate = endAt,
  213. Name = details.titles[0].title120 ?? "Unknown",
  214. OfficialRating = null,
  215. CommunityRating = null,
  216. EpisodeTitle = episodeTitle,
  217. Audio = audioType,
  218. // IsNew = programInfo.@new ?? false,
  219. IsRepeat = programInfo.@new == null,
  220. IsSeries = string.Equals(details.entityType, "episode", StringComparison.OrdinalIgnoreCase),
  221. ImageUrl = details.primaryImage,
  222. ThumbImageUrl = details.thumbImage,
  223. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  224. IsSports = string.Equals(details.entityType, "sports", StringComparison.OrdinalIgnoreCase),
  225. IsMovie = IsMovie(details),
  226. Etag = programInfo.md5,
  227. IsLive = string.Equals(programInfo.liveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
  228. IsPremiere = programInfo.premiere || (programInfo.isPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
  229. };
  230. var showId = programId;
  231. if (!info.IsSeries)
  232. {
  233. // It's also a series if it starts with SH
  234. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  235. }
  236. // According to SchedulesDirect, these are generic, unidentified episodes
  237. // SH005316560000
  238. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  239. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  240. if (!hasUniqueShowId)
  241. {
  242. showId = newID;
  243. }
  244. info.ShowId = showId;
  245. if (programInfo.videoProperties != null)
  246. {
  247. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  248. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  249. }
  250. if (details.contentRating != null && details.contentRating.Count > 0)
  251. {
  252. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-", StringComparison.Ordinal)
  253. .Replace("--", "-", StringComparison.Ordinal);
  254. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  255. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  256. {
  257. info.OfficialRating = null;
  258. }
  259. }
  260. if (details.descriptions != null)
  261. {
  262. if (details.descriptions.description1000 != null && details.descriptions.description1000.Count > 0)
  263. {
  264. info.Overview = details.descriptions.description1000[0].description;
  265. }
  266. else if (details.descriptions.description100 != null && details.descriptions.description100.Count > 0)
  267. {
  268. info.Overview = details.descriptions.description100[0].description;
  269. }
  270. }
  271. if (info.IsSeries)
  272. {
  273. info.SeriesId = programId.Substring(0, 10);
  274. info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
  275. if (details.metadata != null)
  276. {
  277. foreach (var metadataProgram in details.metadata)
  278. {
  279. var gracenote = metadataProgram.Gracenote;
  280. if (gracenote != null)
  281. {
  282. info.SeasonNumber = gracenote.season;
  283. if (gracenote.episode > 0)
  284. {
  285. info.EpisodeNumber = gracenote.episode;
  286. }
  287. break;
  288. }
  289. }
  290. }
  291. }
  292. if (!string.IsNullOrWhiteSpace(details.originalAirDate))
  293. {
  294. info.OriginalAirDate = DateTime.Parse(details.originalAirDate, CultureInfo.InvariantCulture);
  295. info.ProductionYear = info.OriginalAirDate.Value.Year;
  296. }
  297. if (details.movie != null)
  298. {
  299. if (!string.IsNullOrEmpty(details.movie.year)
  300. && int.TryParse(details.movie.year, out int year))
  301. {
  302. info.ProductionYear = year;
  303. }
  304. }
  305. if (details.genres != null)
  306. {
  307. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  308. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  309. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  310. {
  311. info.IsKids = true;
  312. }
  313. }
  314. return info;
  315. }
  316. private static DateTime GetDate(string value)
  317. {
  318. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  319. if (date.Kind != DateTimeKind.Utc)
  320. {
  321. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  322. }
  323. return date;
  324. }
  325. private string GetProgramImage(string apiUrl, IEnumerable<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
  326. {
  327. var match = images
  328. .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
  329. .ThenByDescending(GetSizeOrder)
  330. .FirstOrDefault();
  331. if (match == null)
  332. {
  333. return null;
  334. }
  335. var uri = match.uri;
  336. if (string.IsNullOrWhiteSpace(uri))
  337. {
  338. return null;
  339. }
  340. else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  341. {
  342. return uri;
  343. }
  344. else
  345. {
  346. return apiUrl + "/image/" + uri;
  347. }
  348. }
  349. private static double GetAspectRatio(ScheduleDirect.ImageData i)
  350. {
  351. int width = 0;
  352. int height = 0;
  353. if (!string.IsNullOrWhiteSpace(i.width))
  354. {
  355. int.TryParse(i.width, out width);
  356. }
  357. if (!string.IsNullOrWhiteSpace(i.height))
  358. {
  359. int.TryParse(i.height, out height);
  360. }
  361. if (height == 0 || width == 0)
  362. {
  363. return 0;
  364. }
  365. double result = width;
  366. result /= height;
  367. return result;
  368. }
  369. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  370. ListingsProviderInfo info,
  371. IReadOnlyList<string> programIds,
  372. CancellationToken cancellationToken)
  373. {
  374. if (programIds.Count == 0)
  375. {
  376. return new List<ScheduleDirect.ShowImages>();
  377. }
  378. StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
  379. foreach (ReadOnlySpan<char> i in programIds)
  380. {
  381. str.Append('"')
  382. .Append(i.Slice(0, 10))
  383. .Append("\",");
  384. }
  385. // Remove last ,
  386. str.Length--;
  387. str.Append(']');
  388. using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
  389. {
  390. Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
  391. };
  392. try
  393. {
  394. using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
  395. await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  396. return await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.ShowImages>>(response).ConfigureAwait(false);
  397. }
  398. catch (Exception ex)
  399. {
  400. _logger.LogError(ex, "Error getting image info from schedules direct");
  401. return new List<ScheduleDirect.ShowImages>();
  402. }
  403. }
  404. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  405. {
  406. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  407. var lineups = new List<NameIdPair>();
  408. if (string.IsNullOrWhiteSpace(token))
  409. {
  410. return lineups;
  411. }
  412. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
  413. options.Headers.TryAddWithoutValidation("token", token);
  414. try
  415. {
  416. using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
  417. await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  418. var root = await _jsonSerializer.DeserializeFromStreamAsync<List<ScheduleDirect.Headends>>(response).ConfigureAwait(false);
  419. if (root != null)
  420. {
  421. foreach (ScheduleDirect.Headends headend in root)
  422. {
  423. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  424. {
  425. lineups.Add(new NameIdPair
  426. {
  427. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  428. Id = lineup.uri.Substring(18)
  429. });
  430. }
  431. }
  432. }
  433. else
  434. {
  435. _logger.LogInformation("No lineups available");
  436. }
  437. }
  438. catch (Exception ex)
  439. {
  440. _logger.LogError(ex, "Error getting headends");
  441. }
  442. return lineups;
  443. }
  444. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  445. {
  446. var username = info.Username;
  447. // Reset the token if there's no username
  448. if (string.IsNullOrWhiteSpace(username))
  449. {
  450. return null;
  451. }
  452. var password = info.Password;
  453. if (string.IsNullOrEmpty(password))
  454. {
  455. return null;
  456. }
  457. // Avoid hammering SD
  458. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  459. {
  460. return null;
  461. }
  462. if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
  463. {
  464. savedToken = new NameValuePair();
  465. _tokens.TryAdd(username, savedToken);
  466. }
  467. if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
  468. {
  469. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out long ticks))
  470. {
  471. // If it's under 24 hours old we can still use it
  472. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  473. {
  474. return savedToken.Name;
  475. }
  476. }
  477. }
  478. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  479. try
  480. {
  481. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  482. savedToken.Name = result;
  483. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  484. return result;
  485. }
  486. catch (HttpRequestException ex)
  487. {
  488. if (ex.StatusCode.HasValue)
  489. {
  490. if ((int)ex.StatusCode.Value == 400)
  491. {
  492. _tokens.Clear();
  493. _lastErrorResponse = DateTime.UtcNow;
  494. }
  495. }
  496. throw;
  497. }
  498. finally
  499. {
  500. _tokenSemaphore.Release();
  501. }
  502. }
  503. private async Task<HttpResponseMessage> Send(
  504. HttpRequestMessage options,
  505. bool enableRetry,
  506. ListingsProviderInfo providerInfo,
  507. CancellationToken cancellationToken,
  508. HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
  509. {
  510. try
  511. {
  512. return await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
  513. }
  514. catch (HttpRequestException ex)
  515. {
  516. _tokens.Clear();
  517. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  518. {
  519. enableRetry = false;
  520. }
  521. if (!enableRetry)
  522. {
  523. throw;
  524. }
  525. }
  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. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  542. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).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. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  584. using var response = httpResponse.Content;
  585. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(stream).ConfigureAwait(false);
  586. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  587. }
  588. catch (HttpRequestException ex)
  589. {
  590. // Apparently we're supposed to swallow this
  591. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  592. {
  593. return false;
  594. }
  595. throw;
  596. }
  597. }
  598. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  599. {
  600. if (validateLogin)
  601. {
  602. if (string.IsNullOrEmpty(info.Username))
  603. {
  604. throw new ArgumentException("Username is required");
  605. }
  606. if (string.IsNullOrEmpty(info.Password))
  607. {
  608. throw new ArgumentException("Password is required");
  609. }
  610. }
  611. if (validateListings)
  612. {
  613. if (string.IsNullOrEmpty(info.ListingsId))
  614. {
  615. throw new ArgumentException("Listings Id required");
  616. }
  617. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  618. if (!hasLineup)
  619. {
  620. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  621. }
  622. }
  623. }
  624. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  625. {
  626. return GetHeadends(info, country, location, CancellationToken.None);
  627. }
  628. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  629. {
  630. var listingsId = info.ListingsId;
  631. if (string.IsNullOrEmpty(listingsId))
  632. {
  633. throw new Exception("ListingsId required");
  634. }
  635. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  636. if (string.IsNullOrEmpty(token))
  637. {
  638. throw new Exception("token required");
  639. }
  640. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  641. options.Headers.TryAddWithoutValidation("token", token);
  642. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  643. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  644. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(stream).ConfigureAwait(false);
  645. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
  646. _logger.LogInformation("Mapping Stations to Channel");
  647. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  648. var map = root.map;
  649. int len = map.Count;
  650. var array = new List<ChannelInfo>(len);
  651. for (int i = 0; i < len; i++)
  652. {
  653. var channelNumber = GetChannelNumber(map[i]);
  654. var station = allStations.Find(item => string.Equals(item.stationID, map[i].stationID, StringComparison.OrdinalIgnoreCase));
  655. if (station == null)
  656. {
  657. station = new ScheduleDirect.Station
  658. {
  659. stationID = map[i].stationID
  660. };
  661. }
  662. var channelInfo = new ChannelInfo
  663. {
  664. Id = station.stationID,
  665. CallSign = station.callsign,
  666. Number = channelNumber,
  667. Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
  668. };
  669. if (station.logo != null)
  670. {
  671. channelInfo.ImageUrl = station.logo.URL;
  672. }
  673. array[i] = channelInfo;
  674. }
  675. return array;
  676. }
  677. private static string NormalizeName(string value)
  678. {
  679. return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
  680. }
  681. public class ScheduleDirect
  682. {
  683. public class Token
  684. {
  685. public int code { get; set; }
  686. public string message { get; set; }
  687. public string serverID { get; set; }
  688. public string token { get; set; }
  689. }
  690. public class Lineup
  691. {
  692. public string lineup { get; set; }
  693. public string name { get; set; }
  694. public string transport { get; set; }
  695. public string location { get; set; }
  696. public string uri { get; set; }
  697. }
  698. public class Lineups
  699. {
  700. public int code { get; set; }
  701. public string serverID { get; set; }
  702. public string datetime { get; set; }
  703. public List<Lineup> lineups { get; set; }
  704. }
  705. public class Headends
  706. {
  707. public string headend { get; set; }
  708. public string transport { get; set; }
  709. public string location { get; set; }
  710. public List<Lineup> lineups { get; set; }
  711. }
  712. public class Map
  713. {
  714. public string stationID { get; set; }
  715. public string channel { get; set; }
  716. public string logicalChannelNumber { get; set; }
  717. public int uhfVhf { get; set; }
  718. public int atscMajor { get; set; }
  719. public int atscMinor { get; set; }
  720. }
  721. public class Broadcaster
  722. {
  723. public string city { get; set; }
  724. public string state { get; set; }
  725. public string postalcode { get; set; }
  726. public string country { get; set; }
  727. }
  728. public class Logo
  729. {
  730. public string URL { get; set; }
  731. public int height { get; set; }
  732. public int width { get; set; }
  733. public string md5 { get; set; }
  734. }
  735. public class Station
  736. {
  737. public string stationID { get; set; }
  738. public string name { get; set; }
  739. public string callsign { get; set; }
  740. public List<string> broadcastLanguage { get; set; }
  741. public List<string> descriptionLanguage { get; set; }
  742. public Broadcaster broadcaster { get; set; }
  743. public string affiliate { get; set; }
  744. public Logo logo { get; set; }
  745. public bool? isCommercialFree { get; set; }
  746. }
  747. public class Metadata
  748. {
  749. public string lineup { get; set; }
  750. public string modified { get; set; }
  751. public string transport { get; set; }
  752. }
  753. public class Channel
  754. {
  755. public List<Map> map { get; set; }
  756. public List<Station> stations { get; set; }
  757. public Metadata metadata { get; set; }
  758. }
  759. public class RequestScheduleForChannel
  760. {
  761. public string stationID { get; set; }
  762. public List<string> date { get; set; }
  763. }
  764. public class Rating
  765. {
  766. public string body { get; set; }
  767. public string code { get; set; }
  768. }
  769. public class Multipart
  770. {
  771. public int partNumber { get; set; }
  772. public int totalParts { get; set; }
  773. }
  774. public class Program
  775. {
  776. public string programID { get; set; }
  777. public string airDateTime { get; set; }
  778. public int duration { get; set; }
  779. public string md5 { get; set; }
  780. public List<string> audioProperties { get; set; }
  781. public List<string> videoProperties { get; set; }
  782. public List<Rating> ratings { get; set; }
  783. public bool? @new { get; set; }
  784. public Multipart multipart { get; set; }
  785. public string liveTapeDelay { get; set; }
  786. public bool premiere { get; set; }
  787. public bool repeat { get; set; }
  788. public string isPremiereOrFinale { get; set; }
  789. }
  790. public class MetadataSchedule
  791. {
  792. public string modified { get; set; }
  793. public string md5 { get; set; }
  794. public string startDate { get; set; }
  795. public string endDate { get; set; }
  796. public int days { get; set; }
  797. }
  798. public class Day
  799. {
  800. public string stationID { get; set; }
  801. public List<Program> programs { get; set; }
  802. public MetadataSchedule metadata { get; set; }
  803. public Day()
  804. {
  805. programs = new List<Program>();
  806. }
  807. }
  808. public class Title
  809. {
  810. public string title120 { get; set; }
  811. }
  812. public class EventDetails
  813. {
  814. public string subType { get; set; }
  815. }
  816. public class Description100
  817. {
  818. public string descriptionLanguage { get; set; }
  819. public string description { get; set; }
  820. }
  821. public class Description1000
  822. {
  823. public string descriptionLanguage { get; set; }
  824. public string description { get; set; }
  825. }
  826. public class DescriptionsProgram
  827. {
  828. public List<Description100> description100 { get; set; }
  829. public List<Description1000> description1000 { get; set; }
  830. }
  831. public class Gracenote
  832. {
  833. public int season { get; set; }
  834. public int episode { get; set; }
  835. }
  836. public class MetadataPrograms
  837. {
  838. public Gracenote Gracenote { get; set; }
  839. }
  840. public class ContentRating
  841. {
  842. public string body { get; set; }
  843. public string code { get; set; }
  844. }
  845. public class Cast
  846. {
  847. public string billingOrder { get; set; }
  848. public string role { get; set; }
  849. public string nameId { get; set; }
  850. public string personId { get; set; }
  851. public string name { get; set; }
  852. public string characterName { get; set; }
  853. }
  854. public class Crew
  855. {
  856. public string billingOrder { get; set; }
  857. public string role { get; set; }
  858. public string nameId { get; set; }
  859. public string personId { get; set; }
  860. public string name { get; set; }
  861. }
  862. public class QualityRating
  863. {
  864. public string ratingsBody { get; set; }
  865. public string rating { get; set; }
  866. public string minRating { get; set; }
  867. public string maxRating { get; set; }
  868. public string increment { get; set; }
  869. }
  870. public class Movie
  871. {
  872. public string year { get; set; }
  873. public int duration { get; set; }
  874. public List<QualityRating> qualityRating { get; set; }
  875. }
  876. public class Recommendation
  877. {
  878. public string programID { get; set; }
  879. public string title120 { get; set; }
  880. }
  881. public class ProgramDetails
  882. {
  883. public string audience { get; set; }
  884. public string programID { get; set; }
  885. public List<Title> titles { get; set; }
  886. public EventDetails eventDetails { get; set; }
  887. public DescriptionsProgram descriptions { get; set; }
  888. public string originalAirDate { get; set; }
  889. public List<string> genres { get; set; }
  890. public string episodeTitle150 { get; set; }
  891. public List<MetadataPrograms> metadata { get; set; }
  892. public List<ContentRating> contentRating { get; set; }
  893. public List<Cast> cast { get; set; }
  894. public List<Crew> crew { get; set; }
  895. public string entityType { get; set; }
  896. public string showType { get; set; }
  897. public bool hasImageArtwork { get; set; }
  898. public string primaryImage { get; set; }
  899. public string thumbImage { get; set; }
  900. public string backdropImage { get; set; }
  901. public string bannerImage { get; set; }
  902. public string imageID { get; set; }
  903. public string md5 { get; set; }
  904. public List<string> contentAdvisory { get; set; }
  905. public Movie movie { get; set; }
  906. public List<Recommendation> recommendations { get; set; }
  907. }
  908. public class Caption
  909. {
  910. public string content { get; set; }
  911. public string lang { get; set; }
  912. }
  913. public class ImageData
  914. {
  915. public string width { get; set; }
  916. public string height { get; set; }
  917. public string uri { get; set; }
  918. public string size { get; set; }
  919. public string aspect { get; set; }
  920. public string category { get; set; }
  921. public string text { get; set; }
  922. public string primary { get; set; }
  923. public string tier { get; set; }
  924. public Caption caption { get; set; }
  925. }
  926. public class ShowImages
  927. {
  928. public string programID { get; set; }
  929. public List<ImageData> data { get; set; }
  930. }
  931. }
  932. }
  933. }