SchedulesDirect.cs 38 KB

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