SchedulesDirect.cs 44 KB

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