SchedulesDirect.cs 47 KB

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