SchedulesDirect.cs 45 KB

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