2
0

BaseNfoParser.cs 43 KB

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