SchedulesDirect.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. using MediaBrowser.Model.Extensions;
  19. namespace Emby.Server.Implementations.LiveTv.Listings
  20. {
  21. public class SchedulesDirect : IListingsProvider
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IJsonSerializer _jsonSerializer;
  25. private readonly IHttpClient _httpClient;
  26. private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
  27. private readonly IApplicationHost _appHost;
  28. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  29. private readonly Dictionary<string, Dictionary<string, ScheduleDirect.Station>> _channelPairingCache =
  30. new Dictionary<string, Dictionary<string, ScheduleDirect.Station>>(StringComparer.OrdinalIgnoreCase);
  31. public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
  32. {
  33. _logger = logger;
  34. _jsonSerializer = jsonSerializer;
  35. _httpClient = httpClient;
  36. _appHost = appHost;
  37. }
  38. private string UserAgent
  39. {
  40. get { return "Emby/" + _appHost.ApplicationVersion; }
  41. }
  42. private List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  43. {
  44. List<string> dates = new List<string>();
  45. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  46. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  47. while (start <= end)
  48. {
  49. dates.Add(start.ToString("yyyy-MM-dd"));
  50. start = start.AddDays(1);
  51. }
  52. return dates;
  53. }
  54. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  55. {
  56. if (string.IsNullOrWhiteSpace(channelId))
  57. {
  58. throw new ArgumentNullException("channelId");
  59. }
  60. // Normalize incoming input
  61. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  62. List<ProgramInfo> programsInfo = new List<ProgramInfo>();
  63. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  64. if (string.IsNullOrWhiteSpace(token))
  65. {
  66. _logger.Warn("SchedulesDirect token is empty, returning empty program list");
  67. return programsInfo;
  68. }
  69. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  70. string stationID = channelId;
  71. _logger.Info("Channel Station ID is: " + stationID);
  72. List<ScheduleDirect.RequestScheduleForChannel> requestList =
  73. new List<ScheduleDirect.RequestScheduleForChannel>()
  74. {
  75. new ScheduleDirect.RequestScheduleForChannel()
  76. {
  77. stationID = stationID,
  78. date = dates
  79. }
  80. };
  81. var requestString = _jsonSerializer.SerializeToString(requestList);
  82. _logger.Debug("Request string for schedules is: " + requestString);
  83. var httpOptions = new HttpRequestOptions()
  84. {
  85. Url = ApiUrl + "/schedules",
  86. UserAgent = UserAgent,
  87. CancellationToken = cancellationToken,
  88. // The data can be large so give it some extra time
  89. TimeoutMs = 60000,
  90. LogErrorResponseBody = true
  91. };
  92. httpOptions.RequestHeaders["token"] = token;
  93. httpOptions.RequestContent = requestString;
  94. using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
  95. {
  96. StreamReader reader = new StreamReader(response.Content);
  97. string responseString = reader.ReadToEnd();
  98. var dailySchedules = _jsonSerializer.DeserializeFromString<List<ScheduleDirect.Day>>(responseString);
  99. _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect");
  100. httpOptions = new HttpRequestOptions()
  101. {
  102. Url = ApiUrl + "/programs",
  103. UserAgent = UserAgent,
  104. CancellationToken = cancellationToken,
  105. LogErrorResponseBody = true,
  106. // The data can be large so give it some extra time
  107. TimeoutMs = 60000
  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 Post(httpOptions, true, info).ConfigureAwait(false))
  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 programIdsWithImages =
  123. programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID)
  124. .ToList();
  125. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  126. var schedules = dailySchedules.SelectMany(d => d.programs);
  127. foreach (ScheduleDirect.Program schedule in schedules)
  128. {
  129. //_logger.Debug("Proccesing Schedule for statio ID " + stationID +
  130. // " which corresponds to channel " + channelNumber + " and program id " +
  131. // schedule.programID + " which says it has images? " +
  132. // programDict[schedule.programID].hasImageArtwork);
  133. if (images != null)
  134. {
  135. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  136. if (imageIndex > -1)
  137. {
  138. var programEntry = programDict[schedule.programID];
  139. var allImages = (images[imageIndex].data ?? new List<ScheduleDirect.ImageData>()).OrderByDescending(GetSizeOrder).ToList();
  140. var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
  141. programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, "Logo", true, 600) ??
  142. GetProgramImage(ApiUrl, allImages, "Logo", true, 600);
  143. //programEntry.thumbImage = GetProgramImage(ApiUrl, data, "Iconic", false);
  144. //programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  145. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  146. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  147. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  148. }
  149. }
  150. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
  151. }
  152. }
  153. }
  154. return programsInfo;
  155. }
  156. private int GetSizeOrder(ScheduleDirect.ImageData image)
  157. {
  158. if (!string.IsNullOrWhiteSpace(image.height))
  159. {
  160. int value;
  161. if (int.TryParse(image.height, out value))
  162. {
  163. return value;
  164. }
  165. }
  166. return 0;
  167. }
  168. private string GetChannelNumber(ScheduleDirect.Map map)
  169. {
  170. var channelNumber = map.logicalChannelNumber;
  171. if (string.IsNullOrWhiteSpace(channelNumber))
  172. {
  173. channelNumber = map.channel;
  174. }
  175. if (string.IsNullOrWhiteSpace(channelNumber))
  176. {
  177. channelNumber = map.atscMajor + "." + map.atscMinor;
  178. }
  179. channelNumber = channelNumber.TrimStart('0');
  180. return channelNumber;
  181. }
  182. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  183. {
  184. //_logger.Debug("Show type is: " + (details.showType ?? "No ShowType"));
  185. DateTime startAt = GetDate(programInfo.airDateTime);
  186. DateTime endAt = startAt.AddSeconds(programInfo.duration);
  187. ProgramAudio audioType = ProgramAudio.Stereo;
  188. bool repeat = programInfo.@new == null;
  189. string newID = programInfo.programID + "T" + startAt.Ticks + "C" + channelId;
  190. if (programInfo.audioProperties != null)
  191. {
  192. if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
  193. {
  194. audioType = ProgramAudio.Atmos;
  195. }
  196. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  197. {
  198. audioType = ProgramAudio.DolbyDigital;
  199. }
  200. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  201. {
  202. audioType = ProgramAudio.DolbyDigital;
  203. }
  204. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  205. {
  206. audioType = ProgramAudio.Stereo;
  207. }
  208. else
  209. {
  210. audioType = ProgramAudio.Mono;
  211. }
  212. }
  213. string episodeTitle = null;
  214. if (details.episodeTitle150 != null)
  215. {
  216. episodeTitle = details.episodeTitle150;
  217. }
  218. var showType = details.showType ?? string.Empty;
  219. var info = new ProgramInfo
  220. {
  221. ChannelId = channelId,
  222. Id = newID,
  223. StartDate = startAt,
  224. EndDate = endAt,
  225. Name = details.titles[0].title120 ?? "Unkown",
  226. OfficialRating = null,
  227. CommunityRating = null,
  228. EpisodeTitle = episodeTitle,
  229. Audio = audioType,
  230. IsRepeat = repeat,
  231. IsSeries = showType.IndexOf("series", StringComparison.OrdinalIgnoreCase) != -1,
  232. ImageUrl = details.primaryImage,
  233. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  234. IsSports = showType.IndexOf("sports", StringComparison.OrdinalIgnoreCase) != -1,
  235. IsMovie = showType.IndexOf("movie", StringComparison.OrdinalIgnoreCase) != -1 || showType.IndexOf("film", StringComparison.OrdinalIgnoreCase) != -1,
  236. Etag = programInfo.md5
  237. };
  238. var showId = programInfo.programID ?? string.Empty;
  239. if (!info.IsSeries)
  240. {
  241. // It's also a series if it starts with SH
  242. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  243. }
  244. // According to SchedulesDirect, these are generic, unidentified episodes
  245. // SH005316560000
  246. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  247. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  248. if (!hasUniqueShowId)
  249. {
  250. showId = newID;
  251. }
  252. info.ShowId = showId;
  253. if (programInfo.videoProperties != null)
  254. {
  255. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  256. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  257. }
  258. if (details.contentRating != null && details.contentRating.Count > 0)
  259. {
  260. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
  261. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  262. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  263. {
  264. info.OfficialRating = null;
  265. }
  266. }
  267. if (details.descriptions != null)
  268. {
  269. if (details.descriptions.description1000 != null)
  270. {
  271. info.Overview = details.descriptions.description1000[0].description;
  272. }
  273. else if (details.descriptions.description100 != null)
  274. {
  275. info.Overview = details.descriptions.description100[0].description;
  276. }
  277. }
  278. if (info.IsSeries)
  279. {
  280. info.SeriesId = programInfo.programID.Substring(0, 10);
  281. if (details.metadata != null)
  282. {
  283. var gracenote = details.metadata.Find(x => x.Gracenote != null).Gracenote;
  284. info.SeasonNumber = gracenote.season;
  285. if (gracenote.episode > 0)
  286. {
  287. info.EpisodeNumber = gracenote.episode;
  288. }
  289. }
  290. }
  291. if (!string.IsNullOrWhiteSpace(details.originalAirDate) && (!info.IsSeries || info.IsRepeat))
  292. {
  293. info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
  294. info.ProductionYear = info.OriginalAirDate.Value.Year;
  295. }
  296. if (details.genres != null)
  297. {
  298. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  299. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  300. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  301. {
  302. info.IsKids = true;
  303. }
  304. }
  305. return info;
  306. }
  307. private DateTime GetDate(string value)
  308. {
  309. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  310. if (date.Kind != DateTimeKind.Utc)
  311. {
  312. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  313. }
  314. return date;
  315. }
  316. private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, string category, bool returnDefaultImage, int desiredWidth)
  317. {
  318. string url = null;
  319. var matches = images
  320. .Where(i => string.Equals(i.category, category, StringComparison.OrdinalIgnoreCase))
  321. .ToList();
  322. if (matches.Count == 0)
  323. {
  324. if (!returnDefaultImage)
  325. {
  326. return null;
  327. }
  328. matches = images;
  329. }
  330. var match = matches.FirstOrDefault(i =>
  331. {
  332. if (!string.IsNullOrWhiteSpace(i.width))
  333. {
  334. int value;
  335. if (int.TryParse(i.width, out value))
  336. {
  337. return value <= desiredWidth;
  338. }
  339. }
  340. return false;
  341. });
  342. if (match == null)
  343. {
  344. // Get the second lowest quality image, when possible
  345. if (matches.Count > 1)
  346. {
  347. match = matches[matches.Count - 2];
  348. }
  349. else
  350. {
  351. match = matches.FirstOrDefault();
  352. }
  353. }
  354. if (match == null)
  355. {
  356. return null;
  357. }
  358. var uri = match.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. return url;
  372. }
  373. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  374. ListingsProviderInfo info,
  375. List<string> programIds,
  376. CancellationToken cancellationToken)
  377. {
  378. if (programIds.Count == 0)
  379. {
  380. return new List<ScheduleDirect.ShowImages>();
  381. }
  382. var imageIdString = "[";
  383. foreach (var i in programIds)
  384. {
  385. var imageId = i.Substring(0, 10);
  386. if (!imageIdString.Contains(imageId))
  387. {
  388. imageIdString += "\"" + imageId + "\",";
  389. }
  390. }
  391. imageIdString = imageIdString.TrimEnd(',') + "]";
  392. var httpOptions = new HttpRequestOptions()
  393. {
  394. Url = ApiUrl + "/metadata/programs",
  395. UserAgent = UserAgent,
  396. CancellationToken = cancellationToken,
  397. RequestContent = imageIdString,
  398. LogErrorResponseBody = true,
  399. // The data can be large so give it some extra time
  400. TimeoutMs = 60000
  401. };
  402. try
  403. {
  404. using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
  405. {
  406. return _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.ShowImages>>(
  407. innerResponse2.Content);
  408. }
  409. }
  410. catch (Exception ex)
  411. {
  412. _logger.ErrorException("Error getting image info from schedules direct", ex);
  413. return new List<ScheduleDirect.ShowImages>();
  414. }
  415. }
  416. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  417. {
  418. var token = await GetToken(info, cancellationToken);
  419. var lineups = new List<NameIdPair>();
  420. if (string.IsNullOrWhiteSpace(token))
  421. {
  422. return lineups;
  423. }
  424. var options = new HttpRequestOptions()
  425. {
  426. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  427. UserAgent = UserAgent,
  428. CancellationToken = cancellationToken,
  429. LogErrorResponseBody = true
  430. };
  431. options.RequestHeaders["token"] = token;
  432. try
  433. {
  434. using (Stream responce = await Get(options, false, info).ConfigureAwait(false))
  435. {
  436. var root = _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.Headends>>(responce);
  437. if (root != null)
  438. {
  439. foreach (ScheduleDirect.Headends headend in root)
  440. {
  441. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  442. {
  443. lineups.Add(new NameIdPair
  444. {
  445. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  446. Id = lineup.uri.Substring(18)
  447. });
  448. }
  449. }
  450. }
  451. else
  452. {
  453. _logger.Info("No lineups available");
  454. }
  455. }
  456. }
  457. catch (Exception ex)
  458. {
  459. _logger.Error("Error getting headends", ex);
  460. }
  461. return lineups;
  462. }
  463. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  464. private DateTime _lastErrorResponse;
  465. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  466. {
  467. var username = info.Username;
  468. // Reset the token if there's no username
  469. if (string.IsNullOrWhiteSpace(username))
  470. {
  471. return null;
  472. }
  473. var password = info.Password;
  474. if (string.IsNullOrWhiteSpace(password))
  475. {
  476. return null;
  477. }
  478. // Avoid hammering SD
  479. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  480. {
  481. return null;
  482. }
  483. NameValuePair savedToken = null;
  484. if (!_tokens.TryGetValue(username, out savedToken))
  485. {
  486. savedToken = new NameValuePair();
  487. _tokens.TryAdd(username, savedToken);
  488. }
  489. if (!string.IsNullOrWhiteSpace(savedToken.Name) && !string.IsNullOrWhiteSpace(savedToken.Value))
  490. {
  491. long ticks;
  492. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
  493. {
  494. // If it's under 24 hours old we can still use it
  495. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  496. {
  497. return savedToken.Name;
  498. }
  499. }
  500. }
  501. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  502. try
  503. {
  504. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  505. savedToken.Name = result;
  506. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  507. return result;
  508. }
  509. catch (HttpException ex)
  510. {
  511. if (ex.StatusCode.HasValue)
  512. {
  513. if ((int)ex.StatusCode.Value == 400)
  514. {
  515. _tokens.Clear();
  516. _lastErrorResponse = DateTime.UtcNow;
  517. }
  518. }
  519. throw;
  520. }
  521. finally
  522. {
  523. _tokenSemaphore.Release();
  524. }
  525. }
  526. private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
  527. bool enableRetry,
  528. ListingsProviderInfo providerInfo)
  529. {
  530. try
  531. {
  532. return await _httpClient.Post(options).ConfigureAwait(false);
  533. }
  534. catch (HttpException ex)
  535. {
  536. _tokens.Clear();
  537. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  538. {
  539. enableRetry = false;
  540. }
  541. if (!enableRetry)
  542. {
  543. throw;
  544. }
  545. }
  546. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  547. options.RequestHeaders["token"] = newToken;
  548. return await Post(options, false, providerInfo).ConfigureAwait(false);
  549. }
  550. private async Task<Stream> Get(HttpRequestOptions options,
  551. bool enableRetry,
  552. ListingsProviderInfo providerInfo)
  553. {
  554. try
  555. {
  556. return await _httpClient.Get(options).ConfigureAwait(false);
  557. }
  558. catch (HttpException ex)
  559. {
  560. _tokens.Clear();
  561. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  562. {
  563. enableRetry = false;
  564. }
  565. if (!enableRetry)
  566. {
  567. throw;
  568. }
  569. }
  570. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  571. options.RequestHeaders["token"] = newToken;
  572. return await Get(options, false, providerInfo).ConfigureAwait(false);
  573. }
  574. private async Task<string> GetTokenInternal(string username, string password,
  575. CancellationToken cancellationToken)
  576. {
  577. var httpOptions = new HttpRequestOptions()
  578. {
  579. Url = ApiUrl + "/token",
  580. UserAgent = UserAgent,
  581. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  582. CancellationToken = cancellationToken,
  583. LogErrorResponseBody = true
  584. };
  585. //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  586. // httpOptions.RequestContent);
  587. using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false))
  588. {
  589. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Token>(responce.Content);
  590. if (root.message == "OK")
  591. {
  592. _logger.Info("Authenticated with Schedules Direct token: " + root.token);
  593. return root.token;
  594. }
  595. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  596. }
  597. }
  598. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  599. {
  600. var token = await GetToken(info, cancellationToken);
  601. if (string.IsNullOrWhiteSpace(token))
  602. {
  603. throw new ArgumentException("Authentication required.");
  604. }
  605. if (string.IsNullOrWhiteSpace(info.ListingsId))
  606. {
  607. throw new ArgumentException("Listings Id required");
  608. }
  609. _logger.Info("Adding new LineUp ");
  610. var httpOptions = new HttpRequestOptions()
  611. {
  612. Url = ApiUrl + "/lineups/" + info.ListingsId,
  613. UserAgent = UserAgent,
  614. CancellationToken = cancellationToken,
  615. LogErrorResponseBody = true,
  616. BufferContent = false
  617. };
  618. httpOptions.RequestHeaders["token"] = token;
  619. using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
  620. {
  621. }
  622. }
  623. public string Name
  624. {
  625. get { return "Schedules Direct"; }
  626. }
  627. public static string TypeName = "SchedulesDirect";
  628. public string Type
  629. {
  630. get { return TypeName; }
  631. }
  632. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  633. {
  634. if (string.IsNullOrWhiteSpace(info.ListingsId))
  635. {
  636. throw new ArgumentException("Listings Id required");
  637. }
  638. var token = await GetToken(info, cancellationToken);
  639. if (string.IsNullOrWhiteSpace(token))
  640. {
  641. throw new Exception("token required");
  642. }
  643. _logger.Info("Headends on account ");
  644. var options = new HttpRequestOptions()
  645. {
  646. Url = ApiUrl + "/lineups",
  647. UserAgent = UserAgent,
  648. CancellationToken = cancellationToken,
  649. LogErrorResponseBody = true
  650. };
  651. options.RequestHeaders["token"] = token;
  652. try
  653. {
  654. using (var response = await Get(options, false, null).ConfigureAwait(false))
  655. {
  656. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Lineups>(response);
  657. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  658. }
  659. }
  660. catch (HttpException ex)
  661. {
  662. // Apparently we're supposed to swallow this
  663. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  664. {
  665. return false;
  666. }
  667. throw;
  668. }
  669. }
  670. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  671. {
  672. if (validateLogin)
  673. {
  674. if (string.IsNullOrWhiteSpace(info.Username))
  675. {
  676. throw new ArgumentException("Username is required");
  677. }
  678. if (string.IsNullOrWhiteSpace(info.Password))
  679. {
  680. throw new ArgumentException("Password is required");
  681. }
  682. }
  683. if (validateListings)
  684. {
  685. if (string.IsNullOrWhiteSpace(info.ListingsId))
  686. {
  687. throw new ArgumentException("Listings Id required");
  688. }
  689. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  690. if (!hasLineup)
  691. {
  692. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  693. }
  694. }
  695. }
  696. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  697. {
  698. return GetHeadends(info, country, location, CancellationToken.None);
  699. }
  700. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  701. {
  702. var listingsId = info.ListingsId;
  703. if (string.IsNullOrWhiteSpace(listingsId))
  704. {
  705. throw new Exception("ListingsId required");
  706. }
  707. var token = await GetToken(info, cancellationToken);
  708. if (string.IsNullOrWhiteSpace(token))
  709. {
  710. throw new Exception("token required");
  711. }
  712. var httpOptions = new HttpRequestOptions()
  713. {
  714. Url = ApiUrl + "/lineups/" + listingsId,
  715. UserAgent = UserAgent,
  716. CancellationToken = cancellationToken,
  717. LogErrorResponseBody = true,
  718. // The data can be large so give it some extra time
  719. TimeoutMs = 60000
  720. };
  721. httpOptions.RequestHeaders["token"] = token;
  722. var list = new List<ChannelInfo>();
  723. using (var response = await Get(httpOptions, true, info).ConfigureAwait(false))
  724. {
  725. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Channel>(response);
  726. _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect");
  727. _logger.Info("Mapping Stations to Channel");
  728. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  729. foreach (ScheduleDirect.Map map in root.map)
  730. {
  731. var channelNumber = GetChannelNumber(map);
  732. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  733. if (station == null)
  734. {
  735. station = new ScheduleDirect.Station
  736. {
  737. stationID = map.stationID
  738. };
  739. }
  740. var name = channelNumber;
  741. var channelInfo = new ChannelInfo
  742. {
  743. Number = channelNumber,
  744. Name = name
  745. };
  746. if (station != null)
  747. {
  748. if (!string.IsNullOrWhiteSpace(station.name))
  749. {
  750. channelInfo.Name = station.name;
  751. }
  752. channelInfo.Id = station.stationID;
  753. channelInfo.CallSign = station.callsign;
  754. if (station.logo != null)
  755. {
  756. channelInfo.ImageUrl = station.logo.URL;
  757. channelInfo.HasImage = true;
  758. }
  759. }
  760. list.Add(channelInfo);
  761. }
  762. }
  763. return list;
  764. }
  765. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  766. {
  767. if (!string.IsNullOrWhiteSpace(channelName))
  768. {
  769. channelName = NormalizeName(channelName);
  770. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  771. if (result != null)
  772. {
  773. return result;
  774. }
  775. }
  776. if (!string.IsNullOrWhiteSpace(channelNumber))
  777. {
  778. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  779. }
  780. return null;
  781. }
  782. private string NormalizeName(string value)
  783. {
  784. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  785. }
  786. public class ScheduleDirect
  787. {
  788. public class Token
  789. {
  790. public int code { get; set; }
  791. public string message { get; set; }
  792. public string serverID { get; set; }
  793. public string token { get; set; }
  794. }
  795. public class Lineup
  796. {
  797. public string lineup { get; set; }
  798. public string name { get; set; }
  799. public string transport { get; set; }
  800. public string location { get; set; }
  801. public string uri { get; set; }
  802. }
  803. public class Lineups
  804. {
  805. public int code { get; set; }
  806. public string serverID { get; set; }
  807. public string datetime { get; set; }
  808. public List<Lineup> lineups { get; set; }
  809. }
  810. public class Headends
  811. {
  812. public string headend { get; set; }
  813. public string transport { get; set; }
  814. public string location { get; set; }
  815. public List<Lineup> lineups { get; set; }
  816. }
  817. public class Map
  818. {
  819. public string stationID { get; set; }
  820. public string channel { get; set; }
  821. public string logicalChannelNumber { get; set; }
  822. public int uhfVhf { get; set; }
  823. public int atscMajor { get; set; }
  824. public int atscMinor { get; set; }
  825. }
  826. public class Broadcaster
  827. {
  828. public string city { get; set; }
  829. public string state { get; set; }
  830. public string postalcode { get; set; }
  831. public string country { get; set; }
  832. }
  833. public class Logo
  834. {
  835. public string URL { get; set; }
  836. public int height { get; set; }
  837. public int width { get; set; }
  838. public string md5 { get; set; }
  839. }
  840. public class Station
  841. {
  842. public string stationID { get; set; }
  843. public string name { get; set; }
  844. public string callsign { get; set; }
  845. public List<string> broadcastLanguage { get; set; }
  846. public List<string> descriptionLanguage { get; set; }
  847. public Broadcaster broadcaster { get; set; }
  848. public string affiliate { get; set; }
  849. public Logo logo { get; set; }
  850. public bool? isCommercialFree { get; set; }
  851. }
  852. public class Metadata
  853. {
  854. public string lineup { get; set; }
  855. public string modified { get; set; }
  856. public string transport { get; set; }
  857. }
  858. public class Channel
  859. {
  860. public List<Map> map { get; set; }
  861. public List<Station> stations { get; set; }
  862. public Metadata metadata { get; set; }
  863. }
  864. public class RequestScheduleForChannel
  865. {
  866. public string stationID { get; set; }
  867. public List<string> date { get; set; }
  868. }
  869. public class Rating
  870. {
  871. public string body { get; set; }
  872. public string code { get; set; }
  873. }
  874. public class Multipart
  875. {
  876. public int partNumber { get; set; }
  877. public int totalParts { get; set; }
  878. }
  879. public class Program
  880. {
  881. public string programID { get; set; }
  882. public string airDateTime { get; set; }
  883. public int duration { get; set; }
  884. public string md5 { get; set; }
  885. public List<string> audioProperties { get; set; }
  886. public List<string> videoProperties { get; set; }
  887. public List<Rating> ratings { get; set; }
  888. public bool? @new { get; set; }
  889. public Multipart multipart { get; set; }
  890. }
  891. public class MetadataSchedule
  892. {
  893. public string modified { get; set; }
  894. public string md5 { get; set; }
  895. public string startDate { get; set; }
  896. public string endDate { get; set; }
  897. public int days { get; set; }
  898. }
  899. public class Day
  900. {
  901. public string stationID { get; set; }
  902. public List<Program> programs { get; set; }
  903. public MetadataSchedule metadata { get; set; }
  904. public Day()
  905. {
  906. programs = new List<Program>();
  907. }
  908. }
  909. //
  910. public class Title
  911. {
  912. public string title120 { get; set; }
  913. }
  914. public class EventDetails
  915. {
  916. public string subType { get; set; }
  917. }
  918. public class Description100
  919. {
  920. public string descriptionLanguage { get; set; }
  921. public string description { get; set; }
  922. }
  923. public class Description1000
  924. {
  925. public string descriptionLanguage { get; set; }
  926. public string description { get; set; }
  927. }
  928. public class DescriptionsProgram
  929. {
  930. public List<Description100> description100 { get; set; }
  931. public List<Description1000> description1000 { get; set; }
  932. }
  933. public class Gracenote
  934. {
  935. public int season { get; set; }
  936. public int episode { get; set; }
  937. }
  938. public class MetadataPrograms
  939. {
  940. public Gracenote Gracenote { get; set; }
  941. }
  942. public class ContentRating
  943. {
  944. public string body { get; set; }
  945. public string code { get; set; }
  946. }
  947. public class Cast
  948. {
  949. public string billingOrder { get; set; }
  950. public string role { get; set; }
  951. public string nameId { get; set; }
  952. public string personId { get; set; }
  953. public string name { get; set; }
  954. public string characterName { get; set; }
  955. }
  956. public class Crew
  957. {
  958. public string billingOrder { get; set; }
  959. public string role { get; set; }
  960. public string nameId { get; set; }
  961. public string personId { get; set; }
  962. public string name { get; set; }
  963. }
  964. public class QualityRating
  965. {
  966. public string ratingsBody { get; set; }
  967. public string rating { get; set; }
  968. public string minRating { get; set; }
  969. public string maxRating { get; set; }
  970. public string increment { get; set; }
  971. }
  972. public class Movie
  973. {
  974. public string year { get; set; }
  975. public int duration { get; set; }
  976. public List<QualityRating> qualityRating { get; set; }
  977. }
  978. public class Recommendation
  979. {
  980. public string programID { get; set; }
  981. public string title120 { get; set; }
  982. }
  983. public class ProgramDetails
  984. {
  985. public string audience { get; set; }
  986. public string programID { get; set; }
  987. public List<Title> titles { get; set; }
  988. public EventDetails eventDetails { get; set; }
  989. public DescriptionsProgram descriptions { get; set; }
  990. public string originalAirDate { get; set; }
  991. public List<string> genres { get; set; }
  992. public string episodeTitle150 { get; set; }
  993. public List<MetadataPrograms> metadata { get; set; }
  994. public List<ContentRating> contentRating { get; set; }
  995. public List<Cast> cast { get; set; }
  996. public List<Crew> crew { get; set; }
  997. public string showType { get; set; }
  998. public bool hasImageArtwork { get; set; }
  999. public string primaryImage { get; set; }
  1000. public string thumbImage { get; set; }
  1001. public string bannerImage { get; set; }
  1002. public string imageID { get; set; }
  1003. public string md5 { get; set; }
  1004. public List<string> contentAdvisory { get; set; }
  1005. public Movie movie { get; set; }
  1006. public List<Recommendation> recommendations { get; set; }
  1007. }
  1008. public class Caption
  1009. {
  1010. public string content { get; set; }
  1011. public string lang { get; set; }
  1012. }
  1013. public class ImageData
  1014. {
  1015. public string width { get; set; }
  1016. public string height { get; set; }
  1017. public string uri { get; set; }
  1018. public string size { get; set; }
  1019. public string aspect { get; set; }
  1020. public string category { get; set; }
  1021. public string text { get; set; }
  1022. public string primary { get; set; }
  1023. public string tier { get; set; }
  1024. public Caption caption { get; set; }
  1025. }
  1026. public class ShowImages
  1027. {
  1028. public string programID { get; set; }
  1029. public List<ImageData> data { get; set; }
  1030. }
  1031. }
  1032. }
  1033. }