BaseNfoParser.cs 48 KB

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