BaseNfoParser.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Xml;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.TV;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.XbmcMetadata.Configuration;
  17. using MediaBrowser.XbmcMetadata.Savers;
  18. using Microsoft.Extensions.Logging;
  19. namespace MediaBrowser.XbmcMetadata.Parsers
  20. {
  21. public class BaseNfoParser<T>
  22. where T : BaseItem
  23. {
  24. private readonly IConfigurationManager _config;
  25. private Dictionary<string, string> _validProviderIds;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
  28. /// </summary>
  29. /// <param name="logger">The logger.</param>
  30. /// <param name="config">the configuration manager.</param>
  31. /// <param name="providerManager">The provider manager.</param>
  32. public BaseNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager)
  33. {
  34. Logger = logger;
  35. _config = config;
  36. ProviderManager = providerManager;
  37. _validProviderIds = new Dictionary<string, string>();
  38. }
  39. protected CultureInfo UsCulture { get; } = new CultureInfo("en-US");
  40. /// <summary>
  41. /// Gets the logger.
  42. /// </summary>
  43. protected ILogger Logger { get; }
  44. protected IProviderManager ProviderManager { get; }
  45. protected virtual bool SupportsUrlAfterClosingXmlTag => false;
  46. protected virtual string MovieDbParserSearchString => "themoviedb.org/movie/";
  47. /// <summary>
  48. /// Fetches metadata for an item from one xml file.
  49. /// </summary>
  50. /// <param name="item">The item.</param>
  51. /// <param name="metadataFile">The metadata file.</param>
  52. /// <param name="cancellationToken">The cancellation token.</param>
  53. /// <exception cref="ArgumentNullException"><c>item</c> is <c>null</c>.</exception>
  54. /// <exception cref="ArgumentException"><c>metadataFile</c> is <c>null</c> or empty.</exception>
  55. public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
  56. {
  57. if (item == null)
  58. {
  59. throw new ArgumentNullException(nameof(item));
  60. }
  61. if (string.IsNullOrEmpty(metadataFile))
  62. {
  63. throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile));
  64. }
  65. _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  66. var idInfos = ProviderManager.GetExternalIdInfos(item.Item);
  67. foreach (var info in idInfos)
  68. {
  69. var id = info.Key + "Id";
  70. if (!_validProviderIds.ContainsKey(id))
  71. {
  72. _validProviderIds.Add(id, info.Key);
  73. }
  74. }
  75. // Additional Mappings
  76. _validProviderIds.Add("collectionnumber", "TmdbCollection");
  77. _validProviderIds.Add("tmdbcolid", "TmdbCollection");
  78. _validProviderIds.Add("imdb_id", "Imdb");
  79. Fetch(item, metadataFile, GetXmlReaderSettings(), cancellationToken);
  80. }
  81. /// <summary>
  82. /// Fetches the specified item.
  83. /// </summary>
  84. /// <param name="item">The item.</param>
  85. /// <param name="metadataFile">The metadata file.</param>
  86. /// <param name="settings">The settings.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. protected virtual void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
  89. {
  90. if (!SupportsUrlAfterClosingXmlTag)
  91. {
  92. using (var fileStream = File.OpenRead(metadataFile))
  93. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  94. using (var reader = XmlReader.Create(streamReader, settings))
  95. {
  96. item.ResetPeople();
  97. reader.MoveToContent();
  98. reader.Read();
  99. // Loop through each element
  100. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  101. {
  102. cancellationToken.ThrowIfCancellationRequested();
  103. if (reader.NodeType == XmlNodeType.Element)
  104. {
  105. FetchDataFromXmlNode(reader, item);
  106. }
  107. else
  108. {
  109. reader.Read();
  110. }
  111. }
  112. }
  113. return;
  114. }
  115. using (var fileStream = File.OpenRead(metadataFile))
  116. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  117. {
  118. item.ResetPeople();
  119. // Need to handle a url after the xml data
  120. // http://kodi.wiki/view/NFO_files/movies
  121. var xml = streamReader.ReadToEnd();
  122. // Find last closing Tag
  123. // Need to do this in two steps to account for random > characters after the closing xml
  124. var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
  125. // If closing tag exists, move to end of Tag
  126. if (index != -1)
  127. {
  128. index = xml.IndexOf('>', index);
  129. }
  130. if (index != -1)
  131. {
  132. var endingXml = xml.Substring(index);
  133. ParseProviderLinks(item.Item, endingXml);
  134. // If the file is just an imdb url, don't go any further
  135. if (index == 0)
  136. {
  137. return;
  138. }
  139. xml = xml.Substring(0, index + 1);
  140. }
  141. else
  142. {
  143. // If the file is just an Imdb url, handle that
  144. ParseProviderLinks(item.Item, xml);
  145. return;
  146. }
  147. // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
  148. try
  149. {
  150. using (var stringReader = new StringReader(xml))
  151. using (var reader = XmlReader.Create(stringReader, settings))
  152. {
  153. reader.MoveToContent();
  154. reader.Read();
  155. // Loop through each element
  156. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  157. {
  158. cancellationToken.ThrowIfCancellationRequested();
  159. if (reader.NodeType == XmlNodeType.Element)
  160. {
  161. FetchDataFromXmlNode(reader, item);
  162. }
  163. else
  164. {
  165. reader.Read();
  166. }
  167. }
  168. }
  169. }
  170. catch (XmlException)
  171. {
  172. }
  173. }
  174. }
  175. protected void ParseProviderLinks(T item, string xml)
  176. {
  177. // Look for a match for the Regex pattern "tt" followed by 7 or 8 digits
  178. var m = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.IgnoreCase);
  179. if (m.Success)
  180. {
  181. item.SetProviderId(MetadataProvider.Imdb, m.Value);
  182. }
  183. // Support Tmdb
  184. // https://www.themoviedb.org/movie/30287-fallo
  185. var srch = MovieDbParserSearchString;
  186. var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  187. if (index != -1)
  188. {
  189. var tmdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/');
  190. index = tmdbId.IndexOf('-');
  191. if (index != -1)
  192. {
  193. tmdbId = tmdbId.Slice(0, index);
  194. }
  195. if (!tmdbId.IsEmpty
  196. && !tmdbId.IsWhiteSpace()
  197. && int.TryParse(tmdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
  198. {
  199. item.SetProviderId(MetadataProvider.Tmdb, value.ToString(UsCulture));
  200. }
  201. }
  202. if (item is Series)
  203. {
  204. srch = "thetvdb.com/?tab=series&id=";
  205. index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  206. if (index != -1)
  207. {
  208. var tvdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/');
  209. if (!tvdbId.IsEmpty
  210. && !tvdbId.IsWhiteSpace()
  211. && int.TryParse(tvdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
  212. {
  213. item.SetProviderId(MetadataProvider.Tvdb, value.ToString(UsCulture));
  214. }
  215. }
  216. }
  217. }
  218. protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
  219. {
  220. var item = itemResult.Item;
  221. switch (reader.Name)
  222. {
  223. // DateCreated
  224. case "dateadded":
  225. {
  226. var val = reader.ReadElementContentAsString();
  227. if (!string.IsNullOrWhiteSpace(val))
  228. {
  229. if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var added))
  230. {
  231. item.DateCreated = added.ToUniversalTime();
  232. }
  233. else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  234. {
  235. item.DateCreated = added.ToUniversalTime();
  236. }
  237. else
  238. {
  239. Logger.LogWarning("Invalid Added value found: " + val);
  240. }
  241. }
  242. break;
  243. }
  244. case "originaltitle":
  245. {
  246. var val = reader.ReadElementContentAsString();
  247. if (!string.IsNullOrEmpty(val))
  248. {
  249. item.OriginalTitle = val;
  250. }
  251. break;
  252. }
  253. case "title":
  254. case "localtitle":
  255. item.Name = reader.ReadElementContentAsString();
  256. break;
  257. case "criticrating":
  258. {
  259. var text = reader.ReadElementContentAsString();
  260. if (!string.IsNullOrEmpty(text))
  261. {
  262. if (float.TryParse(text, NumberStyles.Any, UsCulture, out var value))
  263. {
  264. item.CriticRating = value;
  265. }
  266. }
  267. break;
  268. }
  269. case "sorttitle":
  270. {
  271. var val = reader.ReadElementContentAsString();
  272. if (!string.IsNullOrWhiteSpace(val))
  273. {
  274. item.ForcedSortName = val;
  275. }
  276. break;
  277. }
  278. case "biography":
  279. case "plot":
  280. case "review":
  281. {
  282. var val = reader.ReadElementContentAsString();
  283. if (!string.IsNullOrWhiteSpace(val))
  284. {
  285. item.Overview = val;
  286. }
  287. break;
  288. }
  289. case "language":
  290. {
  291. var val = reader.ReadElementContentAsString();
  292. item.PreferredMetadataLanguage = val;
  293. break;
  294. }
  295. case "countrycode":
  296. {
  297. var val = reader.ReadElementContentAsString();
  298. item.PreferredMetadataCountryCode = val;
  299. break;
  300. }
  301. case "lockedfields":
  302. {
  303. var val = reader.ReadElementContentAsString();
  304. if (!string.IsNullOrWhiteSpace(val))
  305. {
  306. item.LockedFields = val.Split('|').Select(i =>
  307. {
  308. if (Enum.TryParse(i, true, out MetadataField field))
  309. {
  310. return (MetadataField?)field;
  311. }
  312. return null;
  313. }).OfType<MetadataField>().ToArray();
  314. }
  315. break;
  316. }
  317. case "tagline":
  318. {
  319. var val = reader.ReadElementContentAsString();
  320. if (!string.IsNullOrWhiteSpace(val))
  321. {
  322. item.Tagline = val;
  323. }
  324. break;
  325. }
  326. case "country":
  327. {
  328. var val = reader.ReadElementContentAsString();
  329. if (!string.IsNullOrWhiteSpace(val))
  330. {
  331. item.ProductionLocations = val.Split('/')
  332. .Select(i => i.Trim())
  333. .Where(i => !string.IsNullOrWhiteSpace(i))
  334. .ToArray();
  335. }
  336. break;
  337. }
  338. case "mpaa":
  339. {
  340. var rating = reader.ReadElementContentAsString();
  341. if (!string.IsNullOrWhiteSpace(rating))
  342. {
  343. item.OfficialRating = rating;
  344. }
  345. break;
  346. }
  347. case "customrating":
  348. {
  349. var val = reader.ReadElementContentAsString();
  350. if (!string.IsNullOrWhiteSpace(val))
  351. {
  352. item.CustomRating = val;
  353. }
  354. break;
  355. }
  356. case "runtime":
  357. {
  358. var text = reader.ReadElementContentAsString();
  359. if (!string.IsNullOrWhiteSpace(text))
  360. {
  361. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, UsCulture, out var runtime))
  362. {
  363. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  364. }
  365. }
  366. break;
  367. }
  368. case "aspectratio":
  369. {
  370. var val = reader.ReadElementContentAsString();
  371. if (!string.IsNullOrWhiteSpace(val)
  372. && item is IHasAspectRatio hasAspectRatio)
  373. {
  374. hasAspectRatio.AspectRatio = val;
  375. }
  376. break;
  377. }
  378. case "lockdata":
  379. {
  380. var val = reader.ReadElementContentAsString();
  381. if (!string.IsNullOrWhiteSpace(val))
  382. {
  383. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  384. }
  385. break;
  386. }
  387. case "studio":
  388. {
  389. var val = reader.ReadElementContentAsString();
  390. if (!string.IsNullOrWhiteSpace(val))
  391. {
  392. item.AddStudio(val);
  393. }
  394. break;
  395. }
  396. case "director":
  397. {
  398. var val = reader.ReadElementContentAsString();
  399. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  400. {
  401. if (string.IsNullOrWhiteSpace(p.Name))
  402. {
  403. continue;
  404. }
  405. itemResult.AddPerson(p);
  406. }
  407. break;
  408. }
  409. case "credits":
  410. {
  411. var val = reader.ReadElementContentAsString();
  412. if (!string.IsNullOrWhiteSpace(val))
  413. {
  414. var parts = val.Split('/').Select(i => i.Trim())
  415. .Where(i => !string.IsNullOrEmpty(i));
  416. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  417. {
  418. if (string.IsNullOrWhiteSpace(p.Name))
  419. {
  420. continue;
  421. }
  422. itemResult.AddPerson(p);
  423. }
  424. }
  425. break;
  426. }
  427. case "writer":
  428. {
  429. var val = reader.ReadElementContentAsString();
  430. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  431. {
  432. if (string.IsNullOrWhiteSpace(p.Name))
  433. {
  434. continue;
  435. }
  436. itemResult.AddPerson(p);
  437. }
  438. break;
  439. }
  440. case "actor":
  441. {
  442. if (!reader.IsEmptyElement)
  443. {
  444. using (var subtree = reader.ReadSubtree())
  445. {
  446. var person = GetPersonFromXmlNode(subtree);
  447. if (!string.IsNullOrWhiteSpace(person.Name))
  448. {
  449. itemResult.AddPerson(person);
  450. }
  451. }
  452. }
  453. else
  454. {
  455. reader.Read();
  456. }
  457. break;
  458. }
  459. case "trailer":
  460. {
  461. var val = reader.ReadElementContentAsString();
  462. if (!string.IsNullOrWhiteSpace(val))
  463. {
  464. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", BaseNfoSaver.YouTubeWatchUrl, StringComparison.OrdinalIgnoreCase);
  465. item.AddTrailerUrl(val);
  466. }
  467. break;
  468. }
  469. case "displayorder":
  470. {
  471. var val = reader.ReadElementContentAsString();
  472. var hasDisplayOrder = item as IHasDisplayOrder;
  473. if (hasDisplayOrder != null)
  474. {
  475. if (!string.IsNullOrWhiteSpace(val))
  476. {
  477. hasDisplayOrder.DisplayOrder = val;
  478. }
  479. }
  480. break;
  481. }
  482. case "year":
  483. {
  484. var val = reader.ReadElementContentAsString();
  485. if (!string.IsNullOrWhiteSpace(val))
  486. {
  487. if (int.TryParse(val, out var productionYear) && productionYear > 1850)
  488. {
  489. item.ProductionYear = productionYear;
  490. }
  491. }
  492. break;
  493. }
  494. case "rating":
  495. {
  496. var rating = reader.ReadElementContentAsString();
  497. if (!string.IsNullOrWhiteSpace(rating))
  498. {
  499. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  500. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
  501. {
  502. item.CommunityRating = val;
  503. }
  504. }
  505. break;
  506. }
  507. case "ratings":
  508. {
  509. if (!reader.IsEmptyElement)
  510. {
  511. using var subtree = reader.ReadSubtree();
  512. FetchFromRatingsNode(subtree, item);
  513. }
  514. else
  515. {
  516. reader.Read();
  517. }
  518. break;
  519. }
  520. case "aired":
  521. case "formed":
  522. case "premiered":
  523. case "releasedate":
  524. {
  525. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  526. var val = reader.ReadElementContentAsString();
  527. if (!string.IsNullOrWhiteSpace(val))
  528. {
  529. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
  530. {
  531. item.PremiereDate = date.ToUniversalTime();
  532. item.ProductionYear = date.Year;
  533. }
  534. }
  535. break;
  536. }
  537. case "enddate":
  538. {
  539. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  540. var val = reader.ReadElementContentAsString();
  541. if (!string.IsNullOrWhiteSpace(val))
  542. {
  543. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
  544. {
  545. item.EndDate = date.ToUniversalTime();
  546. }
  547. }
  548. break;
  549. }
  550. case "genre":
  551. {
  552. var val = reader.ReadElementContentAsString();
  553. if (!string.IsNullOrWhiteSpace(val))
  554. {
  555. var parts = val.Split('/')
  556. .Select(i => i.Trim())
  557. .Where(i => !string.IsNullOrWhiteSpace(i));
  558. foreach (var p in parts)
  559. {
  560. item.AddGenre(p);
  561. }
  562. }
  563. break;
  564. }
  565. case "style":
  566. case "tag":
  567. {
  568. var val = reader.ReadElementContentAsString();
  569. if (!string.IsNullOrWhiteSpace(val))
  570. {
  571. item.AddTag(val);
  572. }
  573. break;
  574. }
  575. case "fileinfo":
  576. {
  577. if (!reader.IsEmptyElement)
  578. {
  579. using (var subtree = reader.ReadSubtree())
  580. {
  581. FetchFromFileInfoNode(subtree, item);
  582. }
  583. }
  584. else
  585. {
  586. reader.Read();
  587. }
  588. break;
  589. }
  590. default:
  591. string readerName = reader.Name;
  592. if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
  593. {
  594. var id = reader.ReadElementContentAsString();
  595. if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
  596. {
  597. item.SetProviderId(providerIdValue, id);
  598. }
  599. }
  600. else
  601. {
  602. reader.Skip();
  603. }
  604. break;
  605. }
  606. }
  607. private void FetchFromFileInfoNode(XmlReader reader, T item)
  608. {
  609. reader.MoveToContent();
  610. reader.Read();
  611. // Loop through each element
  612. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  613. {
  614. if (reader.NodeType == XmlNodeType.Element)
  615. {
  616. switch (reader.Name)
  617. {
  618. case "streamdetails":
  619. {
  620. if (reader.IsEmptyElement)
  621. {
  622. reader.Read();
  623. continue;
  624. }
  625. using (var subtree = reader.ReadSubtree())
  626. {
  627. FetchFromStreamDetailsNode(subtree, item);
  628. }
  629. break;
  630. }
  631. default:
  632. reader.Skip();
  633. break;
  634. }
  635. }
  636. else
  637. {
  638. reader.Read();
  639. }
  640. }
  641. }
  642. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  643. {
  644. reader.MoveToContent();
  645. reader.Read();
  646. // Loop through each element
  647. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  648. {
  649. if (reader.NodeType == XmlNodeType.Element)
  650. {
  651. switch (reader.Name)
  652. {
  653. case "video":
  654. {
  655. if (reader.IsEmptyElement)
  656. {
  657. reader.Read();
  658. continue;
  659. }
  660. using (var subtree = reader.ReadSubtree())
  661. {
  662. FetchFromVideoNode(subtree, item);
  663. }
  664. break;
  665. }
  666. default:
  667. reader.Skip();
  668. break;
  669. }
  670. }
  671. else
  672. {
  673. reader.Read();
  674. }
  675. }
  676. }
  677. private void FetchFromVideoNode(XmlReader reader, T item)
  678. {
  679. reader.MoveToContent();
  680. reader.Read();
  681. // Loop through each element
  682. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  683. {
  684. if (reader.NodeType == XmlNodeType.Element)
  685. {
  686. switch (reader.Name)
  687. {
  688. case "format3d":
  689. {
  690. var val = reader.ReadElementContentAsString();
  691. var video = item as Video;
  692. if (video != null)
  693. {
  694. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  695. {
  696. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  697. }
  698. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  699. {
  700. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  701. }
  702. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  703. {
  704. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  705. }
  706. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  707. {
  708. video.Video3DFormat = Video3DFormat.FullSideBySide;
  709. }
  710. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  711. {
  712. video.Video3DFormat = Video3DFormat.MVC;
  713. }
  714. }
  715. break;
  716. }
  717. default:
  718. reader.Skip();
  719. break;
  720. }
  721. }
  722. else
  723. {
  724. reader.Read();
  725. }
  726. }
  727. }
  728. private void FetchFromRatingsNode(XmlReader reader, T item)
  729. {
  730. reader.MoveToContent();
  731. reader.Read();
  732. // Loop through each element
  733. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  734. {
  735. if (reader.NodeType == XmlNodeType.Element)
  736. {
  737. switch (reader.Name)
  738. {
  739. case "rating":
  740. {
  741. if (reader.IsEmptyElement)
  742. {
  743. reader.Read();
  744. continue;
  745. }
  746. var ratingName = reader.GetAttribute("name");
  747. using var subtree = reader.ReadSubtree();
  748. FetchFromRatingNode(subtree, item, ratingName);
  749. break;
  750. }
  751. default:
  752. reader.Skip();
  753. break;
  754. }
  755. }
  756. else
  757. {
  758. reader.Read();
  759. }
  760. }
  761. }
  762. private void FetchFromRatingNode(XmlReader reader, T item, string? ratingName)
  763. {
  764. reader.MoveToContent();
  765. reader.Read();
  766. // Loop through each element
  767. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  768. {
  769. if (reader.NodeType == XmlNodeType.Element)
  770. {
  771. switch (reader.Name)
  772. {
  773. case "value":
  774. var val = reader.ReadElementContentAsString();
  775. if (!string.IsNullOrWhiteSpace(val))
  776. {
  777. if (float.TryParse(val, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue))
  778. {
  779. // if ratingName contains tomato --> assume critic rating
  780. if (ratingName != null &&
  781. ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase) &&
  782. !ratingName.Contains("audience", StringComparison.OrdinalIgnoreCase))
  783. {
  784. item.CriticRating = ratingValue;
  785. }
  786. else
  787. {
  788. item.CommunityRating = ratingValue;
  789. }
  790. }
  791. }
  792. break;
  793. default:
  794. reader.Skip();
  795. break;
  796. }
  797. }
  798. else
  799. {
  800. reader.Read();
  801. }
  802. }
  803. }
  804. /// <summary>
  805. /// Gets the persons from XML node.
  806. /// </summary>
  807. /// <param name="reader">The reader.</param>
  808. /// <returns>IEnumerable{PersonInfo}.</returns>
  809. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  810. {
  811. var name = string.Empty;
  812. var type = PersonType.Actor; // If type is not specified assume actor
  813. var role = string.Empty;
  814. int? sortOrder = null;
  815. reader.MoveToContent();
  816. reader.Read();
  817. // Loop through each element
  818. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  819. {
  820. if (reader.NodeType == XmlNodeType.Element)
  821. {
  822. switch (reader.Name)
  823. {
  824. case "name":
  825. name = reader.ReadElementContentAsString() ?? string.Empty;
  826. break;
  827. case "role":
  828. {
  829. var val = reader.ReadElementContentAsString();
  830. if (!string.IsNullOrWhiteSpace(val))
  831. {
  832. role = val;
  833. }
  834. break;
  835. }
  836. case "sortorder":
  837. {
  838. var val = reader.ReadElementContentAsString();
  839. if (!string.IsNullOrWhiteSpace(val))
  840. {
  841. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  842. {
  843. sortOrder = intVal;
  844. }
  845. }
  846. break;
  847. }
  848. default:
  849. reader.Skip();
  850. break;
  851. }
  852. }
  853. else
  854. {
  855. reader.Read();
  856. }
  857. }
  858. return new PersonInfo
  859. {
  860. Name = name.Trim(),
  861. Role = role,
  862. Type = type,
  863. SortOrder = sortOrder
  864. };
  865. }
  866. internal XmlReaderSettings GetXmlReaderSettings()
  867. => new XmlReaderSettings()
  868. {
  869. ValidationType = ValidationType.None,
  870. CheckCharacters = false,
  871. IgnoreProcessingInstructions = true,
  872. IgnoreComments = true
  873. };
  874. /// <summary>
  875. /// Used to split names of comma or pipe delimeted genres and people.
  876. /// </summary>
  877. /// <param name="value">The value.</param>
  878. /// <returns>IEnumerable{System.String}.</returns>
  879. private IEnumerable<string> SplitNames(string value)
  880. {
  881. value = value ?? string.Empty;
  882. // Only split by comma if there is no pipe in the string
  883. // We have to be careful to not split names like Matthew, Jr.
  884. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  885. ? new[] { ',' }
  886. : new[] { '|', ';' };
  887. value = value.Trim().Trim(separator);
  888. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  889. }
  890. }
  891. }