BaseNfoParser.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 "aired":
  508. case "formed":
  509. case "premiered":
  510. case "releasedate":
  511. {
  512. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  513. var val = reader.ReadElementContentAsString();
  514. if (!string.IsNullOrWhiteSpace(val))
  515. {
  516. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  517. {
  518. item.PremiereDate = date.ToUniversalTime();
  519. item.ProductionYear = date.Year;
  520. }
  521. }
  522. break;
  523. }
  524. case "enddate":
  525. {
  526. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  527. var val = reader.ReadElementContentAsString();
  528. if (!string.IsNullOrWhiteSpace(val))
  529. {
  530. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  531. {
  532. item.EndDate = date.ToUniversalTime();
  533. }
  534. }
  535. break;
  536. }
  537. case "genre":
  538. {
  539. var val = reader.ReadElementContentAsString();
  540. if (!string.IsNullOrWhiteSpace(val))
  541. {
  542. var parts = val.Split('/')
  543. .Select(i => i.Trim())
  544. .Where(i => !string.IsNullOrWhiteSpace(i));
  545. foreach (var p in parts)
  546. {
  547. item.AddGenre(p);
  548. }
  549. }
  550. break;
  551. }
  552. case "style":
  553. case "tag":
  554. {
  555. var val = reader.ReadElementContentAsString();
  556. if (!string.IsNullOrWhiteSpace(val))
  557. {
  558. item.AddTag(val);
  559. }
  560. break;
  561. }
  562. case "fileinfo":
  563. {
  564. if (!reader.IsEmptyElement)
  565. {
  566. using (var subtree = reader.ReadSubtree())
  567. {
  568. FetchFromFileInfoNode(subtree, item);
  569. }
  570. }
  571. else
  572. {
  573. reader.Read();
  574. }
  575. break;
  576. }
  577. default:
  578. string readerName = reader.Name;
  579. if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
  580. {
  581. var id = reader.ReadElementContentAsString();
  582. if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
  583. {
  584. item.SetProviderId(providerIdValue, id);
  585. }
  586. }
  587. else
  588. {
  589. reader.Skip();
  590. }
  591. break;
  592. }
  593. }
  594. private void FetchFromFileInfoNode(XmlReader reader, T item)
  595. {
  596. reader.MoveToContent();
  597. reader.Read();
  598. // Loop through each element
  599. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  600. {
  601. if (reader.NodeType == XmlNodeType.Element)
  602. {
  603. switch (reader.Name)
  604. {
  605. case "streamdetails":
  606. {
  607. if (reader.IsEmptyElement)
  608. {
  609. reader.Read();
  610. continue;
  611. }
  612. using (var subtree = reader.ReadSubtree())
  613. {
  614. FetchFromStreamDetailsNode(subtree, item);
  615. }
  616. break;
  617. }
  618. default:
  619. reader.Skip();
  620. break;
  621. }
  622. }
  623. else
  624. {
  625. reader.Read();
  626. }
  627. }
  628. }
  629. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  630. {
  631. reader.MoveToContent();
  632. reader.Read();
  633. // Loop through each element
  634. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  635. {
  636. if (reader.NodeType == XmlNodeType.Element)
  637. {
  638. switch (reader.Name)
  639. {
  640. case "video":
  641. {
  642. if (reader.IsEmptyElement)
  643. {
  644. reader.Read();
  645. continue;
  646. }
  647. using (var subtree = reader.ReadSubtree())
  648. {
  649. FetchFromVideoNode(subtree, item);
  650. }
  651. break;
  652. }
  653. case "subtitle":
  654. {
  655. if (reader.IsEmptyElement)
  656. {
  657. reader.Read();
  658. continue;
  659. }
  660. using (var subtree = reader.ReadSubtree())
  661. {
  662. FetchFromSubtitleNode(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. case "aspect":
  718. {
  719. var val = reader.ReadElementContentAsString();
  720. if (item is Video video)
  721. {
  722. video.AspectRatio = val;
  723. }
  724. break;
  725. }
  726. case "width":
  727. {
  728. var val = reader.ReadElementContentAsInt();
  729. if (item is Video video)
  730. {
  731. video.Width = val;
  732. }
  733. break;
  734. }
  735. case "height":
  736. {
  737. var val = reader.ReadElementContentAsInt();
  738. if (item is Video video)
  739. {
  740. video.Height = val;
  741. }
  742. break;
  743. }
  744. case "durationinseconds":
  745. {
  746. var val = reader.ReadElementContentAsInt();
  747. if (item is Video video)
  748. {
  749. video.RunTimeTicks = new TimeSpan(0, 0, val).Ticks;
  750. }
  751. break;
  752. }
  753. default:
  754. reader.Skip();
  755. break;
  756. }
  757. }
  758. else
  759. {
  760. reader.Read();
  761. }
  762. }
  763. }
  764. private void FetchFromSubtitleNode(XmlReader reader, T item)
  765. {
  766. reader.MoveToContent();
  767. reader.Read();
  768. // Loop through each element
  769. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  770. {
  771. if (reader.NodeType == XmlNodeType.Element)
  772. {
  773. switch (reader.Name)
  774. {
  775. case "language":
  776. {
  777. _ = reader.ReadElementContentAsString();
  778. if (item is Video video)
  779. {
  780. video.HasSubtitles = true;
  781. }
  782. break;
  783. }
  784. default:
  785. reader.Skip();
  786. break;
  787. }
  788. }
  789. else
  790. {
  791. reader.Read();
  792. }
  793. }
  794. }
  795. /// <summary>
  796. /// Gets the persons from XML node.
  797. /// </summary>
  798. /// <param name="reader">The reader.</param>
  799. /// <returns>IEnumerable{PersonInfo}.</returns>
  800. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  801. {
  802. var name = string.Empty;
  803. var type = PersonType.Actor; // If type is not specified assume actor
  804. var role = string.Empty;
  805. int? sortOrder = null;
  806. string? imageUrl = null;
  807. reader.MoveToContent();
  808. reader.Read();
  809. // Loop through each element
  810. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  811. {
  812. if (reader.NodeType == XmlNodeType.Element)
  813. {
  814. switch (reader.Name)
  815. {
  816. case "name":
  817. name = reader.ReadElementContentAsString() ?? string.Empty;
  818. break;
  819. case "role":
  820. {
  821. var val = reader.ReadElementContentAsString();
  822. if (!string.IsNullOrWhiteSpace(val))
  823. {
  824. role = val;
  825. }
  826. break;
  827. }
  828. case "order":
  829. case "sortorder":
  830. {
  831. var val = reader.ReadElementContentAsString();
  832. if (!string.IsNullOrWhiteSpace(val))
  833. {
  834. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  835. {
  836. sortOrder = intVal;
  837. }
  838. }
  839. break;
  840. }
  841. case "thumb":
  842. {
  843. var val = reader.ReadElementContentAsString();
  844. if (!string.IsNullOrWhiteSpace(val))
  845. {
  846. imageUrl = val;
  847. }
  848. break;
  849. }
  850. default:
  851. reader.Skip();
  852. break;
  853. }
  854. }
  855. else
  856. {
  857. reader.Read();
  858. }
  859. }
  860. return new PersonInfo
  861. {
  862. Name = name.Trim(),
  863. Role = role,
  864. Type = type,
  865. SortOrder = sortOrder,
  866. ImageUrl = imageUrl
  867. };
  868. }
  869. internal XmlReaderSettings GetXmlReaderSettings()
  870. => new XmlReaderSettings()
  871. {
  872. ValidationType = ValidationType.None,
  873. CheckCharacters = false,
  874. IgnoreProcessingInstructions = true,
  875. IgnoreComments = true
  876. };
  877. /// <summary>
  878. /// Used to split names of comma or pipe delimeted genres and people.
  879. /// </summary>
  880. /// <param name="value">The value.</param>
  881. /// <returns>IEnumerable{System.String}.</returns>
  882. private IEnumerable<string> SplitNames(string value)
  883. {
  884. value = value ?? string.Empty;
  885. // Only split by comma if there is no pipe in the string
  886. // We have to be careful to not split names like Matthew, Jr.
  887. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  888. ? new[] { ',' }
  889. : new[] { '|', ';' };
  890. value = value.Trim().Trim(separator);
  891. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  892. }
  893. }
  894. }