SchedulesDirect.cs 48 KB

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