SchedulesDirect.cs 36 KB

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