SchedulesDirect.cs 45 KB

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