SchedulesDirect.cs 37 KB

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