SchedulesDirect.cs 35 KB

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