12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310 |
- using MediaBrowser.Common.Configuration;
- using MediaBrowser.Controller.Entities;
- using MediaBrowser.Controller.Providers;
- using MediaBrowser.Model.Entities;
- using MediaBrowser.Model.Extensions;
- using MediaBrowser.Model.Logging;
- using MediaBrowser.XbmcMetadata.Configuration;
- using MediaBrowser.XbmcMetadata.Savers;
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Xml;
- namespace MediaBrowser.XbmcMetadata.Parsers
- {
- public class BaseNfoParser<T>
- where T : BaseItem
- {
- /// <summary>
- /// The logger
- /// </summary>
- protected ILogger Logger { get; private set; }
- private readonly CultureInfo _usCulture = new CultureInfo("en-US");
- private readonly IConfigurationManager _config;
- /// <summary>
- /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
- /// </summary>
- /// <param name="logger">The logger.</param>
- /// <param name="config">The configuration.</param>
- public BaseNfoParser(ILogger logger, IConfigurationManager config)
- {
- Logger = logger;
- _config = config;
- }
- /// <summary>
- /// Fetches metadata for an item from one xml file
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="metadataFile">The metadata file.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <exception cref="System.ArgumentNullException">
- /// </exception>
- public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
- {
- if (item == null)
- {
- throw new ArgumentNullException();
- }
- if (string.IsNullOrEmpty(metadataFile))
- {
- throw new ArgumentNullException();
- }
- var settings = new XmlReaderSettings
- {
- CheckCharacters = false,
- IgnoreProcessingInstructions = true,
- IgnoreComments = true,
- ValidationType = ValidationType.None
- };
- Fetch(item, metadataFile, settings, cancellationToken);
- }
- protected virtual bool SupportsUrlAfterClosingXmlTag
- {
- get { return false; }
- }
- /// <summary>
- /// Fetches the specified item.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="metadataFile">The metadata file.</param>
- /// <param name="settings">The settings.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- private void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
- {
- item.ResetPeople();
- if (!SupportsUrlAfterClosingXmlTag)
- {
- using (var streamReader = BaseNfoSaver.GetStreamReader(metadataFile))
- {
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(streamReader, settings))
- {
- reader.MoveToContent();
- // Loop through each element
- while (reader.Read())
- {
- cancellationToken.ThrowIfCancellationRequested();
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- }
- }
- }
- return;
- }
- using (var streamReader = BaseNfoSaver.GetStreamReader(metadataFile))
- {
- // Need to handle a url after the xml data
- // http://kodi.wiki/view/NFO_files/movies
- var xml = streamReader.ReadToEnd();
- // Find last closing Tag
- // Need to do this in two steps to account for random > characters after the closing xml
- var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
- // If closing tag exists, move to end of Tag
- if (index != -1)
- {
- index = xml.IndexOf('>', index);
- }
- if (index != -1)
- {
- var endingXml = xml.Substring(index);
- ParseProviderLinks(item.Item, endingXml);
- // If the file is just an imdb url, don't go any further
- if (index == 0)
- {
- return;
- }
- xml = xml.Substring(0, index + 1);
- }
- else
- {
- // If the file is just an Imdb url, handle that
- ParseProviderLinks(item.Item, xml);
- return;
- }
- using (var ms = new MemoryStream())
- {
- var bytes = Encoding.UTF8.GetBytes(xml);
- ms.Write(bytes, 0, bytes.Length);
- ms.Position = 0;
- // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
- try
- {
- // Use XmlReader for best performance
- using (var reader = XmlReader.Create(ms, settings))
- {
- reader.MoveToContent();
- // Loop through each element
- while (reader.Read())
- {
- cancellationToken.ThrowIfCancellationRequested();
- if (reader.NodeType == XmlNodeType.Element)
- {
- FetchDataFromXmlNode(reader, item);
- }
- }
- }
- }
- catch (XmlException)
- {
-
- }
- }
- }
- }
- private void ParseProviderLinks(T item, string xml)
- {
- //Look for a match for the Regex pattern "tt" followed by 7 digits
- Match m = Regex.Match(xml, @"tt([0-9]{7})", RegexOptions.IgnoreCase);
- if (m.Success)
- {
- item.SetProviderId(MetadataProviders.Imdb, m.Value);
- }
- // Support Tmdb
- // http://www.themoviedb.org/movie/36557
- var srch = "themoviedb.org/movie/";
- var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
- if (index != -1)
- {
- var tmdbId = xml.Substring(index + srch.Length).TrimEnd('/');
- int value;
- if (!string.IsNullOrWhiteSpace(tmdbId) && int.TryParse(tmdbId, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
- {
- item.SetProviderId(MetadataProviders.Tmdb, tmdbId);
- }
- }
- }
- protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
- {
- var item = itemResult.Item;
- var userDataUserId = _config.GetNfoConfiguration().UserId;
- switch (reader.Name)
- {
- // DateCreated
- case "dateadded":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- DateTime added;
- if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
- {
- item.EndDate = added.ToUniversalTime();
- }
- else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
- {
- item.DateCreated = added.ToUniversalTime();
- }
- else
- {
- Logger.Warn("Invalid Added value found: " + val);
- }
- }
- break;
- }
- case "originaltitle":
- {
- var val = reader.ReadElementContentAsString();
- var hasOriginalTitle = item as IHasOriginalTitle;
- if (hasOriginalTitle != null)
- {
- if (!string.IsNullOrEmpty(hasOriginalTitle.OriginalTitle))
- {
- hasOriginalTitle.OriginalTitle = val;
- }
- }
- break;
- }
- case "type":
- item.DisplayMediaType = reader.ReadElementContentAsString();
- break;
- case "title":
- case "localtitle":
- item.Name = reader.ReadElementContentAsString();
- break;
- case "criticrating":
- {
- var text = reader.ReadElementContentAsString();
- var hasCriticRating = item as IHasCriticRating;
- if (hasCriticRating != null && !string.IsNullOrEmpty(text))
- {
- float value;
- if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
- {
- hasCriticRating.CriticRating = value;
- }
- }
- break;
- }
- case "budget":
- {
- var text = reader.ReadElementContentAsString();
- var hasBudget = item as IHasBudget;
- if (hasBudget != null)
- {
- double value;
- if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
- {
- hasBudget.Budget = value;
- }
- }
- break;
- }
- case "revenue":
- {
- var text = reader.ReadElementContentAsString();
- var hasBudget = item as IHasBudget;
- if (hasBudget != null)
- {
- double value;
- if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
- {
- hasBudget.Revenue = value;
- }
- }
- break;
- }
- case "metascore":
- {
- var text = reader.ReadElementContentAsString();
- var hasMetascore = item as IHasMetascore;
- if (hasMetascore != null)
- {
- float value;
- if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
- {
- hasMetascore.Metascore = value;
- }
- }
- break;
- }
- case "awardsummary":
- {
- var text = reader.ReadElementContentAsString();
- var hasAwards = item as IHasAwards;
- if (hasAwards != null)
- {
- if (!string.IsNullOrWhiteSpace(text))
- {
- hasAwards.AwardSummary = text;
- }
- }
- break;
- }
- case "sorttitle":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.ForcedSortName = val;
- }
- break;
- }
- case "outline":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var hasShortOverview = item as IHasShortOverview;
- if (hasShortOverview != null)
- {
- hasShortOverview.ShortOverview = val;
- }
- }
- break;
- }
- case "biography":
- case "plot":
- case "review":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.Overview = val;
- }
- break;
- }
- case "criticratingsummary":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var hasCriticRating = item as IHasCriticRating;
- if (hasCriticRating != null)
- {
- hasCriticRating.CriticRatingSummary = val;
- }
- }
- break;
- }
- case "language":
- {
- var val = reader.ReadElementContentAsString();
- item.PreferredMetadataLanguage = val;
- break;
- }
- case "countrycode":
- {
- var val = reader.ReadElementContentAsString();
- item.PreferredMetadataCountryCode = val;
- break;
- }
- case "website":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.HomePageUrl = val;
- }
- break;
- }
- case "lockedfields":
- {
- var fields = new List<MetadataFields>();
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var list = val.Split('|').Select(i =>
- {
- MetadataFields field;
- if (Enum.TryParse<MetadataFields>(i, true, out field))
- {
- return (MetadataFields?)field;
- }
- return null;
- }).Where(i => i.HasValue).Select(i => i.Value);
- fields.AddRange(list);
- }
- item.LockedFields = fields;
- break;
- }
- case "tagline":
- {
- var val = reader.ReadElementContentAsString();
- var hasTagline = item as IHasTaglines;
- if (hasTagline != null)
- {
- if (!string.IsNullOrWhiteSpace(val))
- {
- hasTagline.AddTagline(val);
- }
- }
- break;
- }
- case "country":
- {
- var val = reader.ReadElementContentAsString();
- var hasProductionLocations = item as IHasProductionLocations;
- if (hasProductionLocations != null)
- {
- if (!string.IsNullOrWhiteSpace(val))
- {
- var parts = val.Split('/')
- .Select(i => i.Trim())
- .Where(i => !string.IsNullOrWhiteSpace(i));
- foreach (var p in parts)
- {
- hasProductionLocations.AddProductionLocation(p);
- }
- }
- }
- break;
- }
- case "mpaa":
- {
- var rating = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rating))
- {
- item.OfficialRating = rating;
- }
- break;
- }
- case "mpaadescription":
- {
- var rating = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rating))
- {
- item.OfficialRatingDescription = rating;
- }
- break;
- }
- case "customrating":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.CustomRating = val;
- }
- break;
- }
- case "runtime":
- {
- var text = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(text))
- {
- int runtime;
- if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out runtime))
- {
- item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
- }
- }
- break;
- }
- case "aspectratio":
- {
- var val = reader.ReadElementContentAsString();
- var hasAspectRatio = item as IHasAspectRatio;
- if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
- {
- hasAspectRatio.AspectRatio = val;
- }
- break;
- }
- case "lockdata":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
- }
- break;
- }
- case "studio":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var parts = val.Split('/')
- .Select(i => i.Trim())
- .Where(i => !string.IsNullOrWhiteSpace(i));
- foreach (var p in parts)
- {
- item.AddStudio(p);
- }
- }
- break;
- }
- case "director":
- {
- foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
- {
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
- }
- break;
- }
- case "credits":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var parts = val.Split('/').Select(i => i.Trim())
- .Where(i => !string.IsNullOrEmpty(i));
- foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
- {
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
- }
- }
- break;
- }
- case "writer":
- {
- foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
- {
- if (string.IsNullOrWhiteSpace(p.Name))
- {
- continue;
- }
- itemResult.AddPerson(p);
- }
- break;
- }
- case "actor":
- {
- using (var subtree = reader.ReadSubtree())
- {
- var person = GetPersonFromXmlNode(subtree);
- if (!string.IsNullOrWhiteSpace(person.Name))
- {
- itemResult.AddPerson(person);
- }
- }
- break;
- }
- case "trailer":
- {
- var val = reader.ReadElementContentAsString();
- var hasTrailer = item as IHasTrailers;
- if (hasTrailer != null)
- {
- if (!string.IsNullOrWhiteSpace(val))
- {
- val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "http://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
-
- hasTrailer.AddTrailerUrl(val, false);
- }
- }
- break;
- }
- case "displayorder":
- {
- var val = reader.ReadElementContentAsString();
- var hasDisplayOrder = item as IHasDisplayOrder;
- if (hasDisplayOrder != null)
- {
- if (!string.IsNullOrWhiteSpace(val))
- {
- hasDisplayOrder.DisplayOrder = val;
- }
- }
- break;
- }
- case "year":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- int productionYear;
- if (int.TryParse(val, out productionYear) && productionYear > 1850)
- {
- item.ProductionYear = productionYear;
- }
- }
- break;
- }
- case "rating":
- {
- var rating = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rating))
- {
- float val;
- // All external meta is saving this as '.' for decimal I believe...but just to be sure
- if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
- {
- item.CommunityRating = val;
- }
- }
- break;
- }
- case "aired":
- case "formed":
- case "premiered":
- case "releasedate":
- {
- var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- DateTime date;
- if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
- {
- item.PremiereDate = date.ToUniversalTime();
- item.ProductionYear = date.Year;
- }
- }
- break;
- }
- case "enddate":
- {
- var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- DateTime date;
- if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
- {
- item.EndDate = date.ToUniversalTime();
- }
- }
- break;
- }
- case "tvdbid":
- var tvdbId = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(tvdbId))
- {
- item.SetProviderId(MetadataProviders.Tvdb, tvdbId);
- }
- break;
- case "votes":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- int num;
- if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
- {
- item.VoteCount = num;
- }
- }
- break;
- }
- case "musicbrainzalbumid":
- {
- var mbz = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(mbz))
- {
- item.SetProviderId(MetadataProviders.MusicBrainzAlbum, mbz);
- }
- break;
- }
- case "musicbrainzalbumartistid":
- {
- var mbz = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(mbz))
- {
- item.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mbz);
- }
- break;
- }
- case "musicbrainzartistid":
- {
- var mbz = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(mbz))
- {
- item.SetProviderId(MetadataProviders.MusicBrainzArtist, mbz);
- }
- break;
- }
- case "musicbrainzreleasegroupid":
- {
- var mbz = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(mbz))
- {
- item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mbz);
- }
- break;
- }
- case "tvrageid":
- {
- var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
- {
- item.SetProviderId(MetadataProviders.TvRage, id);
- }
- break;
- }
- case "audiodbartistid":
- {
- var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
- {
- item.SetProviderId(MetadataProviders.AudioDbArtist, id);
- }
- break;
- }
- case "audiodbalbumid":
- {
- var id = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(id))
- {
- item.SetProviderId(MetadataProviders.AudioDbAlbum, id);
- }
- break;
- }
- case "rottentomatoesid":
- var rtId = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(rtId))
- {
- item.SetProviderId(MetadataProviders.RottenTomatoes, rtId);
- }
- break;
- case "tmdbid":
- var tmdb = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(tmdb))
- {
- item.SetProviderId(MetadataProviders.Tmdb, tmdb);
- }
- break;
- case "collectionnumber":
- var tmdbCollection = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(tmdbCollection))
- {
- item.SetProviderId(MetadataProviders.TmdbCollection, tmdbCollection);
- }
- break;
- case "tvcomid":
- var TVcomId = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(TVcomId))
- {
- item.SetProviderId(MetadataProviders.Tvcom, TVcomId);
- }
- break;
- case "zap2itid":
- var zap2ItId = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(zap2ItId))
- {
- item.SetProviderId(MetadataProviders.Zap2It, zap2ItId);
- }
- break;
- case "imdb_id":
- case "imdbid":
- var imDbId = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(imDbId))
- {
- item.SetProviderId(MetadataProviders.Imdb, imDbId);
- }
- break;
- case "genre":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var parts = val.Split('/')
- .Select(i => i.Trim())
- .Where(i => !string.IsNullOrWhiteSpace(i));
- foreach (var p in parts)
- {
- item.AddGenre(p);
- }
- }
- break;
- }
- case "style":
- case "tag":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- var hasTags = item as IHasTags;
- if (hasTags != null)
- {
- hasTags.AddTag(val);
- }
- }
- break;
- }
- case "plotkeyword":
- {
- var val = reader.ReadElementContentAsString();
- var hasKeywords = item as IHasKeywords;
- if (hasKeywords != null)
- {
- if (!string.IsNullOrWhiteSpace(val))
- {
- hasKeywords.AddKeyword(val);
- }
- }
- break;
- }
- case "fileinfo":
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromFileInfoNode(subtree, item);
- }
- break;
- }
- case "watched":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
- {
- bool parsedValue;
- if (bool.TryParse(val, out parsedValue))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- userData.Played = parsedValue;
- }
- }
- break;
- }
- case "playcount":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
- {
- int parsedValue;
- if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- userData.PlayCount = parsedValue;
- if (parsedValue > 0)
- {
- userData.Played = true;
- }
- }
- }
- break;
- }
- case "lastplayed":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
- {
- DateTime parsedValue;
- if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- userData.LastPlayedDate = parsedValue.ToUniversalTime();
- }
- }
- break;
- }
- case "resume":
- {
- using (var subtree = reader.ReadSubtree())
- {
- if (!string.IsNullOrWhiteSpace(userDataUserId))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- FetchFromResumeNode(subtree, item, userData);
- }
- }
- break;
- }
- case "isuserfavorite":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
- {
- bool parsedValue;
- if (bool.TryParse(val, out parsedValue))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- userData.IsFavorite = parsedValue;
- }
- }
- break;
- }
- case "userrating":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
- {
- double parsedValue;
- if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
- {
- var userData = GetOrAdd(itemResult, userDataUserId);
- userData.Rating = parsedValue;
- }
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
- {
- return result.GetOrAddUserData(userId);
- }
- private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
- {
- reader.MoveToContent();
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "position":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- double parsedValue;
- if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
- {
- userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
- }
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- }
- }
- private void FetchFromFileInfoNode(XmlReader reader, T item)
- {
- reader.MoveToContent();
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "streamdetails":
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromStreamDetailsNode(subtree, item);
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- }
- }
- private void FetchFromStreamDetailsNode(XmlReader reader, T item)
- {
- reader.MoveToContent();
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "video":
- {
- using (var subtree = reader.ReadSubtree())
- {
- FetchFromVideoNode(subtree, item);
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- }
- }
- private void FetchFromVideoNode(XmlReader reader, T item)
- {
- reader.MoveToContent();
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "format3d":
- {
- var video = item as Video;
- if (video != null)
- {
- var val = reader.ReadElementContentAsString();
- if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.HalfSideBySide;
- }
- else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
- }
- else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.FullTopAndBottom;
- }
- else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.FullSideBySide;
- }
- else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
- {
- video.Video3DFormat = Video3DFormat.MVC;
- }
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- }
- }
- /// <summary>
- /// Gets the persons from XML node.
- /// </summary>
- /// <param name="reader">The reader.</param>
- /// <returns>IEnumerable{PersonInfo}.</returns>
- private PersonInfo GetPersonFromXmlNode(XmlReader reader)
- {
- var name = string.Empty;
- var type = PersonType.Actor; // If type is not specified assume actor
- var role = string.Empty;
- int? sortOrder = null;
- reader.MoveToContent();
- while (reader.Read())
- {
- if (reader.NodeType == XmlNodeType.Element)
- {
- switch (reader.Name)
- {
- case "name":
- name = reader.ReadElementContentAsString() ?? string.Empty;
- break;
- case "type":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- type = val;
- }
- break;
- }
- case "role":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- role = val;
- }
- break;
- }
- case "sortorder":
- {
- var val = reader.ReadElementContentAsString();
- if (!string.IsNullOrWhiteSpace(val))
- {
- int intVal;
- if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
- {
- sortOrder = intVal;
- }
- }
- break;
- }
- default:
- reader.Skip();
- break;
- }
- }
- }
- return new PersonInfo
- {
- Name = name.Trim(),
- Role = role,
- Type = type,
- SortOrder = sortOrder
- };
- }
- /// <summary>
- /// Used to split names of comma or pipe delimeted genres and people
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>IEnumerable{System.String}.</returns>
- private IEnumerable<string> SplitNames(string value)
- {
- value = value ?? string.Empty;
- // Only split by comma if there is no pipe in the string
- // We have to be careful to not split names like Matthew, Jr.
- var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
- value = value.Trim().Trim(separator);
- return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
- }
- /// <summary>
- /// Provides an additional overload for string.split
- /// </summary>
- /// <param name="val">The val.</param>
- /// <param name="separators">The separators.</param>
- /// <param name="options">The options.</param>
- /// <returns>System.String[][].</returns>
- private static string[] Split(string val, char[] separators, StringSplitOptions options)
- {
- return val.Split(separators, options);
- }
- }
- }
|