SchedulesDirect.cs 45 KB

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