BaseNfoParser.cs 43 KB

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