SchedulesDirect.cs 44 KB

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