BaseNfoParser.cs 42 KB

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