RemoteSeriesProvider.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. using System.Globalization;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Extensions;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Net;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Net;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Xml;
  20. namespace MediaBrowser.Controller.Providers.TV
  21. {
  22. /// <summary>
  23. /// Class RemoteSeriesProvider
  24. /// </summary>
  25. class RemoteSeriesProvider : BaseMetadataProvider, IDisposable
  26. {
  27. private readonly IProviderManager _providerManager;
  28. /// <summary>
  29. /// The tv db
  30. /// </summary>
  31. internal readonly SemaphoreSlim TvDbResourcePool = new SemaphoreSlim(5, 5);
  32. internal static RemoteSeriesProvider Current { get; private set; }
  33. /// <summary>
  34. /// Gets the HTTP client.
  35. /// </summary>
  36. /// <value>The HTTP client.</value>
  37. protected IHttpClient HttpClient { get; private set; }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="RemoteSeriesProvider" /> class.
  40. /// </summary>
  41. /// <param name="httpClient">The HTTP client.</param>
  42. /// <param name="logManager">The log manager.</param>
  43. /// <param name="configurationManager">The configuration manager.</param>
  44. /// <param name="providerManager">The provider manager.</param>
  45. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  46. public RemoteSeriesProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  47. : base(logManager, configurationManager)
  48. {
  49. if (httpClient == null)
  50. {
  51. throw new ArgumentNullException("httpClient");
  52. }
  53. HttpClient = httpClient;
  54. _providerManager = providerManager;
  55. Current = this;
  56. }
  57. /// <summary>
  58. /// Releases unmanaged and - optionally - managed resources.
  59. /// </summary>
  60. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  61. protected virtual void Dispose(bool dispose)
  62. {
  63. if (dispose)
  64. {
  65. TvDbResourcePool.Dispose();
  66. }
  67. }
  68. /// <summary>
  69. /// The root URL
  70. /// </summary>
  71. private const string rootUrl = "http://www.thetvdb.com/api/";
  72. /// <summary>
  73. /// The series query
  74. /// </summary>
  75. private const string seriesQuery = "GetSeries.php?seriesname={0}";
  76. /// <summary>
  77. /// The series get
  78. /// </summary>
  79. private const string seriesGet = "http://www.thetvdb.com/api/{0}/series/{1}/{2}.xml";
  80. /// <summary>
  81. /// The get actors
  82. /// </summary>
  83. private const string getActors = "http://www.thetvdb.com/api/{0}/series/{1}/actors.xml";
  84. /// <summary>
  85. /// The LOCA l_ MET a_ FIL e_ NAME
  86. /// </summary>
  87. protected const string LOCAL_META_FILE_NAME = "Series.xml";
  88. /// <summary>
  89. /// Supportses the specified item.
  90. /// </summary>
  91. /// <param name="item">The item.</param>
  92. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  93. public override bool Supports(BaseItem item)
  94. {
  95. return item is Series;
  96. }
  97. /// <summary>
  98. /// Gets the priority.
  99. /// </summary>
  100. /// <value>The priority.</value>
  101. public override MetadataProviderPriority Priority
  102. {
  103. get { return MetadataProviderPriority.Second; }
  104. }
  105. /// <summary>
  106. /// Gets a value indicating whether [requires internet].
  107. /// </summary>
  108. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  109. public override bool RequiresInternet
  110. {
  111. get
  112. {
  113. return true;
  114. }
  115. }
  116. /// <summary>
  117. /// Needses the refresh internal.
  118. /// </summary>
  119. /// <param name="item">The item.</param>
  120. /// <param name="providerInfo">The provider info.</param>
  121. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  122. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  123. {
  124. var downloadDate = providerInfo.LastRefreshed;
  125. if (ConfigurationManager.Configuration.MetadataRefreshDays == -1 && downloadDate != DateTime.MinValue)
  126. {
  127. return false;
  128. }
  129. if (item.DontFetchMeta) return false;
  130. return !HasLocalMeta(item) && (ConfigurationManager.Configuration.MetadataRefreshDays != -1 &&
  131. DateTime.UtcNow.Subtract(downloadDate).TotalDays > ConfigurationManager.Configuration.MetadataRefreshDays);
  132. }
  133. /// <summary>
  134. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  135. /// </summary>
  136. /// <param name="item">The item.</param>
  137. /// <param name="force">if set to <c>true</c> [force].</param>
  138. /// <param name="cancellationToken">The cancellation token.</param>
  139. /// <returns>Task{System.Boolean}.</returns>
  140. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  141. {
  142. cancellationToken.ThrowIfCancellationRequested();
  143. var series = (Series)item;
  144. if (!item.DontFetchMeta && !HasLocalMeta(series))
  145. {
  146. var path = item.Path ?? "";
  147. var seriesId = Path.GetFileName(path).GetAttributeValue("tvdbid") ?? await GetSeriesId(series, cancellationToken);
  148. cancellationToken.ThrowIfCancellationRequested();
  149. if (!string.IsNullOrEmpty(seriesId))
  150. {
  151. series.SetProviderId(MetadataProviders.Tvdb, seriesId);
  152. if (!HasCompleteMetadata(series))
  153. {
  154. await FetchSeriesData(series, seriesId, cancellationToken).ConfigureAwait(false);
  155. }
  156. }
  157. SetLastRefreshed(item, DateTime.UtcNow);
  158. return true;
  159. }
  160. Logger.Info("Series provider not fetching because local meta exists or requested to ignore: " + item.Name);
  161. return false;
  162. }
  163. /// <summary>
  164. /// Fetches the series data.
  165. /// </summary>
  166. /// <param name="series">The series.</param>
  167. /// <param name="seriesId">The series id.</param>
  168. /// <param name="cancellationToken">The cancellation token.</param>
  169. /// <returns>Task{System.Boolean}.</returns>
  170. private async Task<bool> FetchSeriesData(Series series, string seriesId, CancellationToken cancellationToken)
  171. {
  172. var success = false;
  173. var name = series.Name;
  174. Logger.Debug("TvDbProvider: Fetching series data: " + name);
  175. if (!string.IsNullOrEmpty(seriesId))
  176. {
  177. string url = string.Format(seriesGet, TVUtils.TVDBApiKey, seriesId, ConfigurationManager.Configuration.PreferredMetadataLanguage);
  178. var doc = new XmlDocument();
  179. try
  180. {
  181. using (var xml = await HttpClient.Get(new HttpRequestOptions
  182. {
  183. Url = url,
  184. ResourcePool = TvDbResourcePool,
  185. CancellationToken = cancellationToken,
  186. EnableResponseCache = true
  187. }).ConfigureAwait(false))
  188. {
  189. doc.Load(xml);
  190. }
  191. }
  192. catch (HttpException)
  193. {
  194. }
  195. if (doc.HasChildNodes)
  196. {
  197. //kick off the actor and image fetch simultaneously
  198. var actorTask = FetchActors(series, seriesId, doc, cancellationToken);
  199. var imageTask = FetchImages(series, seriesId, cancellationToken);
  200. success = true;
  201. series.Name = doc.SafeGetString("//SeriesName");
  202. series.Overview = doc.SafeGetString("//Overview");
  203. series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
  204. series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
  205. series.AirTime = doc.SafeGetString("//Airs_Time");
  206. string n = doc.SafeGetString("//banner");
  207. if (!string.IsNullOrWhiteSpace(n))
  208. {
  209. series.SetImage(ImageType.Banner, await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n, "banner" + Path.GetExtension(n), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  210. }
  211. string s = doc.SafeGetString("//Network");
  212. if (!string.IsNullOrWhiteSpace(s))
  213. {
  214. series.Studios.Clear();
  215. foreach (var studio in s.Trim().Split('|'))
  216. {
  217. series.AddStudio(studio);
  218. }
  219. }
  220. series.OfficialRating = doc.SafeGetString("//ContentRating");
  221. string g = doc.SafeGetString("//Genre");
  222. if (g != null)
  223. {
  224. string[] genres = g.Trim('|').Split('|');
  225. if (g.Length > 0)
  226. {
  227. series.Genres.Clear();
  228. foreach (var genre in genres)
  229. {
  230. series.AddGenre(genre);
  231. }
  232. }
  233. }
  234. //wait for other tasks
  235. await Task.WhenAll(actorTask, imageTask).ConfigureAwait(false);
  236. if (ConfigurationManager.Configuration.SaveLocalMeta)
  237. {
  238. var ms = new MemoryStream();
  239. doc.Save(ms);
  240. await _providerManager.SaveToLibraryFilesystem(series, Path.Combine(series.MetaLocation, LOCAL_META_FILE_NAME), ms, cancellationToken).ConfigureAwait(false);
  241. }
  242. }
  243. }
  244. return success;
  245. }
  246. /// <summary>
  247. /// Fetches the actors.
  248. /// </summary>
  249. /// <param name="series">The series.</param>
  250. /// <param name="seriesId">The series id.</param>
  251. /// <param name="doc">The doc.</param>
  252. /// <param name="cancellationToken">The cancellation token.</param>
  253. /// <returns>Task.</returns>
  254. private async Task FetchActors(Series series, string seriesId, XmlDocument doc, CancellationToken cancellationToken)
  255. {
  256. string urlActors = string.Format(getActors, TVUtils.TVDBApiKey, seriesId);
  257. var docActors = new XmlDocument();
  258. try
  259. {
  260. using (var actors = await HttpClient.Get(new HttpRequestOptions
  261. {
  262. Url = urlActors,
  263. ResourcePool = TvDbResourcePool,
  264. CancellationToken = cancellationToken,
  265. EnableResponseCache = true
  266. }).ConfigureAwait(false))
  267. {
  268. docActors.Load(actors);
  269. }
  270. }
  271. catch (HttpException)
  272. {
  273. }
  274. if (docActors.HasChildNodes)
  275. {
  276. XmlNode actorsNode = null;
  277. if (ConfigurationManager.Configuration.SaveLocalMeta)
  278. {
  279. //add to the main doc for saving
  280. var seriesNode = doc.SelectSingleNode("//Series");
  281. if (seriesNode != null)
  282. {
  283. actorsNode = doc.CreateNode(XmlNodeType.Element, "Persons", null);
  284. seriesNode.AppendChild(actorsNode);
  285. }
  286. }
  287. var xmlNodeList = docActors.SelectNodes("Actors/Actor");
  288. if (xmlNodeList != null)
  289. {
  290. series.People.Clear();
  291. foreach (XmlNode p in xmlNodeList)
  292. {
  293. string actorName = p.SafeGetString("Name");
  294. string actorRole = p.SafeGetString("Role");
  295. if (!string.IsNullOrWhiteSpace(actorName))
  296. {
  297. series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName, Role = actorRole });
  298. if (ConfigurationManager.Configuration.SaveLocalMeta && actorsNode != null)
  299. {
  300. //create in main doc
  301. var personNode = doc.CreateNode(XmlNodeType.Element, "Person", null);
  302. foreach (XmlNode subNode in p.ChildNodes)
  303. personNode.AppendChild(doc.ImportNode(subNode, true));
  304. //need to add the type
  305. var typeNode = doc.CreateNode(XmlNodeType.Element, "Type", null);
  306. typeNode.InnerText = PersonType.Actor;
  307. personNode.AppendChild(typeNode);
  308. actorsNode.AppendChild(personNode);
  309. }
  310. }
  311. }
  312. }
  313. }
  314. }
  315. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  316. /// <summary>
  317. /// Fetches the images.
  318. /// </summary>
  319. /// <param name="series">The series.</param>
  320. /// <param name="seriesId">The series id.</param>
  321. /// <param name="cancellationToken">The cancellation token.</param>
  322. /// <returns>Task.</returns>
  323. private async Task FetchImages(Series series, string seriesId, CancellationToken cancellationToken)
  324. {
  325. if ((!string.IsNullOrEmpty(seriesId)) && ((series.PrimaryImagePath == null) || (series.BackdropImagePaths == null)))
  326. {
  327. string url = string.Format("http://www.thetvdb.com/api/" + TVUtils.TVDBApiKey + "/series/{0}/banners.xml", seriesId);
  328. var images = new XmlDocument();
  329. try
  330. {
  331. using (var imgs = await HttpClient.Get(new HttpRequestOptions
  332. {
  333. Url = url,
  334. ResourcePool = TvDbResourcePool,
  335. CancellationToken = cancellationToken,
  336. EnableResponseCache = true
  337. }).ConfigureAwait(false))
  338. {
  339. images.Load(imgs);
  340. }
  341. }
  342. catch (HttpException)
  343. {
  344. }
  345. if (images.HasChildNodes)
  346. {
  347. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("folder"))
  348. {
  349. var n = images.SelectSingleNode("//Banner[BannerType='poster']");
  350. if (n != null)
  351. {
  352. n = n.SelectSingleNode("./BannerPath");
  353. if (n != null)
  354. {
  355. try
  356. {
  357. series.PrimaryImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "folder" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false);
  358. }
  359. catch (HttpException)
  360. {
  361. }
  362. catch (IOException)
  363. {
  364. }
  365. }
  366. }
  367. }
  368. if (ConfigurationManager.Configuration.DownloadSeriesImages.Banner && (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("banner")))
  369. {
  370. var n = images.SelectSingleNode("//Banner[BannerType='series']");
  371. if (n != null)
  372. {
  373. n = n.SelectSingleNode("./BannerPath");
  374. if (n != null)
  375. {
  376. try
  377. {
  378. var bannerImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "banner" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken);
  379. series.SetImage(ImageType.Banner, bannerImagePath);
  380. }
  381. catch (HttpException)
  382. {
  383. }
  384. catch (IOException)
  385. {
  386. }
  387. }
  388. }
  389. }
  390. var bdNo = 0;
  391. var xmlNodeList = images.SelectNodes("//Banner[BannerType='fanart']");
  392. if (xmlNodeList != null)
  393. foreach (XmlNode b in xmlNodeList)
  394. {
  395. series.BackdropImagePaths = new List<string>();
  396. var p = b.SelectSingleNode("./BannerPath");
  397. if (p != null)
  398. {
  399. var bdName = "backdrop" + (bdNo > 0 ? bdNo.ToString(UsCulture) : "");
  400. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage(bdName))
  401. {
  402. try
  403. {
  404. series.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + p.InnerText, bdName + Path.GetExtension(p.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  405. }
  406. catch (HttpException)
  407. {
  408. }
  409. catch (IOException)
  410. {
  411. }
  412. }
  413. bdNo++;
  414. if (bdNo >= ConfigurationManager.Configuration.MaxBackdrops) break;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. /// <summary>
  421. /// Determines whether [has complete metadata] [the specified series].
  422. /// </summary>
  423. /// <param name="series">The series.</param>
  424. /// <returns><c>true</c> if [has complete metadata] [the specified series]; otherwise, <c>false</c>.</returns>
  425. private bool HasCompleteMetadata(Series series)
  426. {
  427. return (series.HasImage(ImageType.Banner)) && (series.CommunityRating != null)
  428. && (series.Overview != null) && (series.Name != null) && (series.People != null)
  429. && (series.Genres != null) && (series.OfficialRating != null);
  430. }
  431. /// <summary>
  432. /// Determines whether [has local meta] [the specified item].
  433. /// </summary>
  434. /// <param name="item">The item.</param>
  435. /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
  436. private bool HasLocalMeta(BaseItem item)
  437. {
  438. //need at least the xml and folder.jpg/png
  439. return item.ResolveArgs.ContainsMetaFileByName(LOCAL_META_FILE_NAME) && (item.ResolveArgs.ContainsMetaFileByName("folder.jpg") ||
  440. item.ResolveArgs.ContainsMetaFileByName("folder.png"));
  441. }
  442. /// <summary>
  443. /// Gets the series id.
  444. /// </summary>
  445. /// <param name="item">The item.</param>
  446. /// <param name="cancellationToken">The cancellation token.</param>
  447. /// <returns>Task{System.String}.</returns>
  448. private async Task<string> GetSeriesId(BaseItem item, CancellationToken cancellationToken)
  449. {
  450. var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
  451. if (string.IsNullOrEmpty(seriesId))
  452. {
  453. seriesId = await FindSeries(item.Name, cancellationToken).ConfigureAwait(false);
  454. }
  455. return seriesId;
  456. }
  457. /// <summary>
  458. /// Finds the series.
  459. /// </summary>
  460. /// <param name="name">The name.</param>
  461. /// <param name="cancellationToken">The cancellation token.</param>
  462. /// <returns>Task{System.String}.</returns>
  463. public async Task<string> FindSeries(string name, CancellationToken cancellationToken)
  464. {
  465. //nope - search for it
  466. string url = string.Format(rootUrl + seriesQuery, WebUtility.UrlEncode(name));
  467. var doc = new XmlDocument();
  468. try
  469. {
  470. using (var results = await HttpClient.Get(new HttpRequestOptions
  471. {
  472. Url = url,
  473. ResourcePool = TvDbResourcePool,
  474. CancellationToken = cancellationToken,
  475. EnableResponseCache = true
  476. }).ConfigureAwait(false))
  477. {
  478. doc.Load(results);
  479. }
  480. }
  481. catch (HttpException)
  482. {
  483. }
  484. if (doc.HasChildNodes)
  485. {
  486. XmlNodeList nodes = doc.SelectNodes("//Series");
  487. string comparableName = GetComparableName(name);
  488. if (nodes != null)
  489. foreach (XmlNode node in nodes)
  490. {
  491. var n = node.SelectSingleNode("./SeriesName");
  492. if (n != null && GetComparableName(n.InnerText) == comparableName)
  493. {
  494. n = node.SelectSingleNode("./seriesid");
  495. if (n != null)
  496. return n.InnerText;
  497. }
  498. else
  499. {
  500. if (n != null)
  501. Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
  502. }
  503. }
  504. }
  505. Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
  506. return null;
  507. }
  508. /// <summary>
  509. /// The remove
  510. /// </summary>
  511. const string remove = "\"'!`?";
  512. /// <summary>
  513. /// The spacers
  514. /// </summary>
  515. const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  516. /// <summary>
  517. /// Gets the name of the comparable.
  518. /// </summary>
  519. /// <param name="name">The name.</param>
  520. /// <returns>System.String.</returns>
  521. internal static string GetComparableName(string name)
  522. {
  523. name = name.ToLower();
  524. name = name.Normalize(NormalizationForm.FormKD);
  525. var sb = new StringBuilder();
  526. foreach (var c in name)
  527. {
  528. if ((int)c >= 0x2B0 && (int)c <= 0x0333)
  529. {
  530. // skip char modifier and diacritics
  531. }
  532. else if (remove.IndexOf(c) > -1)
  533. {
  534. // skip chars we are removing
  535. }
  536. else if (spacers.IndexOf(c) > -1)
  537. {
  538. sb.Append(" ");
  539. }
  540. else if (c == '&')
  541. {
  542. sb.Append(" and ");
  543. }
  544. else
  545. {
  546. sb.Append(c);
  547. }
  548. }
  549. name = sb.ToString();
  550. name = name.Replace(", the", "");
  551. name = name.Replace("the ", " ");
  552. name = name.Replace(" the ", " ");
  553. string prevName;
  554. do
  555. {
  556. prevName = name;
  557. name = name.Replace(" ", " ");
  558. } while (name.Length != prevName.Length);
  559. return name.Trim();
  560. }
  561. public void Dispose()
  562. {
  563. Dispose(true);
  564. }
  565. }
  566. }