SchedulesDirect.cs 45 KB

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