BaseNfoParser.cs 43 KB

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