2
0

BaseNfoParser.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. if (!string.IsNullOrWhiteSpace(person.Name))
  529. {
  530. itemResult.AddPerson(person);
  531. }
  532. }
  533. break;
  534. }
  535. case "trailer":
  536. {
  537. var val = reader.ReadElementContentAsString();
  538. var hasTrailer = item as IHasTrailers;
  539. if (hasTrailer != null)
  540. {
  541. if (!string.IsNullOrWhiteSpace(val))
  542. {
  543. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "http://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  544. hasTrailer.AddTrailerUrl(val, false);
  545. }
  546. }
  547. break;
  548. }
  549. case "displayorder":
  550. {
  551. var val = reader.ReadElementContentAsString();
  552. var hasDisplayOrder = item as IHasDisplayOrder;
  553. if (hasDisplayOrder != null)
  554. {
  555. if (!string.IsNullOrWhiteSpace(val))
  556. {
  557. hasDisplayOrder.DisplayOrder = val;
  558. }
  559. }
  560. break;
  561. }
  562. case "year":
  563. {
  564. var val = reader.ReadElementContentAsString();
  565. if (!string.IsNullOrWhiteSpace(val))
  566. {
  567. int productionYear;
  568. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  569. {
  570. item.ProductionYear = productionYear;
  571. }
  572. }
  573. break;
  574. }
  575. case "rating":
  576. {
  577. var rating = reader.ReadElementContentAsString();
  578. if (!string.IsNullOrWhiteSpace(rating))
  579. {
  580. float val;
  581. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  582. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  583. {
  584. item.CommunityRating = val;
  585. }
  586. }
  587. break;
  588. }
  589. case "aired":
  590. case "formed":
  591. case "premiered":
  592. case "releasedate":
  593. {
  594. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  595. var val = reader.ReadElementContentAsString();
  596. if (!string.IsNullOrWhiteSpace(val))
  597. {
  598. DateTime date;
  599. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  600. {
  601. item.PremiereDate = date.ToUniversalTime();
  602. item.ProductionYear = date.Year;
  603. }
  604. }
  605. break;
  606. }
  607. case "enddate":
  608. {
  609. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  610. var val = reader.ReadElementContentAsString();
  611. if (!string.IsNullOrWhiteSpace(val))
  612. {
  613. DateTime date;
  614. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  615. {
  616. item.EndDate = date.ToUniversalTime();
  617. }
  618. }
  619. break;
  620. }
  621. case "tvdbid":
  622. var tvdbId = reader.ReadElementContentAsString();
  623. if (!string.IsNullOrWhiteSpace(tvdbId))
  624. {
  625. item.SetProviderId(MetadataProviders.Tvdb, tvdbId);
  626. }
  627. break;
  628. case "votes":
  629. {
  630. var val = reader.ReadElementContentAsString();
  631. if (!string.IsNullOrWhiteSpace(val))
  632. {
  633. int num;
  634. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  635. {
  636. item.VoteCount = num;
  637. }
  638. }
  639. break;
  640. }
  641. case "musicbrainzalbumid":
  642. {
  643. var mbz = reader.ReadElementContentAsString();
  644. if (!string.IsNullOrWhiteSpace(mbz))
  645. {
  646. item.SetProviderId(MetadataProviders.MusicBrainzAlbum, mbz);
  647. }
  648. break;
  649. }
  650. case "musicbrainzalbumartistid":
  651. {
  652. var mbz = reader.ReadElementContentAsString();
  653. if (!string.IsNullOrWhiteSpace(mbz))
  654. {
  655. item.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mbz);
  656. }
  657. break;
  658. }
  659. case "musicbrainzartistid":
  660. {
  661. var mbz = reader.ReadElementContentAsString();
  662. if (!string.IsNullOrWhiteSpace(mbz))
  663. {
  664. item.SetProviderId(MetadataProviders.MusicBrainzArtist, mbz);
  665. }
  666. break;
  667. }
  668. case "musicbrainzreleasegroupid":
  669. {
  670. var mbz = reader.ReadElementContentAsString();
  671. if (!string.IsNullOrWhiteSpace(mbz))
  672. {
  673. item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mbz);
  674. }
  675. break;
  676. }
  677. case "tvrageid":
  678. {
  679. var id = reader.ReadElementContentAsString();
  680. if (!string.IsNullOrWhiteSpace(id))
  681. {
  682. item.SetProviderId(MetadataProviders.TvRage, id);
  683. }
  684. break;
  685. }
  686. case "audiodbartistid":
  687. {
  688. var id = reader.ReadElementContentAsString();
  689. if (!string.IsNullOrWhiteSpace(id))
  690. {
  691. item.SetProviderId(MetadataProviders.AudioDbArtist, id);
  692. }
  693. break;
  694. }
  695. case "audiodbalbumid":
  696. {
  697. var id = reader.ReadElementContentAsString();
  698. if (!string.IsNullOrWhiteSpace(id))
  699. {
  700. item.SetProviderId(MetadataProviders.AudioDbAlbum, id);
  701. }
  702. break;
  703. }
  704. case "rottentomatoesid":
  705. var rtId = reader.ReadElementContentAsString();
  706. if (!string.IsNullOrWhiteSpace(rtId))
  707. {
  708. item.SetProviderId(MetadataProviders.RottenTomatoes, rtId);
  709. }
  710. break;
  711. case "tmdbid":
  712. var tmdb = reader.ReadElementContentAsString();
  713. if (!string.IsNullOrWhiteSpace(tmdb))
  714. {
  715. item.SetProviderId(MetadataProviders.Tmdb, tmdb);
  716. }
  717. break;
  718. case "collectionnumber":
  719. var tmdbCollection = reader.ReadElementContentAsString();
  720. if (!string.IsNullOrWhiteSpace(tmdbCollection))
  721. {
  722. item.SetProviderId(MetadataProviders.TmdbCollection, tmdbCollection);
  723. }
  724. break;
  725. case "tvcomid":
  726. var TVcomId = reader.ReadElementContentAsString();
  727. if (!string.IsNullOrWhiteSpace(TVcomId))
  728. {
  729. item.SetProviderId(MetadataProviders.Tvcom, TVcomId);
  730. }
  731. break;
  732. case "zap2itid":
  733. var zap2ItId = reader.ReadElementContentAsString();
  734. if (!string.IsNullOrWhiteSpace(zap2ItId))
  735. {
  736. item.SetProviderId(MetadataProviders.Zap2It, zap2ItId);
  737. }
  738. break;
  739. case "imdb_id":
  740. case "imdbid":
  741. var imDbId = reader.ReadElementContentAsString();
  742. if (!string.IsNullOrWhiteSpace(imDbId))
  743. {
  744. item.SetProviderId(MetadataProviders.Imdb, imDbId);
  745. }
  746. break;
  747. case "genre":
  748. {
  749. var val = reader.ReadElementContentAsString();
  750. if (!string.IsNullOrWhiteSpace(val))
  751. {
  752. var parts = val.Split('/')
  753. .Select(i => i.Trim())
  754. .Where(i => !string.IsNullOrWhiteSpace(i));
  755. foreach (var p in parts)
  756. {
  757. item.AddGenre(p);
  758. }
  759. }
  760. break;
  761. }
  762. case "style":
  763. case "tag":
  764. {
  765. var val = reader.ReadElementContentAsString();
  766. if (!string.IsNullOrWhiteSpace(val))
  767. {
  768. var hasTags = item as IHasTags;
  769. if (hasTags != null)
  770. {
  771. hasTags.AddTag(val);
  772. }
  773. }
  774. break;
  775. }
  776. case "plotkeyword":
  777. {
  778. var val = reader.ReadElementContentAsString();
  779. var hasKeywords = item as IHasKeywords;
  780. if (hasKeywords != null)
  781. {
  782. if (!string.IsNullOrWhiteSpace(val))
  783. {
  784. hasKeywords.AddKeyword(val);
  785. }
  786. }
  787. break;
  788. }
  789. case "fileinfo":
  790. {
  791. using (var subtree = reader.ReadSubtree())
  792. {
  793. FetchFromFileInfoNode(subtree, item);
  794. }
  795. break;
  796. }
  797. case "watched":
  798. {
  799. var val = reader.ReadElementContentAsString();
  800. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  801. {
  802. bool parsedValue;
  803. if (bool.TryParse(val, out parsedValue))
  804. {
  805. var userData = GetOrAdd(itemResult, userDataUserId);
  806. userData.Played = parsedValue;
  807. }
  808. }
  809. break;
  810. }
  811. case "playcount":
  812. {
  813. var val = reader.ReadElementContentAsString();
  814. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  815. {
  816. int parsedValue;
  817. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  818. {
  819. var userData = GetOrAdd(itemResult, userDataUserId);
  820. userData.PlayCount = parsedValue;
  821. if (parsedValue > 0)
  822. {
  823. userData.Played = true;
  824. }
  825. }
  826. }
  827. break;
  828. }
  829. case "lastplayed":
  830. {
  831. var val = reader.ReadElementContentAsString();
  832. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  833. {
  834. DateTime parsedValue;
  835. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  836. {
  837. var userData = GetOrAdd(itemResult, userDataUserId);
  838. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  839. }
  840. }
  841. break;
  842. }
  843. case "resume":
  844. {
  845. using (var subtree = reader.ReadSubtree())
  846. {
  847. if (!string.IsNullOrWhiteSpace(userDataUserId))
  848. {
  849. var userData = GetOrAdd(itemResult, userDataUserId);
  850. FetchFromResumeNode(subtree, item, userData);
  851. }
  852. }
  853. break;
  854. }
  855. case "isuserfavorite":
  856. {
  857. var val = reader.ReadElementContentAsString();
  858. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  859. {
  860. bool parsedValue;
  861. if (bool.TryParse(val, out parsedValue))
  862. {
  863. var userData = GetOrAdd(itemResult, userDataUserId);
  864. userData.IsFavorite = parsedValue;
  865. }
  866. }
  867. break;
  868. }
  869. case "userrating":
  870. {
  871. var val = reader.ReadElementContentAsString();
  872. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  873. {
  874. double parsedValue;
  875. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  876. {
  877. var userData = GetOrAdd(itemResult, userDataUserId);
  878. userData.Rating = parsedValue;
  879. }
  880. }
  881. break;
  882. }
  883. default:
  884. reader.Skip();
  885. break;
  886. }
  887. }
  888. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  889. {
  890. return result.GetOrAddUserData(userId);
  891. }
  892. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  893. {
  894. reader.MoveToContent();
  895. while (reader.Read())
  896. {
  897. if (reader.NodeType == XmlNodeType.Element)
  898. {
  899. switch (reader.Name)
  900. {
  901. case "position":
  902. {
  903. var val = reader.ReadElementContentAsString();
  904. if (!string.IsNullOrWhiteSpace(val))
  905. {
  906. double parsedValue;
  907. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  908. {
  909. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  910. }
  911. }
  912. break;
  913. }
  914. default:
  915. reader.Skip();
  916. break;
  917. }
  918. }
  919. }
  920. }
  921. private void FetchFromFileInfoNode(XmlReader reader, T item)
  922. {
  923. reader.MoveToContent();
  924. while (reader.Read())
  925. {
  926. if (reader.NodeType == XmlNodeType.Element)
  927. {
  928. switch (reader.Name)
  929. {
  930. case "streamdetails":
  931. {
  932. using (var subtree = reader.ReadSubtree())
  933. {
  934. FetchFromStreamDetailsNode(subtree, item);
  935. }
  936. break;
  937. }
  938. default:
  939. reader.Skip();
  940. break;
  941. }
  942. }
  943. }
  944. }
  945. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  946. {
  947. reader.MoveToContent();
  948. while (reader.Read())
  949. {
  950. if (reader.NodeType == XmlNodeType.Element)
  951. {
  952. switch (reader.Name)
  953. {
  954. case "video":
  955. {
  956. using (var subtree = reader.ReadSubtree())
  957. {
  958. FetchFromVideoNode(subtree, item);
  959. }
  960. break;
  961. }
  962. default:
  963. reader.Skip();
  964. break;
  965. }
  966. }
  967. }
  968. }
  969. private void FetchFromVideoNode(XmlReader reader, T item)
  970. {
  971. reader.MoveToContent();
  972. while (reader.Read())
  973. {
  974. if (reader.NodeType == XmlNodeType.Element)
  975. {
  976. switch (reader.Name)
  977. {
  978. case "format3d":
  979. {
  980. var video = item as Video;
  981. if (video != null)
  982. {
  983. var val = reader.ReadElementContentAsString();
  984. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  985. {
  986. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  987. }
  988. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  989. {
  990. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  991. }
  992. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  993. {
  994. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  995. }
  996. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  997. {
  998. video.Video3DFormat = Video3DFormat.FullSideBySide;
  999. }
  1000. }
  1001. break;
  1002. }
  1003. default:
  1004. reader.Skip();
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. /// <summary>
  1011. /// Gets the persons from XML node.
  1012. /// </summary>
  1013. /// <param name="reader">The reader.</param>
  1014. /// <returns>IEnumerable{PersonInfo}.</returns>
  1015. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  1016. {
  1017. var name = string.Empty;
  1018. var type = PersonType.Actor; // If type is not specified assume actor
  1019. var role = string.Empty;
  1020. int? sortOrder = null;
  1021. reader.MoveToContent();
  1022. while (reader.Read())
  1023. {
  1024. if (reader.NodeType == XmlNodeType.Element)
  1025. {
  1026. switch (reader.Name)
  1027. {
  1028. case "name":
  1029. name = reader.ReadElementContentAsString() ?? string.Empty;
  1030. break;
  1031. case "type":
  1032. {
  1033. var val = reader.ReadElementContentAsString();
  1034. if (!string.IsNullOrWhiteSpace(val))
  1035. {
  1036. type = val;
  1037. }
  1038. break;
  1039. }
  1040. case "role":
  1041. {
  1042. var val = reader.ReadElementContentAsString();
  1043. if (!string.IsNullOrWhiteSpace(val))
  1044. {
  1045. role = val;
  1046. }
  1047. break;
  1048. }
  1049. case "sortorder":
  1050. {
  1051. var val = reader.ReadElementContentAsString();
  1052. if (!string.IsNullOrWhiteSpace(val))
  1053. {
  1054. int intVal;
  1055. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  1056. {
  1057. sortOrder = intVal;
  1058. }
  1059. }
  1060. break;
  1061. }
  1062. default:
  1063. reader.Skip();
  1064. break;
  1065. }
  1066. }
  1067. }
  1068. return new PersonInfo
  1069. {
  1070. Name = name.Trim(),
  1071. Role = role,
  1072. Type = type,
  1073. SortOrder = sortOrder
  1074. };
  1075. }
  1076. /// <summary>
  1077. /// Used to split names of comma or pipe delimeted genres and people
  1078. /// </summary>
  1079. /// <param name="value">The value.</param>
  1080. /// <returns>IEnumerable{System.String}.</returns>
  1081. private IEnumerable<string> SplitNames(string value)
  1082. {
  1083. value = value ?? string.Empty;
  1084. // Only split by comma if there is no pipe in the string
  1085. // We have to be careful to not split names like Matthew, Jr.
  1086. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1087. value = value.Trim().Trim(separator);
  1088. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1089. }
  1090. /// <summary>
  1091. /// Provides an additional overload for string.split
  1092. /// </summary>
  1093. /// <param name="val">The val.</param>
  1094. /// <param name="separators">The separators.</param>
  1095. /// <param name="options">The options.</param>
  1096. /// <returns>System.String[][].</returns>
  1097. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1098. {
  1099. return val.Split(separators, options);
  1100. }
  1101. }
  1102. }