SchedulesDirect.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. namespace MediaBrowser.Server.Implementations.LiveTv.Listings
  19. {
  20. public class SchedulesDirect : IListingsProvider
  21. {
  22. private readonly ILogger _logger;
  23. private readonly IJsonSerializer _jsonSerializer;
  24. private readonly IHttpClient _httpClient;
  25. private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
  26. private readonly IApplicationHost _appHost;
  27. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  28. private readonly ConcurrentDictionary<string, ScheduleDirect.Station> _channelPair =
  29. new ConcurrentDictionary<string, ScheduleDirect.Station>();
  30. public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
  31. {
  32. _logger = logger;
  33. _jsonSerializer = jsonSerializer;
  34. _httpClient = httpClient;
  35. _appHost = appHost;
  36. }
  37. private string UserAgent
  38. {
  39. get { return "Emby/" + _appHost.ApplicationVersion; }
  40. }
  41. private List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  42. {
  43. List<string> dates = new List<string>();
  44. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min();
  45. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max();
  46. while (start.DayOfYear <= end.Day)
  47. {
  48. dates.Add(start.ToString("yyyy-MM-dd"));
  49. start = start.AddDays(1);
  50. }
  51. return dates;
  52. }
  53. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelNumber, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  54. {
  55. List<ProgramInfo> programsInfo = new List<ProgramInfo>();
  56. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  57. if (string.IsNullOrWhiteSpace(token))
  58. {
  59. return programsInfo;
  60. }
  61. if (string.IsNullOrWhiteSpace(info.ListingsId))
  62. {
  63. return programsInfo;
  64. }
  65. var httpOptions = new HttpRequestOptions()
  66. {
  67. Url = ApiUrl + "/schedules",
  68. UserAgent = UserAgent,
  69. CancellationToken = cancellationToken,
  70. // The data can be large so give it some extra time
  71. TimeoutMs = 60000
  72. };
  73. httpOptions.RequestHeaders["token"] = token;
  74. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  75. ScheduleDirect.Station station = null;
  76. if (!_channelPair.TryGetValue(channelNumber, out station))
  77. {
  78. return programsInfo;
  79. }
  80. string stationID = station.stationID;
  81. _logger.Info("Channel Station ID is: " + stationID);
  82. List<ScheduleDirect.RequestScheduleForChannel> requestList =
  83. new List<ScheduleDirect.RequestScheduleForChannel>()
  84. {
  85. new ScheduleDirect.RequestScheduleForChannel()
  86. {
  87. stationID = stationID,
  88. date = dates
  89. }
  90. };
  91. var requestString = _jsonSerializer.SerializeToString(requestList);
  92. _logger.Debug("Request string for schedules is: " + requestString);
  93. httpOptions.RequestContent = requestString;
  94. using (var response = await _httpClient.Post(httpOptions))
  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 " + channelNumber + " ScheduleDirect");
  100. httpOptions = new HttpRequestOptions()
  101. {
  102. Url = ApiUrl + "/programs",
  103. UserAgent = UserAgent,
  104. CancellationToken = cancellationToken
  105. };
  106. httpOptions.RequestHeaders["token"] = token;
  107. List<string> programsID = new List<string>();
  108. programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList();
  109. var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]";
  110. httpOptions.RequestContent = requestBody;
  111. using (var innerResponse = await _httpClient.Post(httpOptions))
  112. {
  113. StreamReader innerReader = new StreamReader(innerResponse.Content);
  114. responseString = innerReader.ReadToEnd();
  115. var programDetails =
  116. _jsonSerializer.DeserializeFromString<List<ScheduleDirect.ProgramDetails>>(
  117. responseString);
  118. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  119. var images = await GetImageForPrograms(programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID).ToList(), cancellationToken);
  120. var schedules = dailySchedules.SelectMany(d => d.programs);
  121. foreach (ScheduleDirect.Program schedule in schedules)
  122. {
  123. //_logger.Debug("Proccesing Schedule for statio ID " + stationID +
  124. // " which corresponds to channel " + channelNumber + " and program id " +
  125. // schedule.programID + " which says it has images? " +
  126. // programDict[schedule.programID].hasImageArtwork);
  127. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  128. if (imageIndex > -1)
  129. {
  130. programDict[schedule.programID].images = GetProgramLogo(ApiUrl, images[imageIndex]);
  131. }
  132. programsInfo.Add(GetProgram(channelNumber, schedule, programDict[schedule.programID]));
  133. }
  134. _logger.Info("Finished with EPGData");
  135. }
  136. }
  137. return programsInfo;
  138. }
  139. public async Task AddMetadata(ListingsProviderInfo info, List<ChannelInfo> channels,
  140. CancellationToken cancellationToken)
  141. {
  142. if (string.IsNullOrWhiteSpace(info.ListingsId))
  143. {
  144. throw new Exception("ListingsId required");
  145. }
  146. var token = await GetToken(info, cancellationToken);
  147. if (string.IsNullOrWhiteSpace(token))
  148. {
  149. throw new Exception("token required");
  150. }
  151. _channelPair.Clear();
  152. var httpOptions = new HttpRequestOptions()
  153. {
  154. Url = ApiUrl + "/lineups/" + info.ListingsId,
  155. UserAgent = UserAgent,
  156. CancellationToken = cancellationToken
  157. };
  158. httpOptions.RequestHeaders["token"] = token;
  159. using (var response = await _httpClient.Get(httpOptions))
  160. {
  161. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Channel>(response);
  162. _logger.Info("Found " + root.map.Count() + " channels on the lineup on ScheduleDirect");
  163. _logger.Info("Mapping Stations to Channel");
  164. foreach (ScheduleDirect.Map map in root.map)
  165. {
  166. var channel = (map.channel ?? (map.atscMajor + "." + map.atscMinor)).TrimStart('0');
  167. _logger.Debug("Found channel: " + channel + " in Schedules Direct");
  168. var schChannel = root.stations.FirstOrDefault(item => item.stationID == map.stationID);
  169. if (!_channelPair.ContainsKey(channel) && channel != "0.0" && schChannel != null)
  170. {
  171. _channelPair.TryAdd(channel, schChannel);
  172. }
  173. }
  174. _logger.Info("Added " + _channelPair.Count() + " channels to the dictionary");
  175. foreach (ChannelInfo channel in channels)
  176. {
  177. // Helper.logger.Info("Modifyin channel " + channel.Number);
  178. if (_channelPair.ContainsKey(channel.Number))
  179. {
  180. string channelName;
  181. if (_channelPair[channel.Number].logo != null)
  182. {
  183. channel.ImageUrl = _channelPair[channel.Number].logo.URL;
  184. channel.HasImage = true;
  185. }
  186. if (_channelPair[channel.Number].affiliate != null)
  187. {
  188. channelName = _channelPair[channel.Number].affiliate;
  189. }
  190. else
  191. {
  192. channelName = _channelPair[channel.Number].name;
  193. }
  194. channel.Name = channelName;
  195. }
  196. else
  197. {
  198. _logger.Info("Schedules Direct doesnt have data for channel: " + channel.Number + " " +
  199. channel.Name);
  200. }
  201. }
  202. }
  203. }
  204. private ProgramInfo GetProgram(string channel, ScheduleDirect.Program programInfo,
  205. ScheduleDirect.ProgramDetails details)
  206. {
  207. //_logger.Debug("Show type is: " + (details.showType ?? "No ShowType"));
  208. DateTime startAt = DateTime.ParseExact(programInfo.airDateTime, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'",
  209. CultureInfo.InvariantCulture);
  210. DateTime endAt = startAt.AddSeconds(programInfo.duration);
  211. ProgramAudio audioType = ProgramAudio.Stereo;
  212. bool repeat = (programInfo.@new == null);
  213. string newID = programInfo.programID + "T" + startAt.Ticks + "C" + channel;
  214. if (programInfo.audioProperties != null)
  215. {
  216. if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  217. {
  218. audioType = ProgramAudio.DolbyDigital;
  219. }
  220. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  221. {
  222. audioType = ProgramAudio.DolbyDigital;
  223. }
  224. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  225. {
  226. audioType = ProgramAudio.Stereo;
  227. }
  228. else
  229. {
  230. audioType = ProgramAudio.Mono;
  231. }
  232. }
  233. string episodeTitle = null;
  234. if (details.episodeTitle150 != null)
  235. {
  236. episodeTitle = details.episodeTitle150;
  237. }
  238. string imageUrl = null;
  239. if (details.hasImageArtwork)
  240. {
  241. imageUrl = details.images;
  242. }
  243. var showType = details.showType ?? string.Empty;
  244. var info = new ProgramInfo
  245. {
  246. ChannelId = channel,
  247. Id = newID,
  248. StartDate = startAt,
  249. EndDate = endAt,
  250. Name = details.titles[0].title120 ?? "Unkown",
  251. OfficialRating = null,
  252. CommunityRating = null,
  253. EpisodeTitle = episodeTitle,
  254. Audio = audioType,
  255. IsRepeat = repeat,
  256. IsSeries = showType.IndexOf("series", StringComparison.OrdinalIgnoreCase) != -1,
  257. ImageUrl = imageUrl,
  258. HasImage = details.hasImageArtwork,
  259. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  260. IsSports = showType.IndexOf("sports", StringComparison.OrdinalIgnoreCase) != -1,
  261. IsMovie = showType.IndexOf("movie", StringComparison.OrdinalIgnoreCase) != -1 || showType.IndexOf("film", StringComparison.OrdinalIgnoreCase) != -1,
  262. ShowId = programInfo.programID,
  263. Etag = programInfo.md5
  264. };
  265. if (programInfo.videoProperties != null)
  266. {
  267. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  268. }
  269. if (details.contentRating != null && details.contentRating.Count > 0)
  270. {
  271. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
  272. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  273. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  274. {
  275. info.OfficialRating = null;
  276. }
  277. }
  278. if (details.descriptions != null)
  279. {
  280. if (details.descriptions.description1000 != null)
  281. {
  282. info.Overview = details.descriptions.description1000[0].description;
  283. }
  284. else if (details.descriptions.description100 != null)
  285. {
  286. info.ShortOverview = details.descriptions.description100[0].description;
  287. }
  288. }
  289. if (info.IsSeries)
  290. {
  291. info.SeriesId = programInfo.programID.Substring(0, 10);
  292. if (details.metadata != null)
  293. {
  294. var gracenote = details.metadata.Find(x => x.Gracenote != null).Gracenote;
  295. info.SeasonNumber = gracenote.season;
  296. info.EpisodeNumber = gracenote.episode;
  297. }
  298. }
  299. if (!string.IsNullOrWhiteSpace(details.originalAirDate))
  300. {
  301. info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
  302. }
  303. if (details.genres != null)
  304. {
  305. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  306. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  307. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  308. {
  309. info.IsKids = true;
  310. }
  311. }
  312. return info;
  313. }
  314. private string GetProgramLogo(string apiUrl, ScheduleDirect.ShowImages images)
  315. {
  316. string url = "";
  317. if (images.data != null)
  318. {
  319. var smallImages = images.data.Where(i => i.size == "Sm").ToList();
  320. if (smallImages.Any())
  321. {
  322. images.data = smallImages;
  323. }
  324. var logoIndex = images.data.FindIndex(i => i.category == "Logo");
  325. if (logoIndex == -1)
  326. {
  327. logoIndex = 0;
  328. }
  329. if (images.data[logoIndex].uri.Contains("http"))
  330. {
  331. url = images.data[logoIndex].uri;
  332. }
  333. else
  334. {
  335. url = apiUrl + "/image/" + images.data[logoIndex].uri;
  336. }
  337. //_logger.Debug("URL for image is : " + url);
  338. }
  339. return url;
  340. }
  341. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(List<string> programIds,
  342. CancellationToken cancellationToken)
  343. {
  344. var imageIdString = "[";
  345. programIds.ForEach(i =>
  346. {
  347. if (!imageIdString.Contains(i.Substring(0, 10)))
  348. {
  349. imageIdString += "\"" + i.Substring(0, 10) + "\",";
  350. }
  351. ;
  352. });
  353. imageIdString = imageIdString.TrimEnd(',') + "]";
  354. var httpOptions = new HttpRequestOptions()
  355. {
  356. Url = ApiUrl + "/metadata/programs",
  357. UserAgent = UserAgent,
  358. CancellationToken = cancellationToken,
  359. RequestContent = imageIdString
  360. };
  361. List<ScheduleDirect.ShowImages> images;
  362. using (var innerResponse2 = await _httpClient.Post(httpOptions))
  363. {
  364. images = _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.ShowImages>>(
  365. innerResponse2.Content);
  366. }
  367. return images;
  368. }
  369. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  370. {
  371. var token = await GetToken(info, cancellationToken);
  372. var lineups = new List<NameIdPair>();
  373. if (string.IsNullOrWhiteSpace(token))
  374. {
  375. return lineups;
  376. }
  377. var options = new HttpRequestOptions()
  378. {
  379. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  380. UserAgent = UserAgent,
  381. CancellationToken = cancellationToken
  382. };
  383. options.RequestHeaders["token"] = token;
  384. try
  385. {
  386. using (Stream responce = await _httpClient.Get(options).ConfigureAwait(false))
  387. {
  388. var root = _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.Headends>>(responce);
  389. if (root != null)
  390. {
  391. foreach (ScheduleDirect.Headends headend in root)
  392. {
  393. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  394. {
  395. lineups.Add(new NameIdPair
  396. {
  397. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  398. Id = lineup.uri.Substring(18)
  399. });
  400. }
  401. }
  402. }
  403. else
  404. {
  405. _logger.Info("No lineups available");
  406. }
  407. }
  408. }
  409. catch (Exception ex)
  410. {
  411. _logger.Error("Error getting headends", ex);
  412. }
  413. return lineups;
  414. }
  415. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  416. private DateTime _lastErrorResponse;
  417. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  418. {
  419. var username = info.Username;
  420. // Reset the token if there's no username
  421. if (string.IsNullOrWhiteSpace(username))
  422. {
  423. return null;
  424. }
  425. var password = info.Password;
  426. if (string.IsNullOrWhiteSpace(password))
  427. {
  428. return null;
  429. }
  430. // Avoid hammering SD
  431. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  432. {
  433. return null;
  434. }
  435. NameValuePair savedToken = null;
  436. if (!_tokens.TryGetValue(username, out savedToken))
  437. {
  438. savedToken = new NameValuePair();
  439. _tokens.TryAdd(username, savedToken);
  440. }
  441. if (!string.IsNullOrWhiteSpace(savedToken.Name) && !string.IsNullOrWhiteSpace(savedToken.Value))
  442. {
  443. long ticks;
  444. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
  445. {
  446. // If it's under 24 hours old we can still use it
  447. if ((DateTime.UtcNow.Ticks - ticks) < TimeSpan.FromHours(24).Ticks)
  448. {
  449. return savedToken.Name;
  450. }
  451. }
  452. }
  453. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  454. try
  455. {
  456. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  457. savedToken.Name = result;
  458. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  459. return result;
  460. }
  461. catch (HttpException ex)
  462. {
  463. if (ex.StatusCode.HasValue)
  464. {
  465. if ((int)ex.StatusCode.Value == 400)
  466. {
  467. _tokens.Clear();
  468. _lastErrorResponse = DateTime.UtcNow;
  469. }
  470. }
  471. throw;
  472. }
  473. finally
  474. {
  475. _tokenSemaphore.Release();
  476. }
  477. }
  478. private async Task<string> GetTokenInternal(string username, string password,
  479. CancellationToken cancellationToken)
  480. {
  481. var httpOptions = new HttpRequestOptions()
  482. {
  483. Url = ApiUrl + "/token",
  484. UserAgent = UserAgent,
  485. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  486. CancellationToken = cancellationToken
  487. };
  488. //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  489. // httpOptions.RequestContent);
  490. using (var responce = await _httpClient.Post(httpOptions))
  491. {
  492. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Token>(responce.Content);
  493. if (root.message == "OK")
  494. {
  495. _logger.Info("Authenticated with Schedules Direct token: " + root.token);
  496. return root.token;
  497. }
  498. throw new ApplicationException("Could not authenticate with Schedules Direct Error: " + root.message);
  499. }
  500. }
  501. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  502. {
  503. var token = await GetToken(info, cancellationToken);
  504. if (string.IsNullOrWhiteSpace(token))
  505. {
  506. throw new ArgumentException("Authentication required.");
  507. }
  508. if (string.IsNullOrWhiteSpace(info.ListingsId))
  509. {
  510. throw new ArgumentException("Listings Id required");
  511. }
  512. _logger.Info("Adding new LineUp ");
  513. var httpOptions = new HttpRequestOptions()
  514. {
  515. Url = ApiUrl + "/lineups/" + info.ListingsId,
  516. UserAgent = UserAgent,
  517. CancellationToken = cancellationToken
  518. };
  519. httpOptions.RequestHeaders["token"] = token;
  520. using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
  521. {
  522. }
  523. }
  524. public string Name
  525. {
  526. get { return "Schedules Direct"; }
  527. }
  528. public string Type
  529. {
  530. get { return "SchedulesDirect"; }
  531. }
  532. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  533. {
  534. if (string.IsNullOrWhiteSpace(info.ListingsId))
  535. {
  536. throw new ArgumentException("Listings Id required");
  537. }
  538. var token = await GetToken(info, cancellationToken);
  539. if (string.IsNullOrWhiteSpace(token))
  540. {
  541. throw new Exception("token required");
  542. }
  543. _logger.Info("Headends on account ");
  544. var options = new HttpRequestOptions()
  545. {
  546. Url = ApiUrl + "/lineups",
  547. UserAgent = UserAgent,
  548. CancellationToken = cancellationToken
  549. };
  550. options.RequestHeaders["token"] = token;
  551. try
  552. {
  553. using (var response = await _httpClient.Get(options).ConfigureAwait(false))
  554. {
  555. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Lineups>(response);
  556. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  557. }
  558. }
  559. catch (HttpException ex)
  560. {
  561. // Apparently we're supposed to swallow this
  562. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  563. {
  564. return false;
  565. }
  566. throw;
  567. }
  568. }
  569. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  570. {
  571. if (validateLogin)
  572. {
  573. if (string.IsNullOrWhiteSpace(info.Username))
  574. {
  575. throw new ArgumentException("Username is required");
  576. }
  577. if (string.IsNullOrWhiteSpace(info.Password))
  578. {
  579. throw new ArgumentException("Password is required");
  580. }
  581. }
  582. if (validateListings)
  583. {
  584. if (string.IsNullOrWhiteSpace(info.ListingsId))
  585. {
  586. throw new ArgumentException("Listings Id required");
  587. }
  588. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  589. if (!hasLineup)
  590. {
  591. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  592. }
  593. }
  594. }
  595. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  596. {
  597. return GetHeadends(info, country, location, CancellationToken.None);
  598. }
  599. public class ScheduleDirect
  600. {
  601. public class Token
  602. {
  603. public int code { get; set; }
  604. public string message { get; set; }
  605. public string serverID { get; set; }
  606. public string token { get; set; }
  607. }
  608. public class Lineup
  609. {
  610. public string lineup { get; set; }
  611. public string name { get; set; }
  612. public string transport { get; set; }
  613. public string location { get; set; }
  614. public string uri { get; set; }
  615. }
  616. public class Lineups
  617. {
  618. public int code { get; set; }
  619. public string serverID { get; set; }
  620. public string datetime { get; set; }
  621. public List<Lineup> lineups { get; set; }
  622. }
  623. public class Headends
  624. {
  625. public string headend { get; set; }
  626. public string transport { get; set; }
  627. public string location { get; set; }
  628. public List<Lineup> lineups { get; set; }
  629. }
  630. public class Map
  631. {
  632. public string stationID { get; set; }
  633. public string channel { get; set; }
  634. public int uhfVhf { get; set; }
  635. public int atscMajor { get; set; }
  636. public int atscMinor { get; set; }
  637. }
  638. public class Broadcaster
  639. {
  640. public string city { get; set; }
  641. public string state { get; set; }
  642. public string postalcode { get; set; }
  643. public string country { get; set; }
  644. }
  645. public class Logo
  646. {
  647. public string URL { get; set; }
  648. public int height { get; set; }
  649. public int width { get; set; }
  650. public string md5 { get; set; }
  651. }
  652. public class Station
  653. {
  654. public string stationID { get; set; }
  655. public string name { get; set; }
  656. public string callsign { get; set; }
  657. public List<string> broadcastLanguage { get; set; }
  658. public List<string> descriptionLanguage { get; set; }
  659. public Broadcaster broadcaster { get; set; }
  660. public string affiliate { get; set; }
  661. public Logo logo { get; set; }
  662. public bool? isCommercialFree { get; set; }
  663. }
  664. public class Metadata
  665. {
  666. public string lineup { get; set; }
  667. public string modified { get; set; }
  668. public string transport { get; set; }
  669. }
  670. public class Channel
  671. {
  672. public List<Map> map { get; set; }
  673. public List<Station> stations { get; set; }
  674. public Metadata metadata { get; set; }
  675. }
  676. public class RequestScheduleForChannel
  677. {
  678. public string stationID { get; set; }
  679. public List<string> date { get; set; }
  680. }
  681. public class Rating
  682. {
  683. public string body { get; set; }
  684. public string code { get; set; }
  685. }
  686. public class Multipart
  687. {
  688. public int partNumber { get; set; }
  689. public int totalParts { get; set; }
  690. }
  691. public class Program
  692. {
  693. public string programID { get; set; }
  694. public string airDateTime { get; set; }
  695. public int duration { get; set; }
  696. public string md5 { get; set; }
  697. public List<string> audioProperties { get; set; }
  698. public List<string> videoProperties { get; set; }
  699. public List<Rating> ratings { get; set; }
  700. public bool? @new { get; set; }
  701. public Multipart multipart { get; set; }
  702. }
  703. public class MetadataSchedule
  704. {
  705. public string modified { get; set; }
  706. public string md5 { get; set; }
  707. public string startDate { get; set; }
  708. public string endDate { get; set; }
  709. public int days { get; set; }
  710. }
  711. public class Day
  712. {
  713. public string stationID { get; set; }
  714. public List<Program> programs { get; set; }
  715. public MetadataSchedule metadata { get; set; }
  716. }
  717. //
  718. public class Title
  719. {
  720. public string title120 { get; set; }
  721. }
  722. public class EventDetails
  723. {
  724. public string subType { get; set; }
  725. }
  726. public class Description100
  727. {
  728. public string descriptionLanguage { get; set; }
  729. public string description { get; set; }
  730. }
  731. public class Description1000
  732. {
  733. public string descriptionLanguage { get; set; }
  734. public string description { get; set; }
  735. }
  736. public class DescriptionsProgram
  737. {
  738. public List<Description100> description100 { get; set; }
  739. public List<Description1000> description1000 { get; set; }
  740. }
  741. public class Gracenote
  742. {
  743. public int season { get; set; }
  744. public int episode { get; set; }
  745. }
  746. public class MetadataPrograms
  747. {
  748. public Gracenote Gracenote { get; set; }
  749. }
  750. public class ContentRating
  751. {
  752. public string body { get; set; }
  753. public string code { get; set; }
  754. }
  755. public class Cast
  756. {
  757. public string billingOrder { get; set; }
  758. public string role { get; set; }
  759. public string nameId { get; set; }
  760. public string personId { get; set; }
  761. public string name { get; set; }
  762. public string characterName { get; set; }
  763. }
  764. public class Crew
  765. {
  766. public string billingOrder { get; set; }
  767. public string role { get; set; }
  768. public string nameId { get; set; }
  769. public string personId { get; set; }
  770. public string name { get; set; }
  771. }
  772. public class QualityRating
  773. {
  774. public string ratingsBody { get; set; }
  775. public string rating { get; set; }
  776. public string minRating { get; set; }
  777. public string maxRating { get; set; }
  778. public string increment { get; set; }
  779. }
  780. public class Movie
  781. {
  782. public string year { get; set; }
  783. public int duration { get; set; }
  784. public List<QualityRating> qualityRating { get; set; }
  785. }
  786. public class Recommendation
  787. {
  788. public string programID { get; set; }
  789. public string title120 { get; set; }
  790. }
  791. public class ProgramDetails
  792. {
  793. public string audience { get; set; }
  794. public string programID { get; set; }
  795. public List<Title> titles { get; set; }
  796. public EventDetails eventDetails { get; set; }
  797. public DescriptionsProgram descriptions { get; set; }
  798. public string originalAirDate { get; set; }
  799. public List<string> genres { get; set; }
  800. public string episodeTitle150 { get; set; }
  801. public List<MetadataPrograms> metadata { get; set; }
  802. public List<ContentRating> contentRating { get; set; }
  803. public List<Cast> cast { get; set; }
  804. public List<Crew> crew { get; set; }
  805. public string showType { get; set; }
  806. public bool hasImageArtwork { get; set; }
  807. public string images { get; set; }
  808. public string imageID { get; set; }
  809. public string md5 { get; set; }
  810. public List<string> contentAdvisory { get; set; }
  811. public Movie movie { get; set; }
  812. public List<Recommendation> recommendations { get; set; }
  813. }
  814. public class Caption
  815. {
  816. public string content { get; set; }
  817. public string lang { get; set; }
  818. }
  819. public class ImageData
  820. {
  821. public string width { get; set; }
  822. public string height { get; set; }
  823. public string uri { get; set; }
  824. public string size { get; set; }
  825. public string aspect { get; set; }
  826. public string category { get; set; }
  827. public string text { get; set; }
  828. public string primary { get; set; }
  829. public string tier { get; set; }
  830. public Caption caption { get; set; }
  831. }
  832. public class ShowImages
  833. {
  834. public string programID { get; set; }
  835. public List<ImageData> data { get; set; }
  836. }
  837. }
  838. }
  839. }