SchedulesDirect.cs 41 KB

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