SchedulesDirect.cs 43 KB

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