BaseNfoParser.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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.Item == null)
  58. {
  59. throw new ArgumentException("Item can't be null.", nameof(item));
  60. }
  61. if (string.IsNullOrEmpty(metadataFile))
  62. {
  63. throw new ArgumentException("The metadata filepath was empty.", 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.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var added))
  230. {
  231. item.DateCreated = added.ToUniversalTime();
  232. }
  233. else
  234. {
  235. Logger.LogWarning("Invalid Added value found: {Value}", val);
  236. }
  237. }
  238. break;
  239. }
  240. case "originaltitle":
  241. {
  242. var val = reader.ReadElementContentAsString();
  243. if (!string.IsNullOrEmpty(val))
  244. {
  245. item.OriginalTitle = val;
  246. }
  247. break;
  248. }
  249. case "name":
  250. case "title":
  251. case "localtitle":
  252. item.Name = reader.ReadElementContentAsString();
  253. break;
  254. case "sortname":
  255. item.SortName = 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. item.Tagline = reader.ReadElementContentAsString();
  319. break;
  320. case "country":
  321. {
  322. var val = reader.ReadElementContentAsString();
  323. if (!string.IsNullOrWhiteSpace(val))
  324. {
  325. item.ProductionLocations = val.Split('/')
  326. .Select(i => i.Trim())
  327. .Where(i => !string.IsNullOrWhiteSpace(i))
  328. .ToArray();
  329. }
  330. break;
  331. }
  332. case "mpaa":
  333. {
  334. var rating = reader.ReadElementContentAsString();
  335. if (!string.IsNullOrWhiteSpace(rating))
  336. {
  337. item.OfficialRating = rating;
  338. }
  339. break;
  340. }
  341. case "customrating":
  342. {
  343. var val = reader.ReadElementContentAsString();
  344. if (!string.IsNullOrWhiteSpace(val))
  345. {
  346. item.CustomRating = val;
  347. }
  348. break;
  349. }
  350. case "runtime":
  351. {
  352. var text = reader.ReadElementContentAsString();
  353. if (!string.IsNullOrWhiteSpace(text))
  354. {
  355. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, UsCulture, out var runtime))
  356. {
  357. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  358. }
  359. }
  360. break;
  361. }
  362. case "aspectratio":
  363. {
  364. var val = reader.ReadElementContentAsString();
  365. if (!string.IsNullOrWhiteSpace(val)
  366. && item is IHasAspectRatio hasAspectRatio)
  367. {
  368. hasAspectRatio.AspectRatio = val;
  369. }
  370. break;
  371. }
  372. case "lockdata":
  373. {
  374. var val = reader.ReadElementContentAsString();
  375. if (!string.IsNullOrWhiteSpace(val))
  376. {
  377. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  378. }
  379. break;
  380. }
  381. case "studio":
  382. {
  383. var val = reader.ReadElementContentAsString();
  384. if (!string.IsNullOrWhiteSpace(val))
  385. {
  386. item.AddStudio(val);
  387. }
  388. break;
  389. }
  390. case "director":
  391. {
  392. var val = reader.ReadElementContentAsString();
  393. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  394. {
  395. if (string.IsNullOrWhiteSpace(p.Name))
  396. {
  397. continue;
  398. }
  399. itemResult.AddPerson(p);
  400. }
  401. break;
  402. }
  403. case "credits":
  404. {
  405. var val = reader.ReadElementContentAsString();
  406. if (!string.IsNullOrWhiteSpace(val))
  407. {
  408. var parts = val.Split('/').Select(i => i.Trim())
  409. .Where(i => !string.IsNullOrEmpty(i));
  410. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  411. {
  412. if (string.IsNullOrWhiteSpace(p.Name))
  413. {
  414. continue;
  415. }
  416. itemResult.AddPerson(p);
  417. }
  418. }
  419. break;
  420. }
  421. case "writer":
  422. {
  423. var val = reader.ReadElementContentAsString();
  424. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  425. {
  426. if (string.IsNullOrWhiteSpace(p.Name))
  427. {
  428. continue;
  429. }
  430. itemResult.AddPerson(p);
  431. }
  432. break;
  433. }
  434. case "actor":
  435. {
  436. if (!reader.IsEmptyElement)
  437. {
  438. using (var subtree = reader.ReadSubtree())
  439. {
  440. var person = GetPersonFromXmlNode(subtree);
  441. if (!string.IsNullOrWhiteSpace(person.Name))
  442. {
  443. itemResult.AddPerson(person);
  444. }
  445. }
  446. }
  447. else
  448. {
  449. reader.Read();
  450. }
  451. break;
  452. }
  453. case "trailer":
  454. {
  455. var val = reader.ReadElementContentAsString();
  456. if (!string.IsNullOrWhiteSpace(val))
  457. {
  458. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", BaseNfoSaver.YouTubeWatchUrl, StringComparison.OrdinalIgnoreCase);
  459. item.AddTrailerUrl(val);
  460. }
  461. break;
  462. }
  463. case "displayorder":
  464. {
  465. var val = reader.ReadElementContentAsString();
  466. var hasDisplayOrder = item as IHasDisplayOrder;
  467. if (hasDisplayOrder != null)
  468. {
  469. if (!string.IsNullOrWhiteSpace(val))
  470. {
  471. hasDisplayOrder.DisplayOrder = val;
  472. }
  473. }
  474. break;
  475. }
  476. case "year":
  477. {
  478. var val = reader.ReadElementContentAsString();
  479. if (!string.IsNullOrWhiteSpace(val))
  480. {
  481. if (int.TryParse(val, out var productionYear) && productionYear > 1850)
  482. {
  483. item.ProductionYear = productionYear;
  484. }
  485. }
  486. break;
  487. }
  488. case "rating":
  489. {
  490. var rating = reader.ReadElementContentAsString();
  491. if (!string.IsNullOrWhiteSpace(rating))
  492. {
  493. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  494. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
  495. {
  496. item.CommunityRating = val;
  497. }
  498. }
  499. break;
  500. }
  501. case "aired":
  502. case "formed":
  503. case "premiered":
  504. case "releasedate":
  505. {
  506. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  507. var val = reader.ReadElementContentAsString();
  508. if (!string.IsNullOrWhiteSpace(val))
  509. {
  510. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  511. {
  512. item.PremiereDate = date.ToUniversalTime();
  513. item.ProductionYear = date.Year;
  514. }
  515. }
  516. break;
  517. }
  518. case "enddate":
  519. {
  520. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  521. var val = reader.ReadElementContentAsString();
  522. if (!string.IsNullOrWhiteSpace(val))
  523. {
  524. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  525. {
  526. item.EndDate = date.ToUniversalTime();
  527. }
  528. }
  529. break;
  530. }
  531. case "genre":
  532. {
  533. var val = reader.ReadElementContentAsString();
  534. if (!string.IsNullOrWhiteSpace(val))
  535. {
  536. var parts = val.Split('/')
  537. .Select(i => i.Trim())
  538. .Where(i => !string.IsNullOrWhiteSpace(i));
  539. foreach (var p in parts)
  540. {
  541. item.AddGenre(p);
  542. }
  543. }
  544. break;
  545. }
  546. case "style":
  547. case "tag":
  548. {
  549. var val = reader.ReadElementContentAsString();
  550. if (!string.IsNullOrWhiteSpace(val))
  551. {
  552. item.AddTag(val);
  553. }
  554. break;
  555. }
  556. case "fileinfo":
  557. {
  558. if (!reader.IsEmptyElement)
  559. {
  560. using (var subtree = reader.ReadSubtree())
  561. {
  562. FetchFromFileInfoNode(subtree, item);
  563. }
  564. }
  565. else
  566. {
  567. reader.Read();
  568. }
  569. break;
  570. }
  571. case "uniqueid":
  572. {
  573. if (reader.IsEmptyElement)
  574. {
  575. reader.Read();
  576. break;
  577. }
  578. var provider = reader.GetAttribute("type");
  579. var id = reader.ReadElementContentAsString();
  580. if (!string.IsNullOrWhiteSpace(provider) && !string.IsNullOrWhiteSpace(id))
  581. {
  582. item.SetProviderId(provider, id);
  583. }
  584. break;
  585. }
  586. default:
  587. string readerName = reader.Name;
  588. if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
  589. {
  590. var id = reader.ReadElementContentAsString();
  591. if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
  592. {
  593. item.SetProviderId(providerIdValue, id);
  594. }
  595. }
  596. else
  597. {
  598. reader.Skip();
  599. }
  600. break;
  601. }
  602. }
  603. private void FetchFromFileInfoNode(XmlReader reader, T item)
  604. {
  605. reader.MoveToContent();
  606. reader.Read();
  607. // Loop through each element
  608. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  609. {
  610. if (reader.NodeType == XmlNodeType.Element)
  611. {
  612. switch (reader.Name)
  613. {
  614. case "streamdetails":
  615. {
  616. if (reader.IsEmptyElement)
  617. {
  618. reader.Read();
  619. continue;
  620. }
  621. using (var subtree = reader.ReadSubtree())
  622. {
  623. FetchFromStreamDetailsNode(subtree, item);
  624. }
  625. break;
  626. }
  627. default:
  628. reader.Skip();
  629. break;
  630. }
  631. }
  632. else
  633. {
  634. reader.Read();
  635. }
  636. }
  637. }
  638. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  639. {
  640. reader.MoveToContent();
  641. reader.Read();
  642. // Loop through each element
  643. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  644. {
  645. if (reader.NodeType == XmlNodeType.Element)
  646. {
  647. switch (reader.Name)
  648. {
  649. case "video":
  650. {
  651. if (reader.IsEmptyElement)
  652. {
  653. reader.Read();
  654. continue;
  655. }
  656. using (var subtree = reader.ReadSubtree())
  657. {
  658. FetchFromVideoNode(subtree, item);
  659. }
  660. break;
  661. }
  662. case "subtitle":
  663. {
  664. if (reader.IsEmptyElement)
  665. {
  666. reader.Read();
  667. continue;
  668. }
  669. using (var subtree = reader.ReadSubtree())
  670. {
  671. FetchFromSubtitleNode(subtree, item);
  672. }
  673. break;
  674. }
  675. default:
  676. reader.Skip();
  677. break;
  678. }
  679. }
  680. else
  681. {
  682. reader.Read();
  683. }
  684. }
  685. }
  686. private void FetchFromVideoNode(XmlReader reader, T item)
  687. {
  688. reader.MoveToContent();
  689. reader.Read();
  690. // Loop through each element
  691. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  692. {
  693. if (reader.NodeType == XmlNodeType.Element)
  694. {
  695. switch (reader.Name)
  696. {
  697. case "format3d":
  698. {
  699. var val = reader.ReadElementContentAsString();
  700. var video = item as Video;
  701. if (video != null)
  702. {
  703. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  704. {
  705. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  706. }
  707. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  708. {
  709. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  710. }
  711. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  712. {
  713. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  714. }
  715. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  716. {
  717. video.Video3DFormat = Video3DFormat.FullSideBySide;
  718. }
  719. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  720. {
  721. video.Video3DFormat = Video3DFormat.MVC;
  722. }
  723. }
  724. break;
  725. }
  726. case "aspect":
  727. {
  728. var val = reader.ReadElementContentAsString();
  729. if (item is Video video)
  730. {
  731. video.AspectRatio = val;
  732. }
  733. break;
  734. }
  735. case "width":
  736. {
  737. var val = reader.ReadElementContentAsInt();
  738. if (item is Video video)
  739. {
  740. video.Width = val;
  741. }
  742. break;
  743. }
  744. case "height":
  745. {
  746. var val = reader.ReadElementContentAsInt();
  747. if (item is Video video)
  748. {
  749. video.Height = val;
  750. }
  751. break;
  752. }
  753. case "durationinseconds":
  754. {
  755. var val = reader.ReadElementContentAsInt();
  756. if (item is Video video)
  757. {
  758. video.RunTimeTicks = new TimeSpan(0, 0, val).Ticks;
  759. }
  760. break;
  761. }
  762. default:
  763. reader.Skip();
  764. break;
  765. }
  766. }
  767. else
  768. {
  769. reader.Read();
  770. }
  771. }
  772. }
  773. private void FetchFromSubtitleNode(XmlReader reader, T item)
  774. {
  775. reader.MoveToContent();
  776. reader.Read();
  777. // Loop through each element
  778. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  779. {
  780. if (reader.NodeType == XmlNodeType.Element)
  781. {
  782. switch (reader.Name)
  783. {
  784. case "language":
  785. {
  786. _ = reader.ReadElementContentAsString();
  787. if (item is Video video)
  788. {
  789. video.HasSubtitles = true;
  790. }
  791. break;
  792. }
  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. string? imageUrl = null;
  816. reader.MoveToContent();
  817. reader.Read();
  818. // Loop through each element
  819. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  820. {
  821. if (reader.NodeType == XmlNodeType.Element)
  822. {
  823. switch (reader.Name)
  824. {
  825. case "name":
  826. name = reader.ReadElementContentAsString() ?? string.Empty;
  827. break;
  828. case "role":
  829. {
  830. var val = reader.ReadElementContentAsString();
  831. if (!string.IsNullOrWhiteSpace(val))
  832. {
  833. role = val;
  834. }
  835. break;
  836. }
  837. case "type":
  838. {
  839. var val = reader.ReadElementContentAsString();
  840. if (!string.IsNullOrWhiteSpace(val))
  841. {
  842. type = val switch
  843. {
  844. PersonType.Composer => PersonType.Composer,
  845. PersonType.Conductor => PersonType.Conductor,
  846. PersonType.Director => PersonType.Director,
  847. PersonType.Lyricist => PersonType.Lyricist,
  848. PersonType.Producer => PersonType.Producer,
  849. PersonType.Writer => PersonType.Writer,
  850. PersonType.GuestStar => PersonType.GuestStar,
  851. // unknown type --> actor
  852. _ => PersonType.Actor
  853. };
  854. }
  855. break;
  856. }
  857. case "order":
  858. case "sortorder":
  859. {
  860. var val = reader.ReadElementContentAsString();
  861. if (!string.IsNullOrWhiteSpace(val))
  862. {
  863. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  864. {
  865. sortOrder = intVal;
  866. }
  867. }
  868. break;
  869. }
  870. case "thumb":
  871. {
  872. var val = reader.ReadElementContentAsString();
  873. if (!string.IsNullOrWhiteSpace(val))
  874. {
  875. imageUrl = val;
  876. }
  877. break;
  878. }
  879. default:
  880. reader.Skip();
  881. break;
  882. }
  883. }
  884. else
  885. {
  886. reader.Read();
  887. }
  888. }
  889. return new PersonInfo
  890. {
  891. Name = name.Trim(),
  892. Role = role,
  893. Type = type,
  894. SortOrder = sortOrder,
  895. ImageUrl = imageUrl
  896. };
  897. }
  898. internal XmlReaderSettings GetXmlReaderSettings()
  899. => new XmlReaderSettings()
  900. {
  901. ValidationType = ValidationType.None,
  902. CheckCharacters = false,
  903. IgnoreProcessingInstructions = true,
  904. IgnoreComments = true
  905. };
  906. /// <summary>
  907. /// Used to split names of comma or pipe delimeted genres and people.
  908. /// </summary>
  909. /// <param name="value">The value.</param>
  910. /// <returns>IEnumerable{System.String}.</returns>
  911. private IEnumerable<string> SplitNames(string value)
  912. {
  913. value = value ?? string.Empty;
  914. // Only split by comma if there is no pipe in the string
  915. // We have to be careful to not split names like Matthew, Jr.
  916. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  917. ? new[] { ',' }
  918. : new[] { '|', ';' };
  919. value = value.Trim().Trim(separator);
  920. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  921. }
  922. }
  923. }