RemoteSeriesProvider.cs 22 KB

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