SchedulesDirect.cs 47 KB

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