SchedulesDirect.cs 36 KB

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