SchedulesDirect.cs 37 KB

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