SchedulesDirect.cs 45 KB

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