1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291 |
- 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);
- }
- // TODO: Support Tmdb
- // http://www.themoviedb.org/movie/36557
- }
- 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);
- 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;
- }
- }
- 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);
- }
- }
- }
|