RemoteSeriesProvider.cs 22 KB

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