SchedulesDirect.cs 45 KB

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