SchedulesDirect.cs 44 KB

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