SchedulesDirect.cs 43 KB

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