BaseNfoParser.cs 47 KB

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