RemoteSeriesProvider.cs 24 KB

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