SchedulesDirect.cs 38 KB

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