SchedulesDirect.cs 46 KB

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