BaseNfoParser.cs 48 KB

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