SchedulesDirect.cs 46 KB

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