SchedulesDirect.cs 45 KB

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