SchedulesDirect.cs 44 KB

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