BaseNfoParser.cs 47 KB

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