BaseNfoParser.cs 43 KB

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