SchedulesDirect.cs 45 KB

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