SchedulesDirect.cs 43 KB

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