RemoteSeriesProvider.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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.Globalization;
  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 LocalMetaFileName = "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. return !HasLocalMeta(item) && base.NeedsRefreshInternal(item, providerInfo);
  125. }
  126. /// <summary>
  127. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  128. /// </summary>
  129. /// <param name="item">The item.</param>
  130. /// <param name="force">if set to <c>true</c> [force].</param>
  131. /// <param name="cancellationToken">The cancellation token.</param>
  132. /// <returns>Task{System.Boolean}.</returns>
  133. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  134. {
  135. cancellationToken.ThrowIfCancellationRequested();
  136. var series = (Series)item;
  137. if (!item.DontFetchMeta && !HasLocalMeta(series))
  138. {
  139. var path = item.Path ?? "";
  140. var seriesId = Path.GetFileName(path).GetAttributeValue("tvdbid") ?? await GetSeriesId(series, cancellationToken);
  141. cancellationToken.ThrowIfCancellationRequested();
  142. var status = ProviderRefreshStatus.Success;
  143. if (!string.IsNullOrEmpty(seriesId))
  144. {
  145. series.SetProviderId(MetadataProviders.Tvdb, seriesId);
  146. status = await FetchSeriesData(series, seriesId, cancellationToken).ConfigureAwait(false);
  147. }
  148. SetLastRefreshed(item, DateTime.UtcNow, status);
  149. return true;
  150. }
  151. Logger.Info("Series provider not fetching because local meta exists or requested to ignore: " + item.Name);
  152. return false;
  153. }
  154. /// <summary>
  155. /// Fetches the series data.
  156. /// </summary>
  157. /// <param name="series">The series.</param>
  158. /// <param name="seriesId">The series id.</param>
  159. /// <param name="cancellationToken">The cancellation token.</param>
  160. /// <returns>Task{System.Boolean}.</returns>
  161. private async Task<ProviderRefreshStatus> FetchSeriesData(Series series, string seriesId, CancellationToken cancellationToken)
  162. {
  163. var status = ProviderRefreshStatus.Success;
  164. if (!string.IsNullOrEmpty(seriesId))
  165. {
  166. string url = string.Format(SeriesGet, TVUtils.TvdbApiKey, seriesId, ConfigurationManager.Configuration.PreferredMetadataLanguage);
  167. var doc = new XmlDocument();
  168. using (var xml = await HttpClient.Get(new HttpRequestOptions
  169. {
  170. Url = url,
  171. ResourcePool = TvDbResourcePool,
  172. CancellationToken = cancellationToken,
  173. EnableResponseCache = true
  174. }).ConfigureAwait(false))
  175. {
  176. doc.Load(xml);
  177. }
  178. if (doc.HasChildNodes)
  179. {
  180. //kick off the actor and image fetch simultaneously
  181. var actorTask = FetchActors(series, seriesId, doc, cancellationToken);
  182. var imageTask = FetchImages(series, seriesId, cancellationToken);
  183. series.Name = doc.SafeGetString("//SeriesName");
  184. series.Overview = doc.SafeGetString("//Overview");
  185. series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
  186. series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
  187. series.AirTime = doc.SafeGetString("//Airs_Time");
  188. string n = doc.SafeGetString("//banner");
  189. if (!string.IsNullOrWhiteSpace(n))
  190. {
  191. series.SetImage(ImageType.Banner, await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n, "banner" + Path.GetExtension(n), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  192. }
  193. string s = doc.SafeGetString("//Network");
  194. if (!string.IsNullOrWhiteSpace(s))
  195. {
  196. series.Studios.Clear();
  197. foreach (var studio in s.Trim().Split('|'))
  198. {
  199. series.AddStudio(studio);
  200. }
  201. }
  202. series.OfficialRating = doc.SafeGetString("//ContentRating");
  203. string g = doc.SafeGetString("//Genre");
  204. if (g != null)
  205. {
  206. string[] genres = g.Trim('|').Split('|');
  207. if (g.Length > 0)
  208. {
  209. series.Genres.Clear();
  210. foreach (var genre in genres)
  211. {
  212. series.AddGenre(genre);
  213. }
  214. }
  215. }
  216. try
  217. {
  218. //wait for other tasks
  219. await Task.WhenAll(actorTask, imageTask).ConfigureAwait(false);
  220. }
  221. catch (HttpException)
  222. {
  223. status = ProviderRefreshStatus.CompletedWithErrors;
  224. }
  225. if (ConfigurationManager.Configuration.SaveLocalMeta)
  226. {
  227. var ms = new MemoryStream();
  228. doc.Save(ms);
  229. await _providerManager.SaveToLibraryFilesystem(series, Path.Combine(series.MetaLocation, LocalMetaFileName), ms, cancellationToken).ConfigureAwait(false);
  230. }
  231. }
  232. }
  233. return status;
  234. }
  235. /// <summary>
  236. /// Fetches the actors.
  237. /// </summary>
  238. /// <param name="series">The series.</param>
  239. /// <param name="seriesId">The series id.</param>
  240. /// <param name="doc">The doc.</param>
  241. /// <param name="cancellationToken">The cancellation token.</param>
  242. /// <returns>Task.</returns>
  243. private async Task FetchActors(Series series, string seriesId, XmlDocument doc, CancellationToken cancellationToken)
  244. {
  245. string urlActors = string.Format(GetActors, TVUtils.TvdbApiKey, seriesId);
  246. var docActors = new XmlDocument();
  247. using (var actors = await HttpClient.Get(new HttpRequestOptions
  248. {
  249. Url = urlActors,
  250. ResourcePool = TvDbResourcePool,
  251. CancellationToken = cancellationToken,
  252. EnableResponseCache = true
  253. }).ConfigureAwait(false))
  254. {
  255. docActors.Load(actors);
  256. }
  257. if (docActors.HasChildNodes)
  258. {
  259. XmlNode actorsNode = null;
  260. if (ConfigurationManager.Configuration.SaveLocalMeta)
  261. {
  262. //add to the main doc for saving
  263. var seriesNode = doc.SelectSingleNode("//Series");
  264. if (seriesNode != null)
  265. {
  266. actorsNode = doc.CreateNode(XmlNodeType.Element, "Persons", null);
  267. seriesNode.AppendChild(actorsNode);
  268. }
  269. }
  270. var xmlNodeList = docActors.SelectNodes("Actors/Actor");
  271. if (xmlNodeList != null)
  272. {
  273. series.People.Clear();
  274. foreach (XmlNode p in xmlNodeList)
  275. {
  276. string actorName = p.SafeGetString("Name");
  277. string actorRole = p.SafeGetString("Role");
  278. if (!string.IsNullOrWhiteSpace(actorName))
  279. {
  280. series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName, Role = actorRole });
  281. if (ConfigurationManager.Configuration.SaveLocalMeta && actorsNode != null)
  282. {
  283. //create in main doc
  284. var personNode = doc.CreateNode(XmlNodeType.Element, "Person", null);
  285. foreach (XmlNode subNode in p.ChildNodes)
  286. personNode.AppendChild(doc.ImportNode(subNode, true));
  287. //need to add the type
  288. var typeNode = doc.CreateNode(XmlNodeType.Element, "Type", null);
  289. typeNode.InnerText = PersonType.Actor;
  290. personNode.AppendChild(typeNode);
  291. actorsNode.AppendChild(personNode);
  292. }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  299. /// <summary>
  300. /// Fetches the images.
  301. /// </summary>
  302. /// <param name="series">The series.</param>
  303. /// <param name="seriesId">The series id.</param>
  304. /// <param name="cancellationToken">The cancellation token.</param>
  305. /// <returns>Task.</returns>
  306. private async Task FetchImages(Series series, string seriesId, CancellationToken cancellationToken)
  307. {
  308. if ((!string.IsNullOrEmpty(seriesId)) && ((series.PrimaryImagePath == null) || (series.BackdropImagePaths == null)))
  309. {
  310. string url = string.Format("http://www.thetvdb.com/api/" + TVUtils.TvdbApiKey + "/series/{0}/banners.xml", seriesId);
  311. var images = new XmlDocument();
  312. using (var imgs = await HttpClient.Get(new HttpRequestOptions
  313. {
  314. Url = url,
  315. ResourcePool = TvDbResourcePool,
  316. CancellationToken = cancellationToken,
  317. EnableResponseCache = true
  318. }).ConfigureAwait(false))
  319. {
  320. images.Load(imgs);
  321. }
  322. if (images.HasChildNodes)
  323. {
  324. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("folder"))
  325. {
  326. var n = images.SelectSingleNode("//Banner[BannerType='poster']");
  327. if (n != null)
  328. {
  329. n = n.SelectSingleNode("./BannerPath");
  330. if (n != null)
  331. {
  332. series.PrimaryImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "folder" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false);
  333. }
  334. }
  335. }
  336. if (ConfigurationManager.Configuration.DownloadSeriesImages.Banner && (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("banner")))
  337. {
  338. var n = images.SelectSingleNode("//Banner[BannerType='series']");
  339. if (n != null)
  340. {
  341. n = n.SelectSingleNode("./BannerPath");
  342. if (n != null)
  343. {
  344. var bannerImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "banner" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken);
  345. series.SetImage(ImageType.Banner, bannerImagePath);
  346. }
  347. }
  348. }
  349. var bdNo = 0;
  350. var xmlNodeList = images.SelectNodes("//Banner[BannerType='fanart']");
  351. if (xmlNodeList != null)
  352. foreach (XmlNode b in xmlNodeList)
  353. {
  354. series.BackdropImagePaths = new List<string>();
  355. var p = b.SelectSingleNode("./BannerPath");
  356. if (p != null)
  357. {
  358. var bdName = "backdrop" + (bdNo > 0 ? bdNo.ToString(UsCulture) : "");
  359. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage(bdName))
  360. {
  361. series.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + p.InnerText, bdName + Path.GetExtension(p.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  362. }
  363. bdNo++;
  364. if (bdNo >= ConfigurationManager.Configuration.MaxBackdrops) break;
  365. }
  366. }
  367. }
  368. }
  369. }
  370. /// <summary>
  371. /// Determines whether [has local meta] [the specified item].
  372. /// </summary>
  373. /// <param name="item">The item.</param>
  374. /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
  375. private bool HasLocalMeta(BaseItem item)
  376. {
  377. return item.ResolveArgs.ContainsMetaFileByName(LocalMetaFileName);
  378. }
  379. /// <summary>
  380. /// Gets the series id.
  381. /// </summary>
  382. /// <param name="item">The item.</param>
  383. /// <param name="cancellationToken">The cancellation token.</param>
  384. /// <returns>Task{System.String}.</returns>
  385. private async Task<string> GetSeriesId(BaseItem item, CancellationToken cancellationToken)
  386. {
  387. var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
  388. if (string.IsNullOrEmpty(seriesId))
  389. {
  390. seriesId = await FindSeries(item.Name, cancellationToken).ConfigureAwait(false);
  391. }
  392. return seriesId;
  393. }
  394. /// <summary>
  395. /// Finds the series.
  396. /// </summary>
  397. /// <param name="name">The name.</param>
  398. /// <param name="cancellationToken">The cancellation token.</param>
  399. /// <returns>Task{System.String}.</returns>
  400. public async Task<string> FindSeries(string name, CancellationToken cancellationToken)
  401. {
  402. //nope - search for it
  403. string url = string.Format(RootUrl + SeriesQuery, WebUtility.UrlEncode(name));
  404. var doc = new XmlDocument();
  405. using (var results = await HttpClient.Get(new HttpRequestOptions
  406. {
  407. Url = url,
  408. ResourcePool = TvDbResourcePool,
  409. CancellationToken = cancellationToken,
  410. EnableResponseCache = true
  411. }).ConfigureAwait(false))
  412. {
  413. doc.Load(results);
  414. }
  415. if (doc.HasChildNodes)
  416. {
  417. XmlNodeList nodes = doc.SelectNodes("//Series");
  418. string comparableName = GetComparableName(name);
  419. if (nodes != null)
  420. foreach (XmlNode node in nodes)
  421. {
  422. var n = node.SelectSingleNode("./SeriesName");
  423. if (n != null && GetComparableName(n.InnerText) == comparableName)
  424. {
  425. n = node.SelectSingleNode("./seriesid");
  426. if (n != null)
  427. return n.InnerText;
  428. }
  429. else
  430. {
  431. if (n != null)
  432. Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
  433. }
  434. }
  435. }
  436. Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
  437. return null;
  438. }
  439. /// <summary>
  440. /// The remove
  441. /// </summary>
  442. const string remove = "\"'!`?";
  443. /// <summary>
  444. /// The spacers
  445. /// </summary>
  446. const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  447. /// <summary>
  448. /// Gets the name of the comparable.
  449. /// </summary>
  450. /// <param name="name">The name.</param>
  451. /// <returns>System.String.</returns>
  452. internal static string GetComparableName(string name)
  453. {
  454. name = name.ToLower();
  455. name = name.Normalize(NormalizationForm.FormKD);
  456. var sb = new StringBuilder();
  457. foreach (var c in name)
  458. {
  459. if ((int)c >= 0x2B0 && (int)c <= 0x0333)
  460. {
  461. // skip char modifier and diacritics
  462. }
  463. else if (remove.IndexOf(c) > -1)
  464. {
  465. // skip chars we are removing
  466. }
  467. else if (spacers.IndexOf(c) > -1)
  468. {
  469. sb.Append(" ");
  470. }
  471. else if (c == '&')
  472. {
  473. sb.Append(" and ");
  474. }
  475. else
  476. {
  477. sb.Append(c);
  478. }
  479. }
  480. name = sb.ToString();
  481. name = name.Replace(", the", "");
  482. name = name.Replace("the ", " ");
  483. name = name.Replace(" the ", " ");
  484. string prevName;
  485. do
  486. {
  487. prevName = name;
  488. name = name.Replace(" ", " ");
  489. } while (name.Length != prevName.Length);
  490. return name.Trim();
  491. }
  492. public void Dispose()
  493. {
  494. Dispose(true);
  495. }
  496. }
  497. }