BaseNfoParser.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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. if (!string.IsNullOrWhiteSpace(val))
  408. {
  409. item.Tagline = val;
  410. }
  411. break;
  412. }
  413. case "country":
  414. {
  415. var val = reader.ReadElementContentAsString();
  416. if (!string.IsNullOrWhiteSpace(val))
  417. {
  418. item.ProductionLocations = val.Split('/')
  419. .Select(i => i.Trim())
  420. .Where(i => !string.IsNullOrWhiteSpace(i))
  421. .ToList();
  422. }
  423. break;
  424. }
  425. case "mpaa":
  426. {
  427. var rating = reader.ReadElementContentAsString();
  428. if (!string.IsNullOrWhiteSpace(rating))
  429. {
  430. item.OfficialRating = rating;
  431. }
  432. break;
  433. }
  434. case "mpaadescription":
  435. {
  436. var rating = reader.ReadElementContentAsString();
  437. if (!string.IsNullOrWhiteSpace(rating))
  438. {
  439. item.OfficialRatingDescription = rating;
  440. }
  441. break;
  442. }
  443. case "customrating":
  444. {
  445. var val = reader.ReadElementContentAsString();
  446. if (!string.IsNullOrWhiteSpace(val))
  447. {
  448. item.CustomRating = val;
  449. }
  450. break;
  451. }
  452. case "runtime":
  453. {
  454. var text = reader.ReadElementContentAsString();
  455. if (!string.IsNullOrWhiteSpace(text))
  456. {
  457. int runtime;
  458. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out runtime))
  459. {
  460. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  461. }
  462. }
  463. break;
  464. }
  465. case "aspectratio":
  466. {
  467. var val = reader.ReadElementContentAsString();
  468. var hasAspectRatio = item as IHasAspectRatio;
  469. if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
  470. {
  471. hasAspectRatio.AspectRatio = val;
  472. }
  473. break;
  474. }
  475. case "lockdata":
  476. {
  477. var val = reader.ReadElementContentAsString();
  478. if (!string.IsNullOrWhiteSpace(val))
  479. {
  480. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  481. }
  482. break;
  483. }
  484. case "studio":
  485. {
  486. var val = reader.ReadElementContentAsString();
  487. if (!string.IsNullOrWhiteSpace(val))
  488. {
  489. var parts = val.Split('/')
  490. .Select(i => i.Trim())
  491. .Where(i => !string.IsNullOrWhiteSpace(i));
  492. foreach (var p in parts)
  493. {
  494. item.AddStudio(p);
  495. }
  496. }
  497. break;
  498. }
  499. case "director":
  500. {
  501. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  502. {
  503. if (string.IsNullOrWhiteSpace(p.Name))
  504. {
  505. continue;
  506. }
  507. itemResult.AddPerson(p);
  508. }
  509. break;
  510. }
  511. case "credits":
  512. {
  513. var val = reader.ReadElementContentAsString();
  514. if (!string.IsNullOrWhiteSpace(val))
  515. {
  516. var parts = val.Split('/').Select(i => i.Trim())
  517. .Where(i => !string.IsNullOrEmpty(i));
  518. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  519. {
  520. if (string.IsNullOrWhiteSpace(p.Name))
  521. {
  522. continue;
  523. }
  524. itemResult.AddPerson(p);
  525. }
  526. }
  527. break;
  528. }
  529. case "writer":
  530. {
  531. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  532. {
  533. if (string.IsNullOrWhiteSpace(p.Name))
  534. {
  535. continue;
  536. }
  537. itemResult.AddPerson(p);
  538. }
  539. break;
  540. }
  541. case "actor":
  542. {
  543. using (var subtree = reader.ReadSubtree())
  544. {
  545. var person = GetPersonFromXmlNode(subtree);
  546. if (!string.IsNullOrWhiteSpace(person.Name))
  547. {
  548. itemResult.AddPerson(person);
  549. }
  550. }
  551. break;
  552. }
  553. case "trailer":
  554. {
  555. var val = reader.ReadElementContentAsString();
  556. var hasTrailer = item as IHasTrailers;
  557. if (hasTrailer != null)
  558. {
  559. if (!string.IsNullOrWhiteSpace(val))
  560. {
  561. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "https://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  562. hasTrailer.AddTrailerUrl(val, false);
  563. }
  564. }
  565. break;
  566. }
  567. case "displayorder":
  568. {
  569. var val = reader.ReadElementContentAsString();
  570. var hasDisplayOrder = item as IHasDisplayOrder;
  571. if (hasDisplayOrder != null)
  572. {
  573. if (!string.IsNullOrWhiteSpace(val))
  574. {
  575. hasDisplayOrder.DisplayOrder = val;
  576. }
  577. }
  578. break;
  579. }
  580. case "year":
  581. {
  582. var val = reader.ReadElementContentAsString();
  583. if (!string.IsNullOrWhiteSpace(val))
  584. {
  585. int productionYear;
  586. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  587. {
  588. item.ProductionYear = productionYear;
  589. }
  590. }
  591. break;
  592. }
  593. case "rating":
  594. {
  595. var rating = reader.ReadElementContentAsString();
  596. if (!string.IsNullOrWhiteSpace(rating))
  597. {
  598. float val;
  599. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  600. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  601. {
  602. item.CommunityRating = val;
  603. }
  604. }
  605. break;
  606. }
  607. case "aired":
  608. case "formed":
  609. case "premiered":
  610. case "releasedate":
  611. {
  612. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  613. var val = reader.ReadElementContentAsString();
  614. if (!string.IsNullOrWhiteSpace(val))
  615. {
  616. DateTime date;
  617. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  618. {
  619. item.PremiereDate = date.ToUniversalTime();
  620. item.ProductionYear = date.Year;
  621. }
  622. }
  623. break;
  624. }
  625. case "enddate":
  626. {
  627. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  628. var val = reader.ReadElementContentAsString();
  629. if (!string.IsNullOrWhiteSpace(val))
  630. {
  631. DateTime date;
  632. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  633. {
  634. item.EndDate = date.ToUniversalTime();
  635. }
  636. }
  637. break;
  638. }
  639. case "votes":
  640. {
  641. var val = reader.ReadElementContentAsString();
  642. if (!string.IsNullOrWhiteSpace(val))
  643. {
  644. int num;
  645. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  646. {
  647. item.VoteCount = num;
  648. }
  649. }
  650. break;
  651. }
  652. case "genre":
  653. {
  654. var val = reader.ReadElementContentAsString();
  655. if (!string.IsNullOrWhiteSpace(val))
  656. {
  657. var parts = val.Split('/')
  658. .Select(i => i.Trim())
  659. .Where(i => !string.IsNullOrWhiteSpace(i));
  660. foreach (var p in parts)
  661. {
  662. item.AddGenre(p);
  663. }
  664. }
  665. break;
  666. }
  667. case "style":
  668. case "tag":
  669. {
  670. var val = reader.ReadElementContentAsString();
  671. if (!string.IsNullOrWhiteSpace(val))
  672. {
  673. item.AddTag(val);
  674. }
  675. break;
  676. }
  677. case "plotkeyword":
  678. {
  679. var val = reader.ReadElementContentAsString();
  680. if (!string.IsNullOrWhiteSpace(val))
  681. {
  682. item.AddKeyword(val);
  683. }
  684. break;
  685. }
  686. case "fileinfo":
  687. {
  688. using (var subtree = reader.ReadSubtree())
  689. {
  690. FetchFromFileInfoNode(subtree, item);
  691. }
  692. break;
  693. }
  694. case "watched":
  695. {
  696. var val = reader.ReadElementContentAsString();
  697. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  698. {
  699. bool parsedValue;
  700. if (bool.TryParse(val, out parsedValue))
  701. {
  702. var userData = GetOrAdd(itemResult, userDataUserId);
  703. userData.Played = parsedValue;
  704. }
  705. }
  706. break;
  707. }
  708. case "playcount":
  709. {
  710. var val = reader.ReadElementContentAsString();
  711. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  712. {
  713. int parsedValue;
  714. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  715. {
  716. var userData = GetOrAdd(itemResult, userDataUserId);
  717. userData.PlayCount = parsedValue;
  718. if (parsedValue > 0)
  719. {
  720. userData.Played = true;
  721. }
  722. }
  723. }
  724. break;
  725. }
  726. case "lastplayed":
  727. {
  728. var val = reader.ReadElementContentAsString();
  729. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  730. {
  731. DateTime parsedValue;
  732. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  733. {
  734. var userData = GetOrAdd(itemResult, userDataUserId);
  735. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  736. }
  737. }
  738. break;
  739. }
  740. case "resume":
  741. {
  742. using (var subtree = reader.ReadSubtree())
  743. {
  744. if (!string.IsNullOrWhiteSpace(userDataUserId))
  745. {
  746. var userData = GetOrAdd(itemResult, userDataUserId);
  747. FetchFromResumeNode(subtree, item, userData);
  748. }
  749. }
  750. break;
  751. }
  752. case "isuserfavorite":
  753. {
  754. var val = reader.ReadElementContentAsString();
  755. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  756. {
  757. bool parsedValue;
  758. if (bool.TryParse(val, out parsedValue))
  759. {
  760. var userData = GetOrAdd(itemResult, userDataUserId);
  761. userData.IsFavorite = parsedValue;
  762. }
  763. }
  764. break;
  765. }
  766. case "userrating":
  767. {
  768. var val = reader.ReadElementContentAsString();
  769. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  770. {
  771. double parsedValue;
  772. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  773. {
  774. var userData = GetOrAdd(itemResult, userDataUserId);
  775. userData.Rating = parsedValue;
  776. }
  777. }
  778. break;
  779. }
  780. default:
  781. reader.Skip();
  782. break;
  783. }
  784. }
  785. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  786. {
  787. return result.GetOrAddUserData(userId);
  788. }
  789. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  790. {
  791. reader.MoveToContent();
  792. while (reader.Read())
  793. {
  794. if (reader.NodeType == XmlNodeType.Element)
  795. {
  796. switch (reader.Name)
  797. {
  798. case "position":
  799. {
  800. var val = reader.ReadElementContentAsString();
  801. if (!string.IsNullOrWhiteSpace(val))
  802. {
  803. double parsedValue;
  804. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  805. {
  806. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  807. }
  808. }
  809. break;
  810. }
  811. default:
  812. reader.Skip();
  813. break;
  814. }
  815. }
  816. }
  817. }
  818. private void FetchFromFileInfoNode(XmlReader reader, T item)
  819. {
  820. reader.MoveToContent();
  821. while (reader.Read())
  822. {
  823. if (reader.NodeType == XmlNodeType.Element)
  824. {
  825. switch (reader.Name)
  826. {
  827. case "streamdetails":
  828. {
  829. using (var subtree = reader.ReadSubtree())
  830. {
  831. FetchFromStreamDetailsNode(subtree, item);
  832. }
  833. break;
  834. }
  835. default:
  836. reader.Skip();
  837. break;
  838. }
  839. }
  840. }
  841. }
  842. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  843. {
  844. reader.MoveToContent();
  845. while (reader.Read())
  846. {
  847. if (reader.NodeType == XmlNodeType.Element)
  848. {
  849. switch (reader.Name)
  850. {
  851. case "video":
  852. {
  853. using (var subtree = reader.ReadSubtree())
  854. {
  855. FetchFromVideoNode(subtree, item);
  856. }
  857. break;
  858. }
  859. default:
  860. reader.Skip();
  861. break;
  862. }
  863. }
  864. }
  865. }
  866. private void FetchFromVideoNode(XmlReader reader, T item)
  867. {
  868. reader.MoveToContent();
  869. while (reader.Read())
  870. {
  871. if (reader.NodeType == XmlNodeType.Element)
  872. {
  873. switch (reader.Name)
  874. {
  875. case "format3d":
  876. {
  877. var video = item as Video;
  878. if (video != null)
  879. {
  880. var val = reader.ReadElementContentAsString();
  881. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  882. {
  883. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  884. }
  885. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  886. {
  887. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  888. }
  889. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  890. {
  891. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  892. }
  893. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  894. {
  895. video.Video3DFormat = Video3DFormat.FullSideBySide;
  896. }
  897. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  898. {
  899. video.Video3DFormat = Video3DFormat.MVC;
  900. }
  901. }
  902. break;
  903. }
  904. default:
  905. reader.Skip();
  906. break;
  907. }
  908. }
  909. }
  910. }
  911. /// <summary>
  912. /// Gets the persons from XML node.
  913. /// </summary>
  914. /// <param name="reader">The reader.</param>
  915. /// <returns>IEnumerable{PersonInfo}.</returns>
  916. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  917. {
  918. var name = string.Empty;
  919. var type = PersonType.Actor; // If type is not specified assume actor
  920. var role = string.Empty;
  921. int? sortOrder = null;
  922. reader.MoveToContent();
  923. while (reader.Read())
  924. {
  925. if (reader.NodeType == XmlNodeType.Element)
  926. {
  927. switch (reader.Name)
  928. {
  929. case "name":
  930. name = reader.ReadElementContentAsString() ?? string.Empty;
  931. break;
  932. case "type":
  933. {
  934. var val = reader.ReadElementContentAsString();
  935. if (!string.IsNullOrWhiteSpace(val))
  936. {
  937. type = val;
  938. }
  939. break;
  940. }
  941. case "role":
  942. {
  943. var val = reader.ReadElementContentAsString();
  944. if (!string.IsNullOrWhiteSpace(val))
  945. {
  946. role = val;
  947. }
  948. break;
  949. }
  950. case "sortorder":
  951. {
  952. var val = reader.ReadElementContentAsString();
  953. if (!string.IsNullOrWhiteSpace(val))
  954. {
  955. int intVal;
  956. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  957. {
  958. sortOrder = intVal;
  959. }
  960. }
  961. break;
  962. }
  963. default:
  964. reader.Skip();
  965. break;
  966. }
  967. }
  968. }
  969. return new PersonInfo
  970. {
  971. Name = name.Trim(),
  972. Role = role,
  973. Type = type,
  974. SortOrder = sortOrder
  975. };
  976. }
  977. /// <summary>
  978. /// Used to split names of comma or pipe delimeted genres and people
  979. /// </summary>
  980. /// <param name="value">The value.</param>
  981. /// <returns>IEnumerable{System.String}.</returns>
  982. private IEnumerable<string> SplitNames(string value)
  983. {
  984. value = value ?? string.Empty;
  985. // Only split by comma if there is no pipe in the string
  986. // We have to be careful to not split names like Matthew, Jr.
  987. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  988. value = value.Trim().Trim(separator);
  989. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  990. }
  991. /// <summary>
  992. /// Provides an additional overload for string.split
  993. /// </summary>
  994. /// <param name="val">The val.</param>
  995. /// <param name="separators">The separators.</param>
  996. /// <param name="options">The options.</param>
  997. /// <returns>System.String[][].</returns>
  998. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  999. {
  1000. return val.Split(separators, options);
  1001. }
  1002. }
  1003. }