< Summary - Jellyfin

Information
Class: MediaBrowser.XbmcMetadata.Parsers.BaseNfoParser<T>
Assembly: MediaBrowser.XbmcMetadata
File(s): /srv/git/jellyfin/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs
Line coverage
86%
Covered lines: 361
Uncovered lines: 57
Coverable lines: 418
Total lines: 995
Line coverage: 86.3%
Branch coverage
91%
Covered branches: 425
Total branches: 462
Branch coverage: 91.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_SupportsUrlAfterClosingXmlTag()100%11100%
Fetch(...)100%44100%
Fetch(...)95%202092.68%
ParseProviderLinks(...)91.66%121290.9%
FetchDataFromXmlNode(...)94.29%60829884.83%
FetchThumbNode(...)95.45%222296.42%
FetchFromFileInfoNode(...)80%111080%
FetchFromStreamDetailsNode(...)91.66%121288.23%
FetchFromVideoNode(...)70%633066.66%
FetchFromSubtitleNode(...)83.33%131282.35%
FetchFromRatingsNode(...)75%161270%
FetchFromRatingNode(...)100%1818100%
GetXmlReaderSettings()100%11100%
GetImageType(...)100%1212100%

File(s)

/srv/git/jellyfin/MediaBrowser.XbmcMetadata/Parsers/BaseNfoParser.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Linq;
 6using System.Text;
 7using System.Threading;
 8using System.Xml;
 9using Jellyfin.Data.Enums;
 10using Jellyfin.Extensions;
 11using MediaBrowser.Common.Configuration;
 12using MediaBrowser.Common.Providers;
 13using MediaBrowser.Controller.Entities;
 14using MediaBrowser.Controller.Entities.Movies;
 15using MediaBrowser.Controller.Entities.TV;
 16using MediaBrowser.Controller.Extensions;
 17using MediaBrowser.Controller.Library;
 18using MediaBrowser.Controller.Providers;
 19using MediaBrowser.Model.Entities;
 20using MediaBrowser.XbmcMetadata.Configuration;
 21using MediaBrowser.XbmcMetadata.Savers;
 22using Microsoft.Extensions.Logging;
 23
 24namespace MediaBrowser.XbmcMetadata.Parsers
 25{
 26    /// <summary>
 27    /// The BaseNfoParser class.
 28    /// </summary>
 29    /// <typeparam name="T">The type.</typeparam>
 30    public class BaseNfoParser<T>
 31        where T : BaseItem
 32    {
 33        private readonly IConfigurationManager _config;
 34        private readonly IUserManager _userManager;
 35        private readonly IUserDataManager _userDataManager;
 36        private readonly IDirectoryService _directoryService;
 37        private Dictionary<string, string> _validProviderIds;
 38
 39        /// <summary>
 40        /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
 41        /// </summary>
 42        /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
 43        /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
 44        /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param>
 45        /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 46        /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param>
 47        /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param>
 48        public BaseNfoParser(
 49            ILogger logger,
 50            IConfigurationManager config,
 51            IProviderManager providerManager,
 52            IUserManager userManager,
 53            IUserDataManager userDataManager,
 54            IDirectoryService directoryService)
 55        {
 3056            Logger = logger;
 3057            _config = config;
 3058            ProviderManager = providerManager;
 3059            _validProviderIds = new Dictionary<string, string>();
 3060            _userManager = userManager;
 3061            _userDataManager = userDataManager;
 3062            _directoryService = directoryService;
 3063        }
 64
 65        /// <summary>
 66        /// Gets the logger.
 67        /// </summary>
 68        protected ILogger Logger { get; }
 69
 70        /// <summary>
 71        /// Gets the provider manager.
 72        /// </summary>
 73        protected IProviderManager ProviderManager { get; }
 74
 75        /// <summary>
 76        /// Gets a value indicating whether URLs after a closing XML tag are supported.
 77        /// </summary>
 378        protected virtual bool SupportsUrlAfterClosingXmlTag => false;
 79
 80        /// <summary>
 81        /// Fetches metadata for an item from one xml file.
 82        /// </summary>
 83        /// <param name="item">The <see cref="MetadataResult{T}"/>.</param>
 84        /// <param name="metadataFile">The metadata file.</param>
 85        /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
 86        /// <exception cref="ArgumentNullException"><c>item</c> is <c>null</c>.</exception>
 87        /// <exception cref="ArgumentException"><c>metadataFile</c> is <c>null</c> or empty.</exception>
 88        public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
 89        {
 3090            if (item.Item is null)
 91            {
 792                throw new ArgumentException("Item can't be null.", nameof(item));
 93            }
 94
 2395            ArgumentException.ThrowIfNullOrEmpty(metadataFile);
 96
 1697            _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 98
 1699            var idInfos = ProviderManager.GetExternalIdInfos(item.Item);
 100
 56101            foreach (var info in idInfos)
 102            {
 12103                var id = info.Key + "Id";
 12104                _validProviderIds.TryAdd(id, info.Key);
 105            }
 106
 107            // Additional Mappings
 16108            _validProviderIds.Add("collectionnumber", "TmdbCollection");
 16109            _validProviderIds.Add("tmdbcolid", "TmdbCollection");
 16110            _validProviderIds.Add("imdb_id", "Imdb");
 111
 16112            Fetch(item, metadataFile, GetXmlReaderSettings(), cancellationToken);
 16113        }
 114
 115        /// <summary>
 116        /// Fetches the specified item.
 117        /// </summary>
 118        /// <param name="item">The <see cref="MetadataResult{T}"/>.</param>
 119        /// <param name="metadataFile">The metadata file.</param>
 120        /// <param name="settings">The <see cref="XmlReaderSettings"/>.</param>
 121        /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
 122        protected virtual void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, Cancellati
 123        {
 12124            if (!SupportsUrlAfterClosingXmlTag)
 125            {
 3126                using (var fileStream = File.OpenRead(metadataFile))
 3127                using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
 3128                using (var reader = XmlReader.Create(streamReader, settings))
 129                {
 3130                    item.ResetPeople();
 131
 3132                    reader.MoveToContent();
 3133                    reader.Read();
 134
 135                    // Loop through each element
 187136                    while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 137                    {
 184138                        cancellationToken.ThrowIfCancellationRequested();
 139
 184140                        if (reader.NodeType == XmlNodeType.Element)
 141                        {
 82142                            FetchDataFromXmlNode(reader, item);
 143                        }
 144                        else
 145                        {
 102146                            reader.Read();
 147                        }
 148                    }
 3149                }
 150
 3151                return;
 152            }
 153
 9154            item.ResetPeople();
 155
 156            // Need to handle a url after the xml data
 157            // http://kodi.wiki/view/NFO_files/movies
 158
 9159            var xml = File.ReadAllText(metadataFile);
 160
 161            // Find last closing Tag
 162            // Need to do this in two steps to account for random > characters after the closing xml
 9163            var index = xml.LastIndexOf("</", StringComparison.Ordinal);
 164
 165            // If closing tag exists, move to end of Tag
 9166            if (index != -1)
 167            {
 5168                index = xml.IndexOf('>', index);
 169            }
 170
 9171            if (index != -1)
 172            {
 5173                var endingXml = xml.AsSpan().Slice(index);
 174
 5175                ParseProviderLinks(item.Item, endingXml);
 176
 177                // If the file is just an IMDb url, don't go any further
 5178                if (index == 0)
 179                {
 0180                    return;
 181                }
 182
 5183                xml = xml.Substring(0, index + 1);
 184            }
 185            else
 186            {
 187                // If the file is just provider urls, handle that
 4188                ParseProviderLinks(item.Item, xml);
 189
 4190                return;
 191            }
 192
 193            // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with
 194            try
 195            {
 5196                using (var stringReader = new StringReader(xml))
 5197                using (var reader = XmlReader.Create(stringReader, settings))
 198                {
 5199                    reader.MoveToContent();
 5200                    reader.Read();
 201
 202                    // Loop through each element
 602203                    while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 204                    {
 597205                        cancellationToken.ThrowIfCancellationRequested();
 206
 597207                        if (reader.NodeType == XmlNodeType.Element)
 208                        {
 279209                            FetchDataFromXmlNode(reader, item);
 210                        }
 211                        else
 212                        {
 318213                            reader.Read();
 214                        }
 215                    }
 5216                }
 5217            }
 0218            catch (XmlException)
 219            {
 0220            }
 5221        }
 222
 223        /// <summary>
 224        /// Parses a XML tag to a provider id.
 225        /// </summary>
 226        /// <param name="item">The item.</param>
 227        /// <param name="xml">The xml tag.</param>
 228        protected void ParseProviderLinks(T item, ReadOnlySpan<char> xml)
 229        {
 9230            if (ProviderIdParsers.TryFindImdbId(xml, out var imdbId))
 231            {
 2232                item.SetProviderId(MetadataProvider.Imdb, imdbId.ToString());
 233            }
 234
 9235            if (item is Movie)
 236            {
 6237                if (ProviderIdParsers.TryFindTmdbMovieId(xml, out var tmdbId))
 238                {
 2239                    item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString());
 240                }
 241            }
 242
 9243            if (item is Series)
 244            {
 2245                if (ProviderIdParsers.TryFindTmdbSeriesId(xml, out var tmdbId))
 246                {
 0247                    item.SetProviderId(MetadataProvider.Tmdb, tmdbId.ToString());
 248                }
 249
 2250                if (ProviderIdParsers.TryFindTvdbId(xml, out var tvdbId))
 251                {
 1252                    item.SetProviderId(MetadataProvider.Tvdb, tvdbId.ToString());
 253                }
 254            }
 9255        }
 256
 257        /// <summary>
 258        /// Fetches metadata from an XML node.
 259        /// </summary>
 260        /// <param name="reader">The <see cref="XmlReader"/>.</param>
 261        /// <param name="itemResult">The <see cref="MetadataResult{T}"/>.</param>
 262        protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
 263        {
 444264            var item = itemResult.Item;
 444265            var nfoConfiguration = _config.GetNfoConfiguration();
 266            UserItemData? userData;
 267
 444268            switch (reader.Name)
 269            {
 270                case "dateadded":
 5271                    if (reader.TryReadDateTime(out var dateCreated))
 272                    {
 5273                        item.DateCreated = dateCreated;
 274                    }
 275
 5276                    break;
 277                case "originaltitle":
 7278                    item.OriginalTitle = reader.ReadNormalizedString();
 7279                    break;
 280                case "name":
 281                case "title":
 282                case "localtitle":
 14283                    item.Name = reader.ReadNormalizedString();
 14284                    break;
 285                case "sortname":
 1286                    item.SortName = reader.ReadNormalizedString();
 1287                    break;
 288                case "criticrating":
 1289                    var criticRatingText = reader.ReadElementContentAsString();
 1290                    if (float.TryParse(criticRatingText, CultureInfo.InvariantCulture, out var value))
 291                    {
 1292                        item.CriticRating = value;
 293                    }
 294
 1295                    break;
 296                case "sorttitle":
 1297                    item.ForcedSortName = reader.ReadNormalizedString();
 1298                    break;
 299                case "biography":
 300                case "plot":
 301                case "review":
 12302                    item.Overview = reader.ReadNormalizedString();
 12303                    break;
 304                case "language":
 1305                    item.PreferredMetadataLanguage = reader.ReadNormalizedString();
 1306                    break;
 307                case "watched":
 8308                    var played = reader.ReadElementContentAsBoolean();
 8309                    if (Guid.TryParse(nfoConfiguration.UserId, out var userId))
 310                    {
 1311                        var user = _userManager.GetUserById(userId);
 1312                        if (user is not null)
 313                        {
 1314                            userData = _userDataManager.GetUserData(user, item);
 1315                            if (userData is not null)
 316                            {
 1317                                userData.Played = played;
 1318                                _userDataManager.SaveUserData(user, item, userData, UserDataSaveReason.Import, Cancellat
 319                            }
 320                        }
 321                    }
 322
 1323                    break;
 324                case "playcount":
 4325                    if (reader.TryReadInt(out var count)
 4326                        && Guid.TryParse(nfoConfiguration.UserId, out var playCountUserId))
 327                    {
 1328                        var user = _userManager.GetUserById(playCountUserId);
 1329                        if (user is not null)
 330                        {
 1331                            userData = _userDataManager.GetUserData(user, item);
 1332                            if (userData is not null)
 333                            {
 1334                                userData.PlayCount = count;
 1335                                _userDataManager.SaveUserData(user, item, userData, UserDataSaveReason.Import, Cancellat
 336                            }
 337                        }
 338                    }
 339
 1340                    break;
 341                case "lastplayed":
 4342                    if (reader.TryReadDateTime(out var lastPlayed)
 4343                        && Guid.TryParse(nfoConfiguration.UserId, out var lastPlayedUserId))
 344                    {
 1345                        var user = _userManager.GetUserById(lastPlayedUserId);
 1346                        if (user is not null)
 347                        {
 1348                            userData = _userDataManager.GetUserData(user, item);
 1349                            if (userData is not null)
 350                            {
 1351                                userData.LastPlayedDate = lastPlayed;
 1352                                _userDataManager.SaveUserData(user, item, userData, UserDataSaveReason.Import, Cancellat
 353                            }
 354                        }
 355                    }
 356
 1357                    break;
 358                case "countrycode":
 1359                    item.PreferredMetadataCountryCode = reader.ReadNormalizedString();
 1360                    break;
 361                case "lockedfields":
 362                    {
 0363                        var val = reader.ReadElementContentAsString();
 364
 0365                        if (!string.IsNullOrWhiteSpace(val))
 366                        {
 0367                            item.LockedFields = val.Split('|').Select(i =>
 0368                            {
 0369                                if (Enum.TryParse(i, true, out MetadataField field))
 0370                                {
 0371                                    return (MetadataField?)field;
 0372                                }
 0373
 0374                                return null;
 0375                            }).OfType<MetadataField>().ToArray();
 376                        }
 377
 0378                        break;
 379                    }
 380
 381                case "tagline":
 4382                    item.Tagline = reader.ReadNormalizedString();
 4383                    break;
 384                case "country":
 385                    {
 3386                        var val = reader.ReadElementContentAsString();
 387
 3388                        if (!string.IsNullOrWhiteSpace(val))
 389                        {
 3390                            item.ProductionLocations = val.Split('/')
 3391                                .Select(i => i.Trim())
 3392                                .Where(i => !string.IsNullOrWhiteSpace(i))
 3393                                .ToArray();
 394                        }
 395
 3396                        break;
 397                    }
 398
 399                case "mpaa":
 4400                    item.OfficialRating = reader.ReadNormalizedString();
 4401                    break;
 402                case "customrating":
 1403                    item.CustomRating = reader.ReadNormalizedString();
 1404                    break;
 405                case "runtime":
 4406                    var runtimeText = reader.ReadElementContentAsString();
 4407                    if (int.TryParse(runtimeText.AsSpan().LeftPart(' '), NumberStyles.Integer, CultureInfo.InvariantCult
 408                    {
 4409                        item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
 410                    }
 411
 4412                    break;
 413                case "aspectratio":
 1414                    var aspectRatio = reader.ReadNormalizedString();
 1415                    if (!string.IsNullOrEmpty(aspectRatio) && item is IHasAspectRatio hasAspectRatio)
 416                    {
 1417                        hasAspectRatio.AspectRatio = aspectRatio;
 418                    }
 419
 1420                    break;
 421                case "lockdata":
 1422                    item.IsLocked = string.Equals(reader.ReadElementContentAsString(), "true", StringComparison.OrdinalI
 1423                    break;
 424                case "studio":
 4425                    var studio = reader.ReadNormalizedString();
 4426                    if (!string.IsNullOrEmpty(studio))
 427                    {
 4428                        item.AddStudio(studio);
 429                    }
 430
 4431                    break;
 432                case "director":
 12433                    foreach (var director in reader.GetPersonArray(PersonKind.Director))
 434                    {
 3435                        itemResult.AddPerson(director);
 436                    }
 437
 438                    break;
 439                case "credits":
 440                    {
 4441                        var val = reader.ReadElementContentAsString();
 442
 4443                        if (!string.IsNullOrWhiteSpace(val))
 444                        {
 4445                            var parts = val.Split('/').Select(i => i.Trim())
 4446                                .Where(i => !string.IsNullOrEmpty(i));
 447
 16448                            foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonKind.Writ
 449                            {
 4450                                if (string.IsNullOrWhiteSpace(p.Name))
 451                                {
 452                                    continue;
 453                                }
 454
 4455                                itemResult.AddPerson(p);
 456                            }
 457                        }
 458
 459                        break;
 460                    }
 461
 462                case "writer":
 4463                    foreach (var writer in reader.GetPersonArray(PersonKind.Writer))
 464                    {
 1465                        itemResult.AddPerson(writer);
 466                    }
 467
 468                    break;
 469                case "actor":
 55470                    var person = reader.GetPersonFromXmlNode();
 55471                    if (person is not null)
 472                    {
 55473                        itemResult.AddPerson(person);
 474                    }
 475
 55476                    break;
 477                case "trailer":
 4478                    var trailer = reader.ReadNormalizedString();
 4479                    if (!string.IsNullOrEmpty(trailer))
 480                    {
 1481                        if (trailer.StartsWith("plugin://plugin.video.youtube/?action=play_video&videoid=", StringCompar
 482                        {
 483                            // Deprecated format
 1484                            item.AddTrailerUrl(trailer.Replace(
 1485                                "plugin://plugin.video.youtube/?action=play_video&videoid=",
 1486                                BaseNfoSaver.YouTubeWatchUrl,
 1487                                StringComparison.OrdinalIgnoreCase));
 488
 1489                            var suggestedUrl = trailer.Replace(
 1490                                "plugin://plugin.video.youtube/?action=play_video&videoid=",
 1491                                "plugin://plugin.video.youtube/play/?video_id=",
 1492                                StringComparison.OrdinalIgnoreCase);
 1493                            Logger.LogWarning("Trailer URL uses a deprecated format : {Url}. Using {NewUrl} instead is a
 494                        }
 0495                        else if (trailer.StartsWith("plugin://plugin.video.youtube/play/?video_id=", StringComparison.Or
 496                        {
 497                            // Proper format
 0498                            item.AddTrailerUrl(trailer.Replace(
 0499                                "plugin://plugin.video.youtube/play/?video_id=",
 0500                                BaseNfoSaver.YouTubeWatchUrl,
 0501                                StringComparison.OrdinalIgnoreCase));
 502                        }
 503                    }
 504
 0505                    break;
 506                case "displayorder":
 0507                    var displayOrder = reader.ReadNormalizedString();
 0508                    if (!string.IsNullOrEmpty(displayOrder) && item is IHasDisplayOrder hasDisplayOrder)
 509                    {
 0510                        hasDisplayOrder.DisplayOrder = displayOrder;
 511                    }
 512
 0513                    break;
 514                case "year":
 6515                    if (reader.TryReadInt(out var productionYear) && productionYear > 1850)
 516                    {
 6517                        item.ProductionYear = productionYear;
 518                    }
 519
 6520                    break;
 521                case "rating":
 7522                    var rating = reader.ReadElementContentAsString().Replace(',', '.');
 523                    // All external meta is saving this as '.' for decimal I believe...but just to be sure
 7524                    if (float.TryParse(rating, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var com
 525                    {
 6526                        item.CommunityRating = communityRating;
 527                    }
 528
 6529                    break;
 530                case "ratings":
 3531                    FetchFromRatingsNode(reader, item);
 3532                    break;
 533                case "aired":
 534                case "formed":
 535                case "premiered":
 536                case "releasedate":
 19537                    if (reader.TryReadDateTimeExact(nfoConfiguration.ReleaseDateFormat, out var releaseDate))
 538                    {
 14539                        item.PremiereDate = releaseDate;
 540
 541                        // Production year can already be set by the year tag
 14542                        item.ProductionYear ??= releaseDate.Year;
 543                    }
 544
 545                    break;
 546                case "enddate":
 1547                    if (reader.TryReadDateTimeExact(nfoConfiguration.ReleaseDateFormat, out var endDate))
 548                    {
 1549                        item.EndDate = endDate;
 550                    }
 551
 1552                    break;
 553                case "genre":
 554                    {
 13555                        var val = reader.ReadElementContentAsString();
 556
 13557                        if (!string.IsNullOrWhiteSpace(val))
 558                        {
 13559                            var parts = val.Split('/')
 13560                                .Select(i => i.Trim())
 13561                                .Where(i => !string.IsNullOrWhiteSpace(i));
 562
 52563                            foreach (var p in parts)
 564                            {
 13565                                item.AddGenre(p);
 566                            }
 567                        }
 568
 569                        break;
 570                    }
 571
 572                case "style":
 573                case "tag":
 2574                    var tag = reader.ReadNormalizedString();
 2575                    if (!string.IsNullOrEmpty(tag))
 576                    {
 2577                        item.AddTag(tag);
 578                    }
 579
 2580                    break;
 581                case "fileinfo":
 3582                    FetchFromFileInfoNode(reader, item);
 3583                    break;
 584                case "uniqueid":
 6585                    if (reader.IsEmptyElement)
 586                    {
 0587                        reader.Read();
 0588                        break;
 589                    }
 590
 6591                    var provider = reader.GetAttribute("type");
 6592                    var providerId = reader.ReadElementContentAsString();
 6593                    item.TrySetProviderId(provider, providerId);
 594
 6595                    break;
 596                case "thumb":
 166597                    FetchThumbNode(reader, itemResult, "thumb");
 166598                    break;
 599                case "fanart":
 600                    {
 4601                        if (reader.IsEmptyElement)
 602                        {
 0603                            reader.Read();
 0604                            break;
 605                        }
 606
 4607                        using var subtree = reader.ReadSubtree();
 4608                        if (!subtree.ReadToDescendant("thumb"))
 609                        {
 0610                            break;
 611                        }
 612
 4613                        FetchThumbNode(subtree, itemResult, "fanart");
 4614                        break;
 615                    }
 616
 617                default:
 66618                    string readerName = reader.Name;
 66619                    if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
 620                    {
 3621                        var id = reader.ReadElementContentAsString();
 3622                        item.TrySetProviderId(providerIdValue, id);
 623                    }
 624                    else
 625                    {
 63626                        reader.Skip();
 627                    }
 628
 629                    break;
 630            }
 113631        }
 632
 633        private void FetchThumbNode(XmlReader reader, MetadataResult<T> itemResult, string parentNode)
 634        {
 170635            var artType = reader.GetAttribute("aspect");
 170636            var val = reader.ReadElementContentAsString();
 637
 638            // artType is null if the thumb node is a child of the fanart tag
 639            // -> set image type to fanart
 170640            if (string.IsNullOrWhiteSpace(artType) && parentNode.Equals("fanart", StringComparison.Ordinal))
 641            {
 4642                artType = "fanart";
 643            }
 166644            else if (string.IsNullOrWhiteSpace(artType))
 645            {
 646                // Sonarr writes thumb tags for posters without aspect property
 14647                artType = "poster";
 648            }
 649
 650            // skip:
 651            // - empty uri
 652            // - tag containing '.' because we can't set images for seasons, episodes or movie sets within series or mov
 170653            if (string.IsNullOrEmpty(val) || artType.Contains('.', StringComparison.Ordinal))
 654            {
 11655                return;
 656            }
 657
 159658            ImageType imageType = GetImageType(artType);
 659
 159660            if (!Uri.TryCreate(val, UriKind.Absolute, out var uri))
 661            {
 1662                Logger.LogError("Image location {Path} specified in nfo file for {ItemName} is not a valid URL or file p
 1663                return;
 664            }
 665
 158666            if (uri.IsFile)
 667            {
 668                // only allow one item of each type
 2669                if (itemResult.Images.Any(x => x.Type == imageType))
 670                {
 0671                    return;
 672                }
 673
 2674                var fileSystemMetadata = _directoryService.GetFile(val);
 675                // nonexistent file returns null
 2676                if (fileSystemMetadata is null || !fileSystemMetadata.Exists)
 677                {
 1678                    Logger.LogWarning("Artwork file {Path} specified in nfo file for {ItemName} does not exist.", uri, i
 1679                    return;
 680                }
 681
 1682                itemResult.Images.Add(new LocalImageInfo()
 1683                {
 1684                    FileInfo = fileSystemMetadata,
 1685                    Type = imageType
 1686                });
 687            }
 688            else
 689            {
 690                // only allow one item of each type
 156691                if (itemResult.RemoteImages.Any(x => x.Type == imageType))
 692                {
 121693                    return;
 694                }
 695
 35696                itemResult.RemoteImages.Add((uri.ToString(), imageType));
 697            }
 35698        }
 699
 700        private void FetchFromFileInfoNode(XmlReader parentReader, T item)
 701        {
 3702            if (parentReader.IsEmptyElement)
 703            {
 0704                parentReader.Read();
 0705                return;
 706            }
 707
 3708            using var reader = parentReader.ReadSubtree();
 3709            reader.MoveToContent();
 3710            reader.Read();
 711
 712            // Loop through each element
 18713            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 714            {
 15715                if (reader.NodeType != XmlNodeType.Element)
 716                {
 12717                    reader.Read();
 12718                    continue;
 719                }
 720
 3721                switch (reader.Name)
 722                {
 723                    case "streamdetails":
 3724                        FetchFromStreamDetailsNode(reader, item);
 3725                        break;
 726                    default:
 0727                        reader.Skip();
 728                        break;
 729                }
 730            }
 6731        }
 732
 733        private void FetchFromStreamDetailsNode(XmlReader parentReader, T item)
 734        {
 3735            if (parentReader.IsEmptyElement)
 736            {
 0737                parentReader.Read();
 0738                return;
 739            }
 740
 3741            using var reader = parentReader.ReadSubtree();
 3742            reader.MoveToContent();
 3743            reader.Read();
 744
 745            // Loop through each element
 32746            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 747            {
 29748                if (reader.NodeType != XmlNodeType.Element)
 749                {
 20750                    reader.Read();
 20751                    continue;
 752                }
 753
 9754                switch (reader.Name)
 755                {
 756                    case "video":
 3757                        FetchFromVideoNode(reader, item);
 3758                        break;
 759                    case "subtitle":
 2760                        FetchFromSubtitleNode(reader, item);
 2761                        break;
 762                    default:
 4763                        reader.Skip();
 764                        break;
 765                }
 766            }
 6767        }
 768
 769        private void FetchFromVideoNode(XmlReader parentReader, T item)
 770        {
 3771            if (parentReader.IsEmptyElement)
 772            {
 0773                parentReader.Read();
 0774                return;
 775            }
 776
 3777            using var reader = parentReader.ReadSubtree();
 3778            reader.MoveToContent();
 3779            reader.Read();
 780
 781            // Loop through each element
 53782            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 783            {
 50784                if (reader.NodeType != XmlNodeType.Element || item is not Video video)
 785                {
 28786                    reader.Read();
 28787                    continue;
 788                }
 789
 22790                switch (reader.Name)
 791                {
 792                    case "format3d":
 1793                        var format = reader.ReadElementContentAsString();
 1794                        if (string.Equals("HSBS", format, StringComparison.OrdinalIgnoreCase))
 795                        {
 1796                            video.Video3DFormat = Video3DFormat.HalfSideBySide;
 797                        }
 0798                        else if (string.Equals("HTAB", format, StringComparison.OrdinalIgnoreCase))
 799                        {
 0800                            video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
 801                        }
 0802                        else if (string.Equals("FTAB", format, StringComparison.OrdinalIgnoreCase))
 803                        {
 0804                            video.Video3DFormat = Video3DFormat.FullTopAndBottom;
 805                        }
 0806                        else if (string.Equals("FSBS", format, StringComparison.OrdinalIgnoreCase))
 807                        {
 0808                            video.Video3DFormat = Video3DFormat.FullSideBySide;
 809                        }
 0810                        else if (string.Equals("MVC", format, StringComparison.OrdinalIgnoreCase))
 811                        {
 0812                            video.Video3DFormat = Video3DFormat.MVC;
 813                        }
 814
 0815                        break;
 816                    case "aspect":
 3817                        video.AspectRatio = reader.ReadNormalizedString();
 3818                        break;
 819                    case "width":
 3820                        video.Width = reader.ReadElementContentAsInt();
 3821                        break;
 822                    case "height":
 3823                        video.Height = reader.ReadElementContentAsInt();
 3824                        break;
 825                    case "durationinseconds":
 3826                        video.RunTimeTicks = new TimeSpan(0, 0, reader.ReadElementContentAsInt()).Ticks;
 3827                        break;
 828                    default:
 9829                        reader.Skip();
 830                        break;
 831                }
 832            }
 6833        }
 834
 835        private void FetchFromSubtitleNode(XmlReader parentReader, T item)
 836        {
 2837            if (parentReader.IsEmptyElement)
 838            {
 0839                parentReader.Read();
 0840                return;
 841            }
 842
 2843            using var reader = parentReader.ReadSubtree();
 2844            reader.MoveToContent();
 2845            reader.Read();
 846
 847            // Loop through each element
 10848            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 849            {
 8850                if (reader.NodeType != XmlNodeType.Element)
 851                {
 6852                    reader.Read();
 6853                    continue;
 854                }
 855
 2856                switch (reader.Name)
 857                {
 858                    case "language":
 2859                        _ = reader.ReadElementContentAsString();
 2860                        if (item is Video video)
 861                        {
 2862                            video.HasSubtitles = true;
 863                        }
 864
 2865                        break;
 866                    default:
 0867                        reader.Skip();
 868                        break;
 869                }
 870            }
 4871        }
 872
 873        private void FetchFromRatingsNode(XmlReader parentReader, T item)
 874        {
 3875            if (parentReader.IsEmptyElement)
 876            {
 0877                parentReader.Read();
 0878                return;
 879            }
 880
 3881            using var reader = parentReader.ReadSubtree();
 3882            reader.MoveToContent();
 3883            reader.Read();
 884
 885            // Loop through each element
 42886            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 887            {
 39888                if (reader.NodeType == XmlNodeType.Element)
 889                {
 11890                    switch (reader.Name)
 891                    {
 892                        case "rating":
 893                            {
 11894                                if (reader.IsEmptyElement)
 895                                {
 0896                                    reader.Read();
 0897                                    continue;
 898                                }
 899
 11900                                var ratingName = reader.GetAttribute("name");
 901
 11902                                using var subtree = reader.ReadSubtree();
 11903                                FetchFromRatingNode(subtree, item, ratingName);
 904
 11905                                break;
 906                            }
 907
 908                        default:
 0909                            reader.Skip();
 0910                            break;
 911                    }
 912                }
 913                else
 914                {
 28915                    reader.Read();
 916                }
 917            }
 6918        }
 919
 920        private void FetchFromRatingNode(XmlReader reader, T item, string? ratingName)
 921        {
 11922            reader.MoveToContent();
 11923            reader.Read();
 924
 925            // Loop through each element
 77926            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
 927            {
 66928                if (reader.NodeType == XmlNodeType.Element)
 929                {
 22930                    switch (reader.Name)
 931                    {
 932                        case "value":
 11933                            var val = reader.ReadElementContentAsString();
 934
 11935                            if (float.TryParse(val, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out va
 936                            {
 937                                // if ratingName contains tomato --> assume critic rating
 11938                                if (ratingName is not null
 11939                                    && ratingName.Contains("tomato", StringComparison.OrdinalIgnoreCase)
 11940                                    && !ratingName.Contains("audience", StringComparison.OrdinalIgnoreCase))
 941                                {
 2942                                    if (!ratingName.Contains("avg", StringComparison.OrdinalIgnoreCase))
 943                                    {
 2944                                        item.CriticRating = ratingValue;
 945                                    }
 946                                }
 947                                else
 948                                {
 9949                                    item.CommunityRating = ratingValue;
 950                                }
 951                            }
 952
 9953                            break;
 954                        default:
 11955                            reader.Skip();
 11956                            break;
 957                    }
 958                }
 959                else
 960                {
 44961                    reader.Read();
 962                }
 963            }
 11964        }
 965
 966        internal XmlReaderSettings GetXmlReaderSettings()
 18967            => new XmlReaderSettings()
 18968            {
 18969                ValidationType = ValidationType.None,
 18970                CheckCharacters = false,
 18971                IgnoreProcessingInstructions = true,
 18972                IgnoreComments = true
 18973            };
 974
 975        /// <summary>
 976        /// Parses the <see cref="ImageType"/> from the NFO aspect property.
 977        /// </summary>
 978        /// <param name="aspect">The NFO aspect property.</param>
 979        /// <returns>The <see cref="ImageType"/>.</returns>
 980        private static ImageType GetImageType(string aspect)
 981        {
 159982            return aspect switch
 159983            {
 23984                "banner" => ImageType.Banner,
 23985                "clearlogo" => ImageType.Logo,
 12986                "discart" => ImageType.Disc,
 18987                "landscape" => ImageType.Thumb,
 8988                "clearart" => ImageType.Art,
 6989                "fanart" => ImageType.Backdrop,
 159990                // unknown type (including "poster") --> primary
 69991                _ => ImageType.Primary,
 159992            };
 993        }
 994    }
 995}