BaseNfoParser.cs 46 KB

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