SchedulesDirect.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  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. // TODO: remove ToLower when Convert.ToHexString supports lowercase
  540. // Schedules Direct requires the hex to be lowercase
  541. string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
  542. options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
  543. using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  544. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  545. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Token>(stream).ConfigureAwait(false);
  546. if (root.message == "OK")
  547. {
  548. _logger.LogInformation("Authenticated with Schedules Direct token: " + root.token);
  549. return root.token;
  550. }
  551. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  552. }
  553. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  554. {
  555. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  556. if (string.IsNullOrEmpty(token))
  557. {
  558. throw new ArgumentException("Authentication required.");
  559. }
  560. if (string.IsNullOrEmpty(info.ListingsId))
  561. {
  562. throw new ArgumentException("Listings Id required");
  563. }
  564. _logger.LogInformation("Adding new LineUp ");
  565. using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
  566. options.Headers.TryAddWithoutValidation("token", token);
  567. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  568. }
  569. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  570. {
  571. if (string.IsNullOrEmpty(info.ListingsId))
  572. {
  573. throw new ArgumentException("Listings Id required");
  574. }
  575. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  576. if (string.IsNullOrEmpty(token))
  577. {
  578. throw new Exception("token required");
  579. }
  580. _logger.LogInformation("Headends on account ");
  581. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
  582. options.Headers.TryAddWithoutValidation("token", token);
  583. try
  584. {
  585. using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
  586. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  587. using var response = httpResponse.Content;
  588. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Lineups>(stream).ConfigureAwait(false);
  589. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  590. }
  591. catch (HttpRequestException ex)
  592. {
  593. // Apparently we're supposed to swallow this
  594. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  595. {
  596. return false;
  597. }
  598. throw;
  599. }
  600. }
  601. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  602. {
  603. if (validateLogin)
  604. {
  605. if (string.IsNullOrEmpty(info.Username))
  606. {
  607. throw new ArgumentException("Username is required");
  608. }
  609. if (string.IsNullOrEmpty(info.Password))
  610. {
  611. throw new ArgumentException("Password is required");
  612. }
  613. }
  614. if (validateListings)
  615. {
  616. if (string.IsNullOrEmpty(info.ListingsId))
  617. {
  618. throw new ArgumentException("Listings Id required");
  619. }
  620. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  621. if (!hasLineup)
  622. {
  623. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  624. }
  625. }
  626. }
  627. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  628. {
  629. return GetHeadends(info, country, location, CancellationToken.None);
  630. }
  631. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  632. {
  633. var listingsId = info.ListingsId;
  634. if (string.IsNullOrEmpty(listingsId))
  635. {
  636. throw new Exception("ListingsId required");
  637. }
  638. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  639. if (string.IsNullOrEmpty(token))
  640. {
  641. throw new Exception("token required");
  642. }
  643. using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
  644. options.Headers.TryAddWithoutValidation("token", token);
  645. var list = new List<ChannelInfo>();
  646. using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
  647. await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  648. var root = await _jsonSerializer.DeserializeFromStreamAsync<ScheduleDirect.Channel>(stream).ConfigureAwait(false);
  649. _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.map.Count);
  650. _logger.LogInformation("Mapping Stations to Channel");
  651. var allStations = root.stations ?? Enumerable.Empty<ScheduleDirect.Station>();
  652. foreach (ScheduleDirect.Map map in root.map)
  653. {
  654. var channelNumber = GetChannelNumber(map);
  655. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  656. if (station == null)
  657. {
  658. station = new ScheduleDirect.Station { stationID = map.stationID };
  659. }
  660. var channelInfo = new ChannelInfo
  661. {
  662. Id = station.stationID,
  663. CallSign = station.callsign,
  664. Number = channelNumber,
  665. Name = string.IsNullOrWhiteSpace(station.name) ? channelNumber : station.name
  666. };
  667. if (station.logo != null)
  668. {
  669. channelInfo.ImageUrl = station.logo.URL;
  670. }
  671. list.Add(channelInfo);
  672. }
  673. return list;
  674. }
  675. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  676. {
  677. if (!string.IsNullOrWhiteSpace(channelName))
  678. {
  679. channelName = NormalizeName(channelName);
  680. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  681. if (result != null)
  682. {
  683. return result;
  684. }
  685. }
  686. if (!string.IsNullOrWhiteSpace(channelNumber))
  687. {
  688. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  689. }
  690. return null;
  691. }
  692. private static string NormalizeName(string value)
  693. {
  694. return value.Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
  695. }
  696. public class ScheduleDirect
  697. {
  698. public class Token
  699. {
  700. public int code { get; set; }
  701. public string message { get; set; }
  702. public string serverID { get; set; }
  703. public string token { get; set; }
  704. }
  705. public class Lineup
  706. {
  707. public string lineup { get; set; }
  708. public string name { get; set; }
  709. public string transport { get; set; }
  710. public string location { get; set; }
  711. public string uri { get; set; }
  712. }
  713. public class Lineups
  714. {
  715. public int code { get; set; }
  716. public string serverID { get; set; }
  717. public string datetime { get; set; }
  718. public List<Lineup> lineups { get; set; }
  719. }
  720. public class Headends
  721. {
  722. public string headend { get; set; }
  723. public string transport { get; set; }
  724. public string location { get; set; }
  725. public List<Lineup> lineups { get; set; }
  726. }
  727. public class Map
  728. {
  729. public string stationID { get; set; }
  730. public string channel { get; set; }
  731. public string logicalChannelNumber { get; set; }
  732. public int uhfVhf { get; set; }
  733. public int atscMajor { get; set; }
  734. public int atscMinor { get; set; }
  735. }
  736. public class Broadcaster
  737. {
  738. public string city { get; set; }
  739. public string state { get; set; }
  740. public string postalcode { get; set; }
  741. public string country { get; set; }
  742. }
  743. public class Logo
  744. {
  745. public string URL { get; set; }
  746. public int height { get; set; }
  747. public int width { get; set; }
  748. public string md5 { get; set; }
  749. }
  750. public class Station
  751. {
  752. public string stationID { get; set; }
  753. public string name { get; set; }
  754. public string callsign { get; set; }
  755. public List<string> broadcastLanguage { get; set; }
  756. public List<string> descriptionLanguage { get; set; }
  757. public Broadcaster broadcaster { get; set; }
  758. public string affiliate { get; set; }
  759. public Logo logo { get; set; }
  760. public bool? isCommercialFree { get; set; }
  761. }
  762. public class Metadata
  763. {
  764. public string lineup { get; set; }
  765. public string modified { get; set; }
  766. public string transport { get; set; }
  767. }
  768. public class Channel
  769. {
  770. public List<Map> map { get; set; }
  771. public List<Station> stations { get; set; }
  772. public Metadata metadata { get; set; }
  773. }
  774. public class RequestScheduleForChannel
  775. {
  776. public string stationID { get; set; }
  777. public List<string> date { get; set; }
  778. }
  779. public class Rating
  780. {
  781. public string body { get; set; }
  782. public string code { get; set; }
  783. }
  784. public class Multipart
  785. {
  786. public int partNumber { get; set; }
  787. public int totalParts { get; set; }
  788. }
  789. public class Program
  790. {
  791. public string programID { get; set; }
  792. public string airDateTime { get; set; }
  793. public int duration { get; set; }
  794. public string md5 { get; set; }
  795. public List<string> audioProperties { get; set; }
  796. public List<string> videoProperties { get; set; }
  797. public List<Rating> ratings { get; set; }
  798. public bool? @new { get; set; }
  799. public Multipart multipart { get; set; }
  800. public string liveTapeDelay { get; set; }
  801. public bool premiere { get; set; }
  802. public bool repeat { get; set; }
  803. public string isPremiereOrFinale { get; set; }
  804. }
  805. public class MetadataSchedule
  806. {
  807. public string modified { get; set; }
  808. public string md5 { get; set; }
  809. public string startDate { get; set; }
  810. public string endDate { get; set; }
  811. public int days { get; set; }
  812. }
  813. public class Day
  814. {
  815. public string stationID { get; set; }
  816. public List<Program> programs { get; set; }
  817. public MetadataSchedule metadata { get; set; }
  818. public Day()
  819. {
  820. programs = new List<Program>();
  821. }
  822. }
  823. //
  824. public class Title
  825. {
  826. public string title120 { get; set; }
  827. }
  828. public class EventDetails
  829. {
  830. public string subType { get; set; }
  831. }
  832. public class Description100
  833. {
  834. public string descriptionLanguage { get; set; }
  835. public string description { get; set; }
  836. }
  837. public class Description1000
  838. {
  839. public string descriptionLanguage { get; set; }
  840. public string description { get; set; }
  841. }
  842. public class DescriptionsProgram
  843. {
  844. public List<Description100> description100 { get; set; }
  845. public List<Description1000> description1000 { get; set; }
  846. }
  847. public class Gracenote
  848. {
  849. public int season { get; set; }
  850. public int episode { get; set; }
  851. }
  852. public class MetadataPrograms
  853. {
  854. public Gracenote Gracenote { get; set; }
  855. }
  856. public class ContentRating
  857. {
  858. public string body { get; set; }
  859. public string code { get; set; }
  860. }
  861. public class Cast
  862. {
  863. public string billingOrder { get; set; }
  864. public string role { get; set; }
  865. public string nameId { get; set; }
  866. public string personId { get; set; }
  867. public string name { get; set; }
  868. public string characterName { get; set; }
  869. }
  870. public class Crew
  871. {
  872. public string billingOrder { get; set; }
  873. public string role { get; set; }
  874. public string nameId { get; set; }
  875. public string personId { get; set; }
  876. public string name { get; set; }
  877. }
  878. public class QualityRating
  879. {
  880. public string ratingsBody { get; set; }
  881. public string rating { get; set; }
  882. public string minRating { get; set; }
  883. public string maxRating { get; set; }
  884. public string increment { get; set; }
  885. }
  886. public class Movie
  887. {
  888. public string year { get; set; }
  889. public int duration { get; set; }
  890. public List<QualityRating> qualityRating { get; set; }
  891. }
  892. public class Recommendation
  893. {
  894. public string programID { get; set; }
  895. public string title120 { get; set; }
  896. }
  897. public class ProgramDetails
  898. {
  899. public string audience { get; set; }
  900. public string programID { get; set; }
  901. public List<Title> titles { get; set; }
  902. public EventDetails eventDetails { get; set; }
  903. public DescriptionsProgram descriptions { get; set; }
  904. public string originalAirDate { get; set; }
  905. public List<string> genres { get; set; }
  906. public string episodeTitle150 { get; set; }
  907. public List<MetadataPrograms> metadata { get; set; }
  908. public List<ContentRating> contentRating { get; set; }
  909. public List<Cast> cast { get; set; }
  910. public List<Crew> crew { get; set; }
  911. public string entityType { get; set; }
  912. public string showType { get; set; }
  913. public bool hasImageArtwork { get; set; }
  914. public string primaryImage { get; set; }
  915. public string thumbImage { get; set; }
  916. public string backdropImage { get; set; }
  917. public string bannerImage { get; set; }
  918. public string imageID { get; set; }
  919. public string md5 { get; set; }
  920. public List<string> contentAdvisory { get; set; }
  921. public Movie movie { get; set; }
  922. public List<Recommendation> recommendations { get; set; }
  923. }
  924. public class Caption
  925. {
  926. public string content { get; set; }
  927. public string lang { get; set; }
  928. }
  929. public class ImageData
  930. {
  931. public string width { get; set; }
  932. public string height { get; set; }
  933. public string uri { get; set; }
  934. public string size { get; set; }
  935. public string aspect { get; set; }
  936. public string category { get; set; }
  937. public string text { get; set; }
  938. public string primary { get; set; }
  939. public string tier { get; set; }
  940. public Caption caption { get; set; }
  941. }
  942. public class ShowImages
  943. {
  944. public string programID { get; set; }
  945. public List<ImageData> data { get; set; }
  946. }
  947. }
  948. }
  949. }