SchedulesDirect.cs 45 KB

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