SchedulesDirect.cs 48 KB

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