< Summary - Jellyfin

Information
Class: MediaBrowser.Controller.Entities.BaseItem
Assembly: MediaBrowser.Controller
File(s): /srv/git/jellyfin/MediaBrowser.Controller/Entities/BaseItem.cs
Line coverage
51%
Covered lines: 374
Uncovered lines: 358
Coverable lines: 732
Total lines: 2694
Line coverage: 51%
Branch coverage
39%
Covered branches: 185
Total branches: 464
Branch coverage: 39.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 12/27/2025 - 12:11:51 AM Line coverage: 51.2% (376/733) Branch coverage: 40.3% (188/466) Total lines: 269212/29/2025 - 12:13:19 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 26971/19/2026 - 12:13:54 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 27003/3/2026 - 12:13:24 AM Line coverage: 51.2% (375/731) Branch coverage: 40.2% (185/460) Total lines: 26884/7/2026 - 12:14:03 AM Line coverage: 51% (374/732) Branch coverage: 39.8% (185/464) Total lines: 2694 12/27/2025 - 12:11:51 AM Line coverage: 51.2% (376/733) Branch coverage: 40.3% (188/466) Total lines: 269212/29/2025 - 12:13:19 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 26971/19/2026 - 12:13:54 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 27003/3/2026 - 12:13:24 AM Line coverage: 51.2% (375/731) Branch coverage: 40.2% (185/460) Total lines: 26884/7/2026 - 12:14:03 AM Line coverage: 51% (374/732) Branch coverage: 39.8% (185/464) Total lines: 2694

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor()100%11100%
get_SupportsAddingToPlaylist()100%210%
get_AlwaysScanInternalMetadataPath()100%11100%
get_SupportsPlayedStatus()100%210%
get_SupportsPositionTicksResume()100%210%
get_SupportsRemoteImageDownloading()100%11100%
get_Name()100%11100%
set_Name(...)100%11100%
get_IsUnaired()0%620%
get_IsThemeMedia()0%2040%
get_DisplayPreferencesId()50%22100%
get_SourceType()50%2266.66%
get_ContainingFolderPath()100%22100%
get_IsHidden()100%210%
get_LocationType()33.33%11650%
get_PathProtocol()100%22100%
get_IsFileProtocol()100%11100%
get_HasPathProtocol()100%210%
get_SupportsLocalMetadata()50%2266.66%
get_FileNameWithoutExtension()0%620%
get_EnableAlphaNumericSorting()100%11100%
get_IsHD()100%11100%
get_PrimaryImagePath()100%210%
get_MediaType()100%11100%
get_PhysicalLocations()0%620%
get_EnableMediaSourceDisplay()50%2266.66%
get_ForcedSortName()100%11100%
set_ForcedSortName(...)100%11100%
get_SortName()75%4480%
set_SortName(...)100%11100%
get_DisplayParentId()100%11100%
get_DisplayParent()100%22100%
get_HasLocalAlternateVersions()100%210%
get_OfficialRatingForComparison()75%4485.71%
get_CustomRatingForComparison()100%11100%
get_LatestItemsIndexContainer()100%210%
get_EnableRememberingTrackSelections()100%210%
get_IsTopParent()80%121075%
get_SupportsAncestors()100%11100%
get_SupportsOwnedItems()100%22100%
get_SupportsPeople()100%11100%
get_SupportsThemeMedia()100%210%
get_SupportsInheritedParentImages()100%210%
get_IsFolder()100%11100%
get_IsDisplayedAsFolder()100%210%
GetCustomRatingForComparision(...)87.5%8888.88%
GetDefaultPrimaryImageAspectRatio()100%210%
CreatePresentationUniqueKey()100%11100%
CanDelete()0%620%
IsAuthorizedToDelete(...)0%7280%
GetOwner()50%22100%
CanDelete(...)50%22100%
CanDelete(...)100%11100%
CanDownload()100%11100%
IsAuthorizedToDownload(...)100%210%
CanDownload(...)50%22100%
ToString()100%11100%
GetInternalMetadataPath()100%11100%
GetInternalMetadataPath(...)50%2275%
CreateSortName()71.42%171475%
ModifySortChunks(...)87.5%8893.75%
GetParent()100%22100%
FindParent()0%2040%
GetPlayAccess(...)50%2266.66%
GetMediaStreams()100%210%
IsActiveRecording()100%210%
GetMediaSources(...)0%7280%
GetAllItemsForMediaSources()100%210%
GetVersionInfo(...)0%2970540%
GetMediaSourceName(...)68.75%743265.51%
RefreshMetadata(...)100%11100%
IsVisibleStandaloneInternal(...)0%210140%
SetParent(...)50%22100%
GetFileSystemChildren(...)100%11100%
GetPresentationUniqueKey()0%620%
RequiresRefresh()50%11650%
GetUserDataKeys()50%5466.66%
UpdateFromResolvedItem(...)50%2260%
AfterMetadataRefresh()100%11100%
GetPreferredMetadataLanguage()100%88100%
GetPreferredMetadataCountryCode()100%88100%
IsSaveLocalMetadataEnabled()50%2275%
IsParentalAllowed(...)25%641642.85%
GetParentalRatingScore()75%4483.33%
GetInheritedTags()75%4485.71%
IsVisibleViaTags(...)38.88%591850%
GetBlockUnratedType()50%2266.66%
GetBlockUnratedValue(...)50%5466.66%
IsVisible(...)100%11100%
IsVisibleStandalone(...)0%2040%
GetClientTypeName()70%141066.66%
GetBaseItemKind()100%22100%
GetLinkedChild(...)0%7280%
FindLinkedChild(...)0%7280%
AddStudio(...)50%4475%
SetStudios(...)100%210%
AddGenre(...)100%22100%
MarkPlayed(...)0%110100%
MarkUnplayed(...)100%210%
ChangedExternally()100%210%
HasImage(...)100%11100%
SetImage(...)75%4490.9%
SetImagePath(...)75%4490.9%
RemoveImage(...)100%210%
RemoveImages(...)100%11100%
AddImage(...)100%11100%
ValidateImages()100%1212100%
GetImagePath(...)50%22100%
GetImageInfo(...)16.66%24620%
GetImageIndex(...)0%110100%
AddImages(...)85%202091.3%
GetImageInfo(...)100%11100%
GetDeletePaths()100%210%
GetLocalMetadataFilesToDelete()0%2040%
AllowsMultipleImages(...)100%22100%
SwapImagesAsync(...)0%110100%
IsPlayed(...)0%2040%
IsFavoriteOrLiked(...)0%4260%
IsUnplayed(...)0%2040%
MediaBrowser.Controller.Providers.IHasLookupInfo<MediaBrowser.Controller.Providers.ItemLookupInfo>.GetLookupInfo()100%11100%
GetItemLookupInfo()100%11100%
GetNameForMetadataLookup()100%11100%
BeforeMetadataRefresh(...)50%5466.66%
GetMappedPath(...)0%620%
FillUserDataDtoValues(...)0%4260%
GetEtag(...)100%11100%
GetEtagValues(...)100%11100%
GetAncestorIds()100%11100%
GetTopParent()100%22100%
GetIdsForAncestorQuery()100%11100%
GetRefreshProgress()100%210%
OnMetadataChanged()37.5%22840%
UpdateRatingToItems(...)0%4260%
GetThemeSongs(...)100%210%
GetThemeSongs(...)100%210%
GetThemeVideos(...)100%210%
GetThemeVideos(...)100%210%
GetExtras()100%11100%
GetExtras(...)100%210%
GetRunTimeTicksForPlayState()100%210%
Equals(...)0%620%
Equals(...)50%22100%
GetHashCode()100%11100%

File(s)

/srv/git/jellyfin/MediaBrowser.Controller/Entities/BaseItem.cs

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CS1591, SA1401
 4
 5using System;
 6using System.Collections.Generic;
 7using System.Collections.Immutable;
 8using System.Globalization;
 9using System.IO;
 10using System.Linq;
 11using System.Text;
 12using System.Text.Json.Serialization;
 13using System.Threading;
 14using System.Threading.Tasks;
 15using Jellyfin.Data;
 16using Jellyfin.Data.Enums;
 17using Jellyfin.Database.Implementations.Entities;
 18using Jellyfin.Database.Implementations.Enums;
 19using Jellyfin.Extensions;
 20using MediaBrowser.Common.Extensions;
 21using MediaBrowser.Controller.Channels;
 22using MediaBrowser.Controller.Chapters;
 23using MediaBrowser.Controller.Configuration;
 24using MediaBrowser.Controller.Dto;
 25using MediaBrowser.Controller.Entities.TV;
 26using MediaBrowser.Controller.IO;
 27using MediaBrowser.Controller.Library;
 28using MediaBrowser.Controller.MediaSegments;
 29using MediaBrowser.Controller.Persistence;
 30using MediaBrowser.Controller.Providers;
 31using MediaBrowser.Model.Dto;
 32using MediaBrowser.Model.Entities;
 33using MediaBrowser.Model.Globalization;
 34using MediaBrowser.Model.IO;
 35using MediaBrowser.Model.Library;
 36using MediaBrowser.Model.LiveTv;
 37using MediaBrowser.Model.MediaInfo;
 38using Microsoft.Extensions.Logging;
 39
 40namespace MediaBrowser.Controller.Entities
 41{
 42    /// <summary>
 43    /// Class BaseItem.
 44    /// </summary>
 45    public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
 46    {
 47        private BaseItemKind? _baseItemKind;
 48
 49        public const string ThemeSongFileName = "theme";
 50
 51        /// <summary>
 52        /// The supported image extensions.
 53        /// </summary>
 454        public static readonly string[] SupportedImageExtensions
 455            = [".png", ".jpg", ".jpeg", ".webp", ".tbn", ".gif", ".svg"];
 56
 457        private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
 458        {
 459            ".nfo",
 460            ".xml",
 461            ".srt",
 462            ".vtt",
 463            ".sub",
 464            ".sup",
 465            ".idx",
 466            ".txt",
 467            ".edl",
 468            ".bif",
 469            ".smi",
 470            ".ttml",
 471            ".lrc",
 472            ".elrc"
 473        };
 74
 75        /// <summary>
 76        /// Extra types that should be counted and displayed as "Special Features" in the UI.
 77        /// </summary>
 478        public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
 479        {
 480            Model.Entities.ExtraType.Unknown,
 481            Model.Entities.ExtraType.BehindTheScenes,
 482            Model.Entities.ExtraType.Clip,
 483            Model.Entities.ExtraType.DeletedScene,
 484            Model.Entities.ExtraType.Interview,
 485            Model.Entities.ExtraType.Sample,
 486            Model.Entities.ExtraType.Scene,
 487            Model.Entities.ExtraType.Featurette,
 488            Model.Entities.ExtraType.Short
 489        };
 90
 91        private string _sortName;
 92
 93        private string _forcedSortName;
 94
 95        private string _name;
 96
 97        public const char SlugChar = '-';
 98
 99        protected BaseItem()
 100        {
 950101            Tags = Array.Empty<string>();
 950102            Genres = Array.Empty<string>();
 950103            Studios = Array.Empty<string>();
 950104            ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 950105            LockedFields = Array.Empty<MetadataField>();
 950106            ImageInfos = Array.Empty<ItemImageInfo>();
 950107            ProductionLocations = Array.Empty<string>();
 950108            RemoteTrailers = Array.Empty<MediaUrl>();
 950109            ExtraIds = Array.Empty<Guid>();
 950110            UserData = [];
 950111        }
 112
 113        /// <summary>
 114        /// Gets or Sets the user data collection as cached from the last Db query.
 115        /// </summary>
 116        [JsonIgnore]
 117        public ICollection<UserData> UserData { get; set; }
 118
 119        [JsonIgnore]
 120        public string PreferredMetadataCountryCode { get; set; }
 121
 122        [JsonIgnore]
 123        public string PreferredMetadataLanguage { get; set; }
 124
 125        public long? Size { get; set; }
 126
 127        public string Container { get; set; }
 128
 129        [JsonIgnore]
 130        public string Tagline { get; set; }
 131
 132        [JsonIgnore]
 133        public virtual ItemImageInfo[] ImageInfos { get; set; }
 134
 135        [JsonIgnore]
 136        public bool IsVirtualItem { get; set; }
 137
 138        /// <summary>
 139        /// Gets or sets the album.
 140        /// </summary>
 141        /// <value>The album.</value>
 142        [JsonIgnore]
 143        public string Album { get; set; }
 144
 145        /// <summary>
 146        /// Gets or sets the LUFS value.
 147        /// </summary>
 148        /// <value>The LUFS Value.</value>
 149        [JsonIgnore]
 150        public float? LUFS { get; set; }
 151
 152        /// <summary>
 153        /// Gets or sets the gain required for audio normalization.
 154        /// </summary>
 155        /// <value>The gain required for audio normalization.</value>
 156        [JsonIgnore]
 157        public float? NormalizationGain { get; set; }
 158
 159        /// <summary>
 160        /// Gets or sets the channel identifier.
 161        /// </summary>
 162        /// <value>The channel identifier.</value>
 163        [JsonIgnore]
 164        public Guid ChannelId { get; set; }
 165
 166        [JsonIgnore]
 0167        public virtual bool SupportsAddingToPlaylist => false;
 168
 169        [JsonIgnore]
 13170        public virtual bool AlwaysScanInternalMetadataPath => false;
 171
 172        /// <summary>
 173        /// Gets or sets a value indicating whether this instance is in mixed folder.
 174        /// </summary>
 175        /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
 176        [JsonIgnore]
 177        public bool IsInMixedFolder { get; set; }
 178
 179        [JsonIgnore]
 0180        public virtual bool SupportsPlayedStatus => false;
 181
 182        [JsonIgnore]
 0183        public virtual bool SupportsPositionTicksResume => false;
 184
 185        [JsonIgnore]
 17186        public virtual bool SupportsRemoteImageDownloading => true;
 187
 188        /// <summary>
 189        /// Gets or sets the name.
 190        /// </summary>
 191        /// <value>The name.</value>
 192        [JsonIgnore]
 193        public virtual string Name
 194        {
 953195            get => _name;
 196            set
 197            {
 349198                _name = value;
 199
 200                // lazy load this again
 349201                _sortName = null;
 349202            }
 203        }
 204
 205        [JsonIgnore]
 0206        public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
 207
 208        [JsonIgnore]
 209        public int? TotalBitrate { get; set; }
 210
 211        [JsonIgnore]
 212        public ExtraType? ExtraType { get; set; }
 213
 214        [JsonIgnore]
 0215        public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || Extr
 216
 217        [JsonIgnore]
 218        public string OriginalTitle { get; set; }
 219
 220        /// <summary>
 221        /// Gets or sets the id.
 222        /// </summary>
 223        /// <value>The id.</value>
 224        [JsonIgnore]
 225        public Guid Id { get; set; }
 226
 227        [JsonIgnore]
 228        public Guid OwnerId { get; set; }
 229
 230        /// <summary>
 231        /// Gets or sets the audio.
 232        /// </summary>
 233        /// <value>The audio.</value>
 234        [JsonIgnore]
 235        public ProgramAudio? Audio { get; set; }
 236
 237        /// <summary>
 238        /// Gets the id that should be used to key display prefs for this item.
 239        /// Default is based on the type for everything except actual generic folders.
 240        /// </summary>
 241        /// <value>The display prefs id.</value>
 242        [JsonIgnore]
 243        public virtual Guid DisplayPreferencesId
 244        {
 245            get
 246            {
 6247                var thisType = GetType();
 6248                return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
 249            }
 250        }
 251
 252        /// <summary>
 253        /// Gets or sets the path.
 254        /// </summary>
 255        /// <value>The path.</value>
 256        [JsonIgnore]
 257        public virtual string Path { get; set; }
 258
 259        [JsonIgnore]
 260        public virtual SourceType SourceType
 261        {
 262            get
 263            {
 2044264                if (!ChannelId.IsEmpty())
 265                {
 0266                    return SourceType.Channel;
 267                }
 268
 2044269                return SourceType.Library;
 270            }
 271        }
 272
 273        /// <summary>
 274        /// Gets the folder containing the item.
 275        /// If the item is a folder, it returns the folder itself.
 276        /// </summary>
 277        [JsonIgnore]
 278        public virtual string ContainingFolderPath
 279        {
 280            get
 281            {
 429282                if (IsFolder)
 283                {
 370284                    return Path;
 285                }
 286
 59287                return System.IO.Path.GetDirectoryName(Path);
 288            }
 289        }
 290
 291        /// <summary>
 292        /// Gets or sets the name of the service.
 293        /// </summary>
 294        /// <value>The name of the service.</value>
 295        [JsonIgnore]
 296        public string ServiceName { get; set; }
 297
 298        /// <summary>
 299        /// Gets or sets the external id.
 300        /// </summary>
 301        /// <remarks>
 302        /// If this content came from an external service, the id of the content on that service.
 303        /// </remarks>
 304        [JsonIgnore]
 305        public string ExternalId { get; set; }
 306
 307        [JsonIgnore]
 308        public string ExternalSeriesId { get; set; }
 309
 310        [JsonIgnore]
 0311        public virtual bool IsHidden => false;
 312
 313        /// <summary>
 314        /// Gets the type of the location.
 315        /// </summary>
 316        /// <value>The type of the location.</value>
 317        [JsonIgnore]
 318        public virtual LocationType LocationType
 319        {
 320            get
 321            {
 9322                var path = Path;
 9323                if (string.IsNullOrEmpty(path))
 324                {
 0325                    if (SourceType == SourceType.Channel)
 326                    {
 0327                        return LocationType.Remote;
 328                    }
 329
 0330                    return LocationType.Virtual;
 331                }
 332
 9333                return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
 334            }
 335        }
 336
 337        [JsonIgnore]
 338        public MediaProtocol? PathProtocol
 339        {
 340            get
 341            {
 2399342                var path = Path;
 343
 2399344                if (string.IsNullOrEmpty(path))
 345                {
 116346                    return null;
 347                }
 348
 2283349                return MediaSourceManager.GetPathProtocol(path);
 350            }
 351        }
 352
 353        [JsonIgnore]
 2378354        public bool IsFileProtocol => PathProtocol == MediaProtocol.File;
 355
 356        [JsonIgnore]
 0357        public bool HasPathProtocol => PathProtocol.HasValue;
 358
 359        [JsonIgnore]
 360        public virtual bool SupportsLocalMetadata
 361        {
 362            get
 363            {
 1265364                if (SourceType == SourceType.Channel)
 365                {
 0366                    return false;
 367                }
 368
 1265369                return IsFileProtocol;
 370            }
 371        }
 372
 373        [JsonIgnore]
 374        public virtual string FileNameWithoutExtension
 375        {
 376            get
 377            {
 0378                if (IsFileProtocol)
 379                {
 0380                    return System.IO.Path.GetFileNameWithoutExtension(Path);
 381                }
 382
 0383                return null;
 384            }
 385        }
 386
 387        [JsonIgnore]
 99388        public virtual bool EnableAlphaNumericSorting => true;
 389
 135390        public virtual bool IsHD => Height >= 720;
 391
 392        public bool IsShortcut { get; set; }
 393
 394        public string ShortcutPath { get; set; }
 395
 396        public int Width { get; set; }
 397
 398        public int Height { get; set; }
 399
 400        public Guid[] ExtraIds { get; set; }
 401
 402        /// <summary>
 403        /// Gets the primary image path.
 404        /// </summary>
 405        /// <remarks>
 406        /// This is just a helper for convenience.
 407        /// </remarks>
 408        /// <value>The primary image path.</value>
 409        [JsonIgnore]
 0410        public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
 411
 412        /// <summary>
 413        /// Gets or sets the date created.
 414        /// </summary>
 415        /// <value>The date created.</value>
 416        [JsonIgnore]
 417        public DateTime DateCreated { get; set; }
 418
 419        /// <summary>
 420        /// Gets or sets the date modified.
 421        /// </summary>
 422        /// <value>The date modified.</value>
 423        [JsonIgnore]
 424        public DateTime DateModified { get; set; }
 425
 426        public DateTime DateLastSaved { get; set; }
 427
 428        [JsonIgnore]
 429        public DateTime DateLastRefreshed { get; set; }
 430
 431        [JsonIgnore]
 432        public bool IsLocked { get; set; }
 433
 434        /// <summary>
 435        /// Gets or sets the locked fields.
 436        /// </summary>
 437        /// <value>The locked fields.</value>
 438        [JsonIgnore]
 439        public MetadataField[] LockedFields { get; set; }
 440
 441        /// <summary>
 442        /// Gets the type of the media.
 443        /// </summary>
 444        /// <value>The type of the media.</value>
 445        [JsonIgnore]
 128446        public virtual MediaType MediaType => MediaType.Unknown;
 447
 448        [JsonIgnore]
 449        public virtual string[] PhysicalLocations
 450        {
 451            get
 452            {
 0453                if (!IsFileProtocol)
 454                {
 0455                    return Array.Empty<string>();
 456                }
 457
 0458                return [Path];
 459            }
 460        }
 461
 462        [JsonIgnore]
 463        public bool EnableMediaSourceDisplay
 464        {
 465            get
 466            {
 6467                if (SourceType == SourceType.Channel)
 468                {
 0469                    return ChannelManager.EnableMediaSourceDisplay(this);
 470                }
 471
 6472                return true;
 473            }
 474        }
 475
 476        [JsonIgnore]
 477        public Guid ParentId { get; set; }
 478
 479        /// <summary>
 480        /// Gets or sets the logger.
 481        /// </summary>
 482        public static ILogger<BaseItem> Logger { get; set; }
 483
 484        public static ILibraryManager LibraryManager { get; set; }
 485
 486        public static IServerConfigurationManager ConfigurationManager { get; set; }
 487
 488        public static IProviderManager ProviderManager { get; set; }
 489
 490        public static ILocalizationManager LocalizationManager { get; set; }
 491
 492        public static IItemRepository ItemRepository { get; set; }
 493
 494        public static IChapterManager ChapterManager { get; set; }
 495
 496        public static IFileSystem FileSystem { get; set; }
 497
 498        public static IUserDataManager UserDataManager { get; set; }
 499
 500        public static IChannelManager ChannelManager { get; set; }
 501
 502        public static IMediaSourceManager MediaSourceManager { get; set; }
 503
 504        public static IMediaSegmentManager MediaSegmentManager { get; set; }
 505
 506        /// <summary>
 507        /// Gets or sets the name of the forced sort.
 508        /// </summary>
 509        /// <value>The name of the forced sort.</value>
 510        [JsonIgnore]
 511        public string ForcedSortName
 512        {
 469513            get => _forcedSortName;
 514            set
 515            {
 88516                _forcedSortName = value;
 88517                _sortName = null;
 88518            }
 519        }
 520
 521        /// <summary>
 522        /// Gets or sets the name of the sort.
 523        /// </summary>
 524        /// <value>The name of the sort.</value>
 525        [JsonIgnore]
 526        public string SortName
 527        {
 528            get
 529            {
 168530                if (_sortName is null)
 531                {
 99532                    if (!string.IsNullOrEmpty(ForcedSortName))
 533                    {
 534                        // Need the ToLower because that's what CreateSortName does
 0535                        _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
 536                    }
 537                    else
 538                    {
 99539                        _sortName = CreateSortName();
 540                    }
 541                }
 542
 168543                return _sortName;
 544            }
 545
 127546            set => _sortName = value;
 547        }
 548
 549        [JsonIgnore]
 332550        public virtual Guid DisplayParentId => ParentId;
 551
 552        [JsonIgnore]
 553        public BaseItem DisplayParent
 554        {
 555            get
 556            {
 326557                var id = DisplayParentId;
 326558                if (id.IsEmpty())
 559                {
 248560                    return null;
 561                }
 562
 78563                return LibraryManager.GetItemById(id);
 564            }
 565        }
 566
 567        /// <summary>
 568        /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be
 569        /// </summary>
 570        /// <value>The premiere date.</value>
 571        [JsonIgnore]
 572        public DateTime? PremiereDate { get; set; }
 573
 574        /// <summary>
 575        /// Gets or sets the end date.
 576        /// </summary>
 577        /// <value>The end date.</value>
 578        [JsonIgnore]
 579        public DateTime? EndDate { get; set; }
 580
 581        /// <summary>
 582        /// Gets or sets the official rating.
 583        /// </summary>
 584        /// <value>The official rating.</value>
 585        [JsonIgnore]
 586        public string OfficialRating { get; set; }
 587
 588        [JsonIgnore]
 589        public int? InheritedParentalRatingValue { get; set; }
 590
 591        [JsonIgnore]
 592        public int? InheritedParentalRatingSubValue { get; set; }
 593
 594        /// <summary>
 595        /// Gets or sets the critic rating.
 596        /// </summary>
 597        /// <value>The critic rating.</value>
 598        [JsonIgnore]
 599        public float? CriticRating { get; set; }
 600
 601        /// <summary>
 602        /// Gets or sets the custom rating.
 603        /// </summary>
 604        /// <value>The custom rating.</value>
 605        [JsonIgnore]
 606        public string CustomRating { get; set; }
 607
 608        /// <summary>
 609        /// Gets or sets the overview.
 610        /// </summary>
 611        /// <value>The overview.</value>
 612        [JsonIgnore]
 613        public string Overview { get; set; }
 614
 615        /// <summary>
 616        /// Gets or sets the studios.
 617        /// </summary>
 618        /// <value>The studios.</value>
 619        [JsonIgnore]
 620        public string[] Studios { get; set; }
 621
 622        /// <summary>
 623        /// Gets or sets the genres.
 624        /// </summary>
 625        /// <value>The genres.</value>
 626        [JsonIgnore]
 627        public string[] Genres { get; set; }
 628
 629        /// <summary>
 630        /// Gets or sets the tags.
 631        /// </summary>
 632        /// <value>The tags.</value>
 633        [JsonIgnore]
 634        public string[] Tags { get; set; }
 635
 636        [JsonIgnore]
 637        public string[] ProductionLocations { get; set; }
 638
 639        /// <summary>
 640        /// Gets or sets the home page URL.
 641        /// </summary>
 642        /// <value>The home page URL.</value>
 643        [JsonIgnore]
 644        public string HomePageUrl { get; set; }
 645
 646        /// <summary>
 647        /// Gets or sets the community rating.
 648        /// </summary>
 649        /// <value>The community rating.</value>
 650        [JsonIgnore]
 651        public float? CommunityRating { get; set; }
 652
 653        /// <summary>
 654        /// Gets or sets the run time ticks.
 655        /// </summary>
 656        /// <value>The run time ticks.</value>
 657        [JsonIgnore]
 658        public long? RunTimeTicks { get; set; }
 659
 660        /// <summary>
 661        /// Gets or sets the production year.
 662        /// </summary>
 663        /// <value>The production year.</value>
 664        [JsonIgnore]
 665        public int? ProductionYear { get; set; }
 666
 667        /// <summary>
 668        /// Gets or sets the index number. If the item is part of a series, this is it's number in the series.
 669        /// This could be episode number, album track number, etc.
 670        /// </summary>
 671        /// <value>The index number.</value>
 672        [JsonIgnore]
 673        public int? IndexNumber { get; set; }
 674
 675        /// <summary>
 676        /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this cou
 677        /// </summary>
 678        /// <value>The parent index number.</value>
 679        [JsonIgnore]
 680        public int? ParentIndexNumber { get; set; }
 681
 682        [JsonIgnore]
 0683        public virtual bool HasLocalAlternateVersions => false;
 684
 685        [JsonIgnore]
 686        public string OfficialRatingForComparison
 687        {
 688            get
 689            {
 163690                var officialRating = OfficialRating;
 163691                if (!string.IsNullOrEmpty(officialRating))
 692                {
 0693                    return officialRating;
 694                }
 695
 163696                var parent = DisplayParent;
 163697                if (parent is not null)
 698                {
 39699                    return parent.OfficialRatingForComparison;
 700                }
 701
 124702                return null;
 703            }
 704        }
 705
 706        [JsonIgnore]
 707        public string CustomRatingForComparison
 708        {
 709            get
 710            {
 124711                return GetCustomRatingForComparision();
 712            }
 713        }
 714
 715        /// <summary>
 716        /// Gets or sets the provider ids.
 717        /// </summary>
 718        /// <value>The provider ids.</value>
 719        [JsonIgnore]
 720        public Dictionary<string, string> ProviderIds { get; set; }
 721
 722        [JsonIgnore]
 0723        public virtual Folder LatestItemsIndexContainer => null;
 724
 725        [JsonIgnore]
 726        public string PresentationUniqueKey { get; set; }
 727
 728        [JsonIgnore]
 0729        public virtual bool EnableRememberingTrackSelections => true;
 730
 731        [JsonIgnore]
 732        public virtual bool IsTopParent
 733        {
 734            get
 735            {
 258736                if (this is BasePluginFolder || this is Channel)
 737                {
 58738                    return true;
 739                }
 740
 200741                if (this is IHasCollectionType view)
 742                {
 13743                    if (view.CollectionType == CollectionType.livetv)
 744                    {
 0745                        return true;
 746                    }
 747                }
 748
 200749                if (GetParent() is AggregateFolder)
 750                {
 0751                    return true;
 752                }
 753
 200754                return false;
 755            }
 756        }
 757
 758        [JsonIgnore]
 218759        public virtual bool SupportsAncestors => true;
 760
 761        [JsonIgnore]
 90762        protected virtual bool SupportsOwnedItems => !ParentId.IsEmpty() && IsFileProtocol;
 763
 764        [JsonIgnore]
 66765        public virtual bool SupportsPeople => false;
 766
 767        [JsonIgnore]
 0768        public virtual bool SupportsThemeMedia => false;
 769
 770        [JsonIgnore]
 0771        public virtual bool SupportsInheritedParentImages => false;
 772
 773        /// <summary>
 774        /// Gets a value indicating whether this instance is folder.
 775        /// </summary>
 776        /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
 777        [JsonIgnore]
 79778        public virtual bool IsFolder => false;
 779
 780        [JsonIgnore]
 0781        public virtual bool IsDisplayedAsFolder => false;
 782
 783        /// <summary>
 784        /// Gets or sets the remote trailers.
 785        /// </summary>
 786        /// <value>The remote trailers.</value>
 787        public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
 788
 789        private string GetCustomRatingForComparision(HashSet<Guid> callstack = null)
 790        {
 163791            callstack ??= new();
 163792            var customRating = CustomRating;
 163793            if (!string.IsNullOrEmpty(customRating))
 794            {
 0795                return customRating;
 796            }
 797
 163798            callstack.Add(Id);
 799
 163800            var parent = DisplayParent;
 163801            if (parent is not null && !callstack.Contains(parent.Id))
 802            {
 39803                return parent.GetCustomRatingForComparision(callstack);
 804            }
 805
 124806            return null;
 807        }
 808
 809        public virtual double GetDefaultPrimaryImageAspectRatio()
 810        {
 0811            return 0;
 812        }
 813
 814        public virtual string CreatePresentationUniqueKey()
 815        {
 56816            return Id.ToString("N", CultureInfo.InvariantCulture);
 817        }
 818
 819        public virtual bool CanDelete()
 820        {
 0821            if (SourceType == SourceType.Channel)
 822            {
 0823                return ChannelManager.CanDelete(this);
 824            }
 825
 0826            return IsFileProtocol;
 827        }
 828
 829        public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
 830        {
 0831            if (user.HasPermission(PermissionKind.EnableContentDeletion))
 832            {
 0833                return true;
 834            }
 835
 0836            var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
 837
 0838            if (SourceType == SourceType.Channel)
 839            {
 0840                return allowed.Contains(ChannelId);
 841            }
 842
 0843            var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
 844
 0845            foreach (var folder in collectionFolders)
 846            {
 0847                if (allowed.Contains(folder.Id))
 848                {
 0849                    return true;
 850                }
 851            }
 852
 0853            return false;
 0854        }
 855
 856        public BaseItem GetOwner()
 857        {
 616858            var ownerId = OwnerId;
 616859            return ownerId.IsEmpty() ? null : LibraryManager.GetItemById(ownerId);
 860        }
 861
 862        public bool CanDelete(User user, List<Folder> allCollectionFolders)
 863        {
 6864            return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
 865        }
 866
 867        public virtual bool CanDelete(User user)
 868        {
 6869            var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
 870
 6871            return CanDelete(user, allCollectionFolders);
 872        }
 873
 874        public virtual bool CanDownload()
 875        {
 6876            return false;
 877        }
 878
 879        public virtual bool IsAuthorizedToDownload(User user)
 880        {
 0881            return user.HasPermission(PermissionKind.EnableContentDownloading);
 882        }
 883
 884        public bool CanDownload(User user)
 885        {
 6886            return CanDownload() && IsAuthorizedToDownload(user);
 887        }
 888
 889        /// <inheritdoc />
 890        public override string ToString()
 891        {
 69892            return Name;
 893        }
 894
 895        public virtual string GetInternalMetadataPath()
 896        {
 71897            var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
 898
 71899            return GetInternalMetadataPath(basePath);
 900        }
 901
 902        protected virtual string GetInternalMetadataPath(string basePath)
 903        {
 71904            if (SourceType == SourceType.Channel)
 905            {
 0906                return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), 
 907            }
 908
 71909            ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
 910
 71911            return System.IO.Path.Join(basePath, "library", idString[..2], idString);
 912        }
 913
 914        /// <summary>
 915        /// Creates the name of the sort.
 916        /// </summary>
 917        /// <returns>System.String.</returns>
 918        protected virtual string CreateSortName()
 919        {
 99920            if (Name is null)
 921            {
 0922                return null; // some items may not have name filled in properly
 923            }
 924
 99925            if (!EnableAlphaNumericSorting)
 926            {
 0927                return Name.TrimStart();
 928            }
 929
 99930            var sortable = Name.Trim().ToLowerInvariant();
 931
 792932            foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
 933            {
 934                // Remove from beginning if a space follows
 297935                if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
 936                {
 0937                    sortable = sortable.Remove(0, search.Length + 1);
 938                }
 939
 940                // Remove from middle if surrounded by spaces
 297941                sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
 942
 943                // Remove from end if preceeded by a space
 297944                if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
 945                {
 0946                    sortable = sortable.Remove(sortable.Length - (search.Length + 1));
 947                }
 948            }
 949
 1386950            foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
 951            {
 594952                sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
 953            }
 954
 792955            foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
 956            {
 297957                sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
 958            }
 959
 99960            return ModifySortChunks(sortable);
 961        }
 962
 963        internal static string ModifySortChunks(ReadOnlySpan<char> name)
 964        {
 965            static void AppendChunk(StringBuilder builder, bool isDigitChunk, ReadOnlySpan<char> chunk)
 966            {
 967                if (isDigitChunk && chunk.Length < 10)
 968                {
 969                    builder.Append('0', 10 - chunk.Length);
 970                }
 971
 972                builder.Append(chunk);
 973            }
 974
 105975            if (name.IsEmpty)
 976            {
 1977                return string.Empty;
 978            }
 979
 104980            var builder = new StringBuilder(name.Length);
 981
 104982            int chunkStart = 0;
 104983            bool isDigitChunk = char.IsDigit(name[0]);
 1664984            for (int i = 0; i < name.Length; i++)
 985            {
 728986                var isDigit = char.IsDigit(name[i]);
 728987                if (isDigit != isDigitChunk)
 988                {
 5989                    AppendChunk(builder, isDigitChunk, name.Slice(chunkStart, i - chunkStart));
 5990                    chunkStart = i;
 5991                    isDigitChunk = isDigit;
 992                }
 993            }
 994
 104995            AppendChunk(builder, isDigitChunk, name.Slice(chunkStart));
 996
 997            // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
 104998            var result = builder.ToString().RemoveDiacritics();
 104999            if (!result.All(char.IsAscii))
 1000            {
 01001                result = result.Transliterated();
 1002            }
 1003
 1041004            return result;
 1005        }
 1006
 1007        public BaseItem GetParent()
 1008        {
 17421009            var parentId = ParentId;
 17421010            if (parentId.IsEmpty())
 1011            {
 14731012                return null;
 1013            }
 1014
 2691015            return LibraryManager.GetItemById(parentId);
 1016        }
 1017
 1018        public IEnumerable<BaseItem> GetParents()
 1019        {
 1020            var parent = GetParent();
 1021
 1022            while (parent is not null)
 1023            {
 1024                yield return parent;
 1025
 1026                parent = parent.GetParent();
 1027            }
 1028        }
 1029
 1030        /// <summary>
 1031        /// Finds a parent of a given type.
 1032        /// </summary>
 1033        /// <typeparam name="T">Type of parent.</typeparam>
 1034        /// <returns>``0.</returns>
 1035        public T FindParent<T>()
 1036            where T : Folder
 1037        {
 01038            foreach (var parent in GetParents())
 1039            {
 01040                if (parent is T item)
 1041                {
 01042                    return item;
 1043                }
 1044            }
 1045
 01046            return null;
 01047        }
 1048
 1049        /// <summary>
 1050        /// Gets the play access.
 1051        /// </summary>
 1052        /// <param name="user">The user.</param>
 1053        /// <returns>PlayAccess.</returns>
 1054        public PlayAccess GetPlayAccess(User user)
 1055        {
 61056            if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
 1057            {
 01058                return PlayAccess.None;
 1059            }
 1060
 1061            // if (!user.IsParentalScheduleAllowed())
 1062            // {
 1063            //    return PlayAccess.None;
 1064            // }
 1065
 61066            return PlayAccess.Full;
 1067        }
 1068
 1069        public virtual IReadOnlyList<MediaStream> GetMediaStreams()
 1070        {
 01071            return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
 01072            {
 01073                ItemId = Id
 01074            });
 1075        }
 1076
 1077        protected virtual bool IsActiveRecording()
 1078        {
 01079            return false;
 1080        }
 1081
 1082        public virtual IReadOnlyList<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
 1083        {
 01084            if (SourceType == SourceType.Channel)
 1085            {
 01086                var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
 01087                           .ToList();
 1088
 01089                if (sources.Count > 0)
 1090                {
 01091                    return sources;
 1092                }
 1093            }
 1094
 01095            var list = GetAllItemsForMediaSources();
 01096            var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item, i.MediaSourceType)).ToList();
 1097
 01098            if (IsActiveRecording())
 1099            {
 01100                foreach (var mediaSource in result)
 1101                {
 01102                    mediaSource.Type = MediaSourceType.Placeholder;
 1103                }
 1104            }
 1105
 01106            return result.OrderBy(i =>
 01107            {
 01108                if (i.VideoType == VideoType.VideoFile)
 01109                {
 01110                    return 0;
 01111                }
 01112
 01113                return 1;
 01114            }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
 01115            .ThenByDescending(i => i, new MediaSourceWidthComparator())
 01116            .ToArray();
 1117        }
 1118
 1119        protected virtual IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
 1120        {
 01121            return Enumerable.Empty<(BaseItem, MediaSourceType)>();
 1122        }
 1123
 1124        private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
 1125        {
 01126            ArgumentNullException.ThrowIfNull(item);
 1127
 01128            var protocol = item.PathProtocol;
 1129
 1130            // Resolve the item path so everywhere we use the media source it will always point to
 1131            // the correct path even if symlinks are in use. Calling ResolveLinkTarget on a non-link
 1132            // path will return null, so it's safe to check for all paths.
 01133            var itemPath = item.Path;
 01134            if (protocol is MediaProtocol.File && FileSystemHelper.ResolveLinkTarget(itemPath, returnFinalTarget: true) 
 1135            {
 01136                itemPath = linkInfo.FullName;
 1137            }
 1138
 01139            var info = new MediaSourceInfo
 01140            {
 01141                Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
 01142                Protocol = protocol ?? MediaProtocol.File,
 01143                MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
 01144                MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
 01145                Name = GetMediaSourceName(item),
 01146                Path = enablePathSubstitution ? GetMappedPath(item, itemPath, protocol) : itemPath,
 01147                RunTimeTicks = item.RunTimeTicks,
 01148                Container = item.Container,
 01149                Size = item.Size,
 01150                Type = type,
 01151                HasSegments = MediaSegmentManager.IsTypeSupported(item)
 01152                    && (protocol is null or MediaProtocol.File)
 01153                    && MediaSegmentManager.HasSegments(item.Id)
 01154            };
 1155
 01156            if (string.IsNullOrEmpty(info.Path))
 1157            {
 01158                info.Type = MediaSourceType.Placeholder;
 1159            }
 1160
 01161            if (info.Protocol == MediaProtocol.File)
 1162            {
 01163                info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", Cultur
 1164            }
 1165
 01166            var video = item as Video;
 01167            if (video is not null)
 1168            {
 01169                info.IsoType = video.IsoType;
 01170                info.VideoType = video.VideoType;
 01171                info.Video3DFormat = video.Video3DFormat;
 01172                info.Timestamp = video.Timestamp;
 1173
 01174                if (video.IsShortcut && !string.IsNullOrEmpty(video.ShortcutPath))
 1175                {
 01176                    var shortcutProtocol = MediaSourceManager.GetPathProtocol(video.ShortcutPath);
 1177
 1178                    // Only allow remote shortcut paths — local file paths in .strm files
 1179                    // could be used to read arbitrary files from the server.
 01180                    if (shortcutProtocol != MediaProtocol.File)
 1181                    {
 01182                        info.IsRemote = true;
 01183                        info.Path = video.ShortcutPath;
 01184                        info.Protocol = shortcutProtocol;
 1185                    }
 1186                }
 1187
 01188                if (string.IsNullOrEmpty(info.Container))
 1189                {
 01190                    if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
 1191                    {
 01192                        if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1193                        {
 01194                            info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1195                        }
 1196                    }
 1197                }
 1198            }
 1199
 01200            if (string.IsNullOrEmpty(info.Container))
 1201            {
 01202                if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1203                {
 01204                    info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1205                }
 1206            }
 1207
 01208            if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
 1209            {
 01210                info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
 1211            }
 1212
 01213            if (video is not null && video.VideoType != VideoType.VideoFile)
 1214            {
 01215                info.SupportsDirectStream = false;
 1216            }
 1217
 01218            info.Bitrate = item.TotalBitrate;
 01219            info.InferTotalBitrate();
 1220
 01221            return info;
 1222        }
 1223
 1224        internal string GetMediaSourceName(BaseItem item)
 1225        {
 41226            var terms = new List<string>();
 1227
 41228            var path = item.Path;
 41229            if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
 1230            {
 41231                var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
 41232                if (HasLocalAlternateVersions)
 1233                {
 41234                    var containingFolderName = System.IO.Path.GetFileName(ContainingFolderPath);
 41235                    if (displayName.Length > containingFolderName.Length && displayName.StartsWith(containingFolderName,
 1236                    {
 21237                        var name = displayName.AsSpan(containingFolderName.Length).TrimStart([' ', '-']);
 21238                        if (!name.IsWhiteSpace())
 1239                        {
 21240                            terms.Add(name.ToString());
 1241                        }
 1242                    }
 1243                }
 1244
 41245                if (terms.Count == 0)
 1246                {
 21247                    terms.Add(displayName);
 1248                }
 1249            }
 1250
 41251            if (terms.Count == 0)
 1252            {
 01253                terms.Add(item.Name);
 1254            }
 1255
 41256            if (item is Video video)
 1257            {
 41258                if (video.Video3DFormat.HasValue)
 1259                {
 01260                    terms.Add("3D");
 1261                }
 1262
 41263                if (video.VideoType == VideoType.BluRay)
 1264                {
 01265                    terms.Add("Bluray");
 1266                }
 41267                else if (video.VideoType == VideoType.Dvd)
 1268                {
 01269                    terms.Add("DVD");
 1270                }
 41271                else if (video.VideoType == VideoType.Iso)
 1272                {
 01273                    if (video.IsoType.HasValue)
 1274                    {
 01275                        if (video.IsoType.Value == IsoType.BluRay)
 1276                        {
 01277                            terms.Add("Bluray");
 1278                        }
 01279                        else if (video.IsoType.Value == IsoType.Dvd)
 1280                        {
 01281                            terms.Add("DVD");
 1282                        }
 1283                    }
 1284                    else
 1285                    {
 01286                        terms.Add("ISO");
 1287                    }
 1288                }
 1289            }
 1290
 41291            return string.Join('/', terms);
 1292        }
 1293
 1294        public Task RefreshMetadata(CancellationToken cancellationToken)
 1295        {
 491296            return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
 1297        }
 1298
 1299        /// <summary>
 1300        /// The base implementation to refresh metadata.
 1301        /// </summary>
 1302        /// <param name="options">The options.</param>
 1303        /// <param name="cancellationToken">The cancellation token.</param>
 1304        /// <returns>true if a provider reports we changed.</returns>
 1305        public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellation
 1306        {
 1307            var requiresSave = false;
 1308
 1309            if (SupportsOwnedItems)
 1310            {
 1311                try
 1312                {
 1313                    if (IsFileProtocol)
 1314                    {
 1315                        requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService
 1316                    }
 1317
 1318                    await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties i
 1319                }
 1320                catch (Exception ex)
 1321                {
 1322                    Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
 1323                }
 1324            }
 1325
 1326            var refreshOptions = requiresSave
 1327                ? new MetadataRefreshOptions(options)
 1328                {
 1329                    ForceSave = true
 1330                }
 1331                : options;
 1332
 1333            return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false
 1334        }
 1335
 1336        protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
 1337        {
 01338            if (!IsVisible(user))
 1339            {
 01340                return false;
 1341            }
 1342
 01343            if (GetParents().Any(i => !i.IsVisible(user, true)))
 1344            {
 01345                return false;
 1346            }
 1347
 01348            if (checkFolders)
 1349            {
 01350                var topParent = GetParents().LastOrDefault() ?? this;
 1351
 01352                if (string.IsNullOrEmpty(topParent.Path))
 1353                {
 01354                    return true;
 1355                }
 1356
 01357                var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
 1358
 01359                if (itemCollectionFolders.Count > 0)
 1360                {
 01361                    var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i
 01362                    if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
 1363                    {
 01364                        return false;
 1365                    }
 1366                }
 1367            }
 1368
 01369            return true;
 1370        }
 1371
 1372        public void SetParent(Folder parent)
 1373        {
 91374            ParentId = parent is null ? Guid.Empty : parent.Id;
 91375        }
 1376
 1377        /// <summary>
 1378        /// Refreshes owned items such as trailers, theme videos, special features, etc.
 1379        /// Returns true or false indicating if changes were found.
 1380        /// </summary>
 1381        /// <param name="options">The metadata refresh options.</param>
 1382        /// <param name="fileSystemChildren">The list of filesystem children.</param>
 1383        /// <param name="cancellationToken">The cancellation token.</param>
 1384        /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
 1385        protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemM
 1386        {
 1387            if (!IsFileProtocol || !SupportsOwnedItems || IsInMixedFolder || this is ICollectionFolder or UserRootFolder
 1388            {
 1389                return false;
 1390            }
 1391
 1392            return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
 1393        }
 1394
 1395        protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
 1396        {
 411397            return directoryService.GetFileSystemEntries(ContainingFolderPath);
 1398        }
 1399
 1400        private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMe
 1401        {
 1402            var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
 1403            var newExtraIds = Array.ConvertAll(extras, x => x.Id);
 1404            var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
 1405
 1406            if (!extrasChanged && !options.ReplaceAllMetadata && options.MetadataRefreshMode != MetadataRefreshMode.Full
 1407            {
 1408                return false;
 1409            }
 1410
 1411            var ownerId = item.Id;
 1412
 1413            var tasks = extras.Select(i =>
 1414            {
 1415                var subOptions = new MetadataRefreshOptions(options);
 1416                if (!i.OwnerId.Equals(ownerId) || !i.ParentId.IsEmpty())
 1417                {
 1418                    i.OwnerId = ownerId;
 1419                    i.ParentId = Guid.Empty;
 1420                    subOptions.ForceSave = true;
 1421                }
 1422
 1423                return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
 1424            });
 1425
 1426            // Cleanup removed extras
 1427            var removedExtraIds = item.ExtraIds.Where(e => !newExtraIds.Contains(e)).ToArray();
 1428            if (removedExtraIds.Length > 0)
 1429            {
 1430                var removedExtras = LibraryManager.GetItemList(new InternalItemsQuery()
 1431                {
 1432                    ItemIds = removedExtraIds
 1433                });
 1434                foreach (var removedExtra in removedExtras)
 1435                {
 1436                    LibraryManager.DeleteItem(removedExtra, new DeleteOptions()
 1437                    {
 1438                        DeleteFileLocation = false
 1439                    });
 1440                }
 1441            }
 1442
 1443            await Task.WhenAll(tasks).ConfigureAwait(false);
 1444
 1445            item.ExtraIds = newExtraIds;
 1446
 1447            return true;
 1448        }
 1449
 1450        public string GetPresentationUniqueKey()
 1451        {
 01452            return PresentationUniqueKey ?? CreatePresentationUniqueKey();
 1453        }
 1454
 1455        public virtual bool RequiresRefresh()
 1456        {
 561457            if (string.IsNullOrEmpty(Path) || DateModified == DateTime.MinValue)
 1458            {
 561459                return false;
 1460            }
 1461
 01462            var info = FileSystem.GetFileSystemInfo(Path);
 1463
 01464            return info.Exists && this.HasChanged(info.LastWriteTimeUtc);
 1465        }
 1466
 1467        public virtual List<string> GetUserDataKeys()
 1468        {
 1491469            var list = new List<string>();
 1470
 1491471            if (SourceType == SourceType.Channel)
 1472            {
 01473                if (!string.IsNullOrEmpty(ExternalId))
 1474                {
 01475                    list.Add(ExternalId);
 1476                }
 1477            }
 1478
 1491479            list.Add(Id.ToString());
 1491480            return list;
 1481        }
 1482
 1483        internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
 1484        {
 51485            var updateType = ItemUpdateType.None;
 1486
 51487            if (IsInMixedFolder != newItem.IsInMixedFolder)
 1488            {
 01489                IsInMixedFolder = newItem.IsInMixedFolder;
 01490                updateType |= ItemUpdateType.MetadataImport;
 1491            }
 1492
 51493            return updateType;
 1494        }
 1495
 1496        public void AfterMetadataRefresh()
 1497        {
 541498            _sortName = null;
 541499        }
 1500
 1501        /// <summary>
 1502        /// Gets the preferred metadata language.
 1503        /// </summary>
 1504        /// <returns>System.String.</returns>
 1505        public string GetPreferredMetadataLanguage()
 1506        {
 331507            string lang = PreferredMetadataLanguage;
 1508
 331509            if (string.IsNullOrEmpty(lang))
 1510            {
 331511                lang = GetParents()
 331512                    .Select(i => i.PreferredMetadataLanguage)
 331513                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1514            }
 1515
 331516            if (string.IsNullOrEmpty(lang))
 1517            {
 331518                lang = LibraryManager.GetCollectionFolders(this)
 331519                    .Select(i => i.PreferredMetadataLanguage)
 331520                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1521            }
 1522
 331523            if (string.IsNullOrEmpty(lang))
 1524            {
 331525                lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
 1526            }
 1527
 331528            if (string.IsNullOrEmpty(lang))
 1529            {
 331530                lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
 1531            }
 1532
 331533            return lang;
 1534        }
 1535
 1536        /// <summary>
 1537        /// Gets the preferred metadata language.
 1538        /// </summary>
 1539        /// <returns>System.String.</returns>
 1540        public string GetPreferredMetadataCountryCode()
 1541        {
 331542            string lang = PreferredMetadataCountryCode;
 1543
 331544            if (string.IsNullOrEmpty(lang))
 1545            {
 331546                lang = GetParents()
 331547                    .Select(i => i.PreferredMetadataCountryCode)
 331548                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1549            }
 1550
 331551            if (string.IsNullOrEmpty(lang))
 1552            {
 331553                lang = LibraryManager.GetCollectionFolders(this)
 331554                    .Select(i => i.PreferredMetadataCountryCode)
 331555                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1556            }
 1557
 331558            if (string.IsNullOrEmpty(lang))
 1559            {
 331560                lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
 1561            }
 1562
 331563            if (string.IsNullOrEmpty(lang))
 1564            {
 331565                lang = ConfigurationManager.Configuration.MetadataCountryCode;
 1566            }
 1567
 331568            return lang;
 1569        }
 1570
 1571        public virtual bool IsSaveLocalMetadataEnabled()
 1572        {
 861573            if (SourceType == SourceType.Channel)
 1574            {
 01575                return false;
 1576            }
 1577
 861578            var libraryOptions = LibraryManager.GetLibraryOptions(this);
 1579
 861580            return libraryOptions.SaveLocalMetadata;
 1581        }
 1582
 1583        /// <summary>
 1584        /// Determines if a given user has access to this item.
 1585        /// </summary>
 1586        /// <param name="user">The user.</param>
 1587        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 1588        /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
 1589        /// <exception cref="ArgumentNullException">If user is null.</exception>
 1590        public bool IsParentalAllowed(User user, bool skipAllowedTagsCheck)
 1591        {
 131592            ArgumentNullException.ThrowIfNull(user);
 1593
 131594            if (!IsVisibleViaTags(user, skipAllowedTagsCheck))
 1595            {
 01596                return false;
 1597            }
 1598
 131599            var maxAllowedRating = user.MaxParentalRatingScore;
 131600            var maxAllowedSubRating = user.MaxParentalRatingSubScore;
 131601            var rating = CustomRatingForComparison;
 1602
 131603            if (string.IsNullOrEmpty(rating))
 1604            {
 131605                rating = OfficialRatingForComparison;
 1606            }
 1607
 131608            if (string.IsNullOrEmpty(rating))
 1609            {
 131610                return !GetBlockUnratedValue(user);
 1611            }
 1612
 01613            var ratingScore = LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1614
 1615            // Could not determine rating level
 01616            if (ratingScore is null)
 1617            {
 01618                var isAllowed = !GetBlockUnratedValue(user);
 1619
 01620                if (!isAllowed)
 1621                {
 01622                    Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
 1623                }
 1624
 01625                return isAllowed;
 1626            }
 1627
 01628            if (!maxAllowedRating.HasValue)
 1629            {
 01630                return true;
 1631            }
 1632
 01633            if (ratingScore.Score != maxAllowedRating.Value)
 1634            {
 01635                return ratingScore.Score < maxAllowedRating.Value;
 1636            }
 1637
 01638            return !maxAllowedSubRating.HasValue || (ratingScore.SubScore ?? 0) <= maxAllowedSubRating.Value;
 1639        }
 1640
 1641        public ParentalRatingScore GetParentalRatingScore()
 1642        {
 1111643            var rating = CustomRatingForComparison;
 1644
 1111645            if (string.IsNullOrEmpty(rating))
 1646            {
 1111647                rating = OfficialRatingForComparison;
 1648            }
 1649
 1111650            if (string.IsNullOrEmpty(rating))
 1651            {
 1111652                return null;
 1653            }
 1654
 01655            return LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1656        }
 1657
 1658        public List<string> GetInheritedTags()
 1659        {
 1221660            var list = new List<string>();
 1221661            list.AddRange(Tags);
 1662
 3241663            foreach (var parent in GetParents())
 1664            {
 401665                list.AddRange(parent.Tags);
 1666            }
 1667
 2441668            foreach (var folder in LibraryManager.GetCollectionFolders(this))
 1669            {
 01670                list.AddRange(folder.Tags);
 1671            }
 1672
 1221673            return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
 1674        }
 1675
 1676        private bool IsVisibleViaTags(User user, bool skipAllowedTagsCheck)
 1677        {
 131678            var allTags = GetInheritedTags();
 131679            if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => allTags.Contains(i, StringComparison.OrdinalIgno
 1680            {
 01681                return false;
 1682            }
 1683
 131684            var parent = GetParents().FirstOrDefault() ?? this;
 131685            if (parent is UserRootFolder or AggregateFolder or UserView)
 1686            {
 131687                return true;
 1688            }
 1689
 01690            var allowedTagsPreference = user.GetPreference(PreferenceKind.AllowedTags);
 01691            if (!skipAllowedTagsCheck && allowedTagsPreference.Length != 0 && !allowedTagsPreference.Any(i => allTags.Co
 1692            {
 01693                return false;
 1694            }
 1695
 01696            return true;
 1697        }
 1698
 1699        public virtual UnratedItem GetBlockUnratedType()
 1700        {
 1091701            if (SourceType == SourceType.Channel)
 1702            {
 01703                return UnratedItem.ChannelContent;
 1704            }
 1705
 1091706            return UnratedItem.Other;
 1707        }
 1708
 1709        /// <summary>
 1710        /// Gets a bool indicating if access to the unrated item is blocked or not.
 1711        /// </summary>
 1712        /// <param name="user">The configuration.</param>
 1713        /// <returns><c>true</c> if blocked, <c>false</c> otherwise.</returns>
 1714        protected virtual bool GetBlockUnratedValue(User user)
 1715        {
 1716            // Don't block plain folders that are unrated. Let the media underneath get blocked
 1717            // Special folders like series and albums will override this method.
 131718            if (IsFolder || this is IItemByName)
 1719            {
 131720                return false;
 1721            }
 1722
 01723            return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType(
 1724        }
 1725
 1726        /// <summary>
 1727        /// Determines if this folder should be visible to a given user.
 1728        /// Default is just parental allowed. Can be overridden for more functionality.
 1729        /// </summary>
 1730        /// <param name="user">The user.</param>
 1731        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 1732        /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
 1733        /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
 1734        public virtual bool IsVisible(User user, bool skipAllowedTagsCheck = false)
 1735        {
 131736            ArgumentNullException.ThrowIfNull(user);
 1737
 131738            return IsParentalAllowed(user, skipAllowedTagsCheck);
 1739        }
 1740
 1741        public virtual bool IsVisibleStandalone(User user)
 1742        {
 01743            if (SourceType == SourceType.Channel)
 1744            {
 01745                return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
 1746            }
 1747
 01748            return IsVisibleStandaloneInternal(user, true);
 1749        }
 1750
 1751        public virtual string GetClientTypeName()
 1752        {
 1101753            if (IsFolder && SourceType == SourceType.Channel && this is not Channel && this is not Season && this is not
 1754            {
 01755                return "ChannelFolderItem";
 1756            }
 1757
 1101758            return GetType().Name;
 1759        }
 1760
 1761        public BaseItemKind GetBaseItemKind()
 1762        {
 2381763            return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
 1764        }
 1765
 1766        /// <summary>
 1767        /// Gets the linked child.
 1768        /// </summary>
 1769        /// <param name="info">The info.</param>
 1770        /// <returns>BaseItem.</returns>
 1771        protected BaseItem GetLinkedChild(LinkedChild info)
 1772        {
 1773            // First get using the cached Id
 01774            if (info.ItemId.HasValue)
 1775            {
 01776                if (info.ItemId.Value.IsEmpty())
 1777                {
 01778                    return null;
 1779                }
 1780
 01781                var itemById = LibraryManager.GetItemById(info.ItemId.Value);
 1782
 01783                if (itemById is not null)
 1784                {
 01785                    return itemById;
 1786                }
 1787            }
 1788
 01789            var item = FindLinkedChild(info);
 1790
 1791            // If still null, log
 01792            if (item is null)
 1793            {
 1794                // Don't keep searching over and over
 01795                info.ItemId = Guid.Empty;
 1796            }
 1797            else
 1798            {
 1799                // Cache the id for next time
 01800                info.ItemId = item.Id;
 1801            }
 1802
 01803            return item;
 1804        }
 1805
 1806        private BaseItem FindLinkedChild(LinkedChild info)
 1807        {
 01808            var path = info.Path;
 1809
 01810            if (!string.IsNullOrEmpty(path))
 1811            {
 01812                path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
 1813
 01814                var itemByPath = LibraryManager.FindByPath(path, null);
 1815
 01816                if (itemByPath is null)
 1817                {
 01818                    Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
 1819                }
 1820
 01821                return itemByPath;
 1822            }
 1823
 01824            if (!string.IsNullOrEmpty(info.LibraryItemId))
 1825            {
 01826                var item = LibraryManager.GetItemById(info.LibraryItemId);
 1827
 01828                if (item is null)
 1829                {
 01830                    Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
 1831                }
 1832
 01833                return item;
 1834            }
 1835
 01836            return null;
 1837        }
 1838
 1839        /// <summary>
 1840        /// Adds a studio to the item.
 1841        /// </summary>
 1842        /// <param name="name">The name.</param>
 1843        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 1844        public void AddStudio(string name)
 1845        {
 41846            ArgumentException.ThrowIfNullOrEmpty(name);
 41847            var current = Studios;
 1848
 41849            if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
 1850            {
 41851                int curLen = current.Length;
 41852                if (curLen == 0)
 1853                {
 41854                    Studios = [name];
 1855                }
 1856                else
 1857                {
 01858                    Studios = [.. current, name];
 1859                }
 1860            }
 01861        }
 1862
 1863        public void SetStudios(IEnumerable<string> names)
 1864        {
 01865            Studios = names.Trimmed().Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 01866        }
 1867
 1868        /// <summary>
 1869        /// Adds a genre to the item.
 1870        /// </summary>
 1871        /// <param name="name">The name.</param>
 1872        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 1873        public void AddGenre(string name)
 1874        {
 131875            ArgumentException.ThrowIfNullOrEmpty(name);
 1876
 131877            var genres = Genres;
 131878            if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
 1879            {
 131880                Genres = [.. genres, name];
 1881            }
 131882        }
 1883
 1884        /// <summary>
 1885        /// Marks the played.
 1886        /// </summary>
 1887        /// <param name="user">The user.</param>
 1888        /// <param name="datePlayed">The date played.</param>
 1889        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 1890        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 1891        public virtual void MarkPlayed(
 1892            User user,
 1893            DateTime? datePlayed,
 1894            bool resetPosition)
 1895        {
 01896            ArgumentNullException.ThrowIfNull(user);
 1897
 01898            var data = UserDataManager.GetUserData(user, this) ?? new UserItemData()
 01899            {
 01900                Key = GetUserDataKeys().First(),
 01901            };
 1902
 01903            if (datePlayed.HasValue)
 1904            {
 1905                // Increment
 01906                data.PlayCount++;
 1907            }
 1908
 1909            // Ensure it's at least one
 01910            data.PlayCount = Math.Max(data.PlayCount, 1);
 1911
 01912            if (resetPosition)
 1913            {
 01914                data.PlaybackPositionTicks = 0;
 1915            }
 1916
 01917            data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
 01918            data.Played = true;
 1919
 01920            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 01921        }
 1922
 1923        /// <summary>
 1924        /// Marks the unplayed.
 1925        /// </summary>
 1926        /// <param name="user">The user.</param>
 1927        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 1928        public virtual void MarkUnplayed(User user)
 1929        {
 01930            ArgumentNullException.ThrowIfNull(user);
 1931
 01932            var data = UserDataManager.GetUserData(user, this);
 1933
 1934            // I think it is okay to do this here.
 1935            // if this is only called when a user is manually forcing something to un-played
 1936            // then it probably is what we want to do...
 01937            data.PlayCount = 0;
 01938            data.PlaybackPositionTicks = 0;
 01939            data.LastPlayedDate = null;
 01940            data.Played = false;
 1941
 01942            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 01943        }
 1944
 1945        /// <summary>
 1946        /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
 1947        /// </summary>
 1948        public virtual void ChangedExternally()
 1949        {
 01950            ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriori
 01951        }
 1952
 1953        /// <summary>
 1954        /// Gets an image.
 1955        /// </summary>
 1956        /// <param name="type">The type.</param>
 1957        /// <param name="imageIndex">Index of the image.</param>
 1958        /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
 1959        /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
 1960        public bool HasImage(ImageType type, int imageIndex)
 1961        {
 1431962            return GetImageInfo(type, imageIndex) is not null;
 1963        }
 1964
 1965        public void SetImage(ItemImageInfo image, int index)
 1966        {
 131967            if (image.Type == ImageType.Chapter)
 1968            {
 01969                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 1970            }
 1971
 131972            var existingImage = GetImageInfo(image.Type, index);
 1973
 131974            if (existingImage is null)
 1975            {
 111976                AddImage(image);
 1977            }
 1978            else
 1979            {
 21980                existingImage.Path = image.Path;
 21981                existingImage.DateModified = image.DateModified;
 21982                existingImage.Width = image.Width;
 21983                existingImage.Height = image.Height;
 21984                existingImage.BlurHash = image.BlurHash;
 1985            }
 21986        }
 1987
 1988        public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
 1989        {
 461990            if (type == ImageType.Chapter)
 1991            {
 01992                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 1993            }
 1994
 461995            var image = GetImageInfo(type, index);
 1996
 461997            if (image is null)
 1998            {
 451999                AddImage(GetImageInfo(file, type));
 2000            }
 2001            else
 2002            {
 12003                var imageInfo = GetImageInfo(file, type);
 2004
 12005                image.Path = file.FullName;
 12006                image.DateModified = imageInfo.DateModified;
 2007
 2008                // reset these values
 12009                image.Width = 0;
 12010                image.Height = 0;
 2011            }
 12012        }
 2013
 2014        /// <summary>
 2015        /// Deletes the image.
 2016        /// </summary>
 2017        /// <param name="type">The type.</param>
 2018        /// <param name="index">The index.</param>
 2019        /// <returns>A task.</returns>
 2020        public async Task DeleteImageAsync(ImageType type, int index)
 2021        {
 2022            var info = GetImageInfo(type, index);
 2023
 2024            if (info is null)
 2025            {
 2026                // Nothing to do
 2027                return;
 2028            }
 2029
 2030            // Remove from file system
 2031            var path = info.Path;
 2032            if (info.IsLocalFile && !string.IsNullOrWhiteSpace(path))
 2033            {
 2034                FileSystem.DeleteFile(path);
 2035            }
 2036
 2037            // Remove from item
 2038            RemoveImage(info);
 2039
 2040            await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
 2041        }
 2042
 2043        public void RemoveImage(ItemImageInfo image)
 2044        {
 02045            RemoveImages([image]);
 02046        }
 2047
 2048        public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
 2049        {
 92050            ImageInfos = ImageInfos.Except(deletedImages).ToArray();
 92051        }
 2052
 2053        public void AddImage(ItemImageInfo image)
 2054        {
 562055            ImageInfos = [.. ImageInfos, image];
 562056        }
 2057
 2058        public virtual async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationTok
 2059         => await LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken).ConfigureAwait(fals
 2060
 2061        public async Task ReattachUserDataAsync(CancellationToken cancellationToken) =>
 2062            await LibraryManager.ReattachUserDataAsync(this, cancellationToken).ConfigureAwait(false);
 2063
 2064        /// <summary>
 2065        /// Validates that images within the item are still on the filesystem.
 2066        /// </summary>
 2067        /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
 2068        public bool ValidateImages()
 2069        {
 702070            List<ItemImageInfo> deletedImages = null;
 1702071            foreach (var imageInfo in ImageInfos)
 2072            {
 152073                if (!imageInfo.IsLocalFile)
 2074                {
 2075                    continue;
 2076                }
 2077
 152078                if (File.Exists(imageInfo.Path))
 2079                {
 2080                    continue;
 2081                }
 2082
 32083                (deletedImages ??= []).Add(imageInfo);
 2084            }
 2085
 702086            var anyImagesRemoved = deletedImages?.Count > 0;
 702087            if (anyImagesRemoved)
 2088            {
 22089                RemoveImages(deletedImages);
 2090            }
 2091
 702092            return anyImagesRemoved;
 2093        }
 2094
 2095        /// <summary>
 2096        /// Gets the image path.
 2097        /// </summary>
 2098        /// <param name="imageType">Type of the image.</param>
 2099        /// <param name="imageIndex">Index of the image.</param>
 2100        /// <returns>System.String.</returns>
 2101        /// <exception cref="ArgumentNullException">Item is null.</exception>
 2102        public string GetImagePath(ImageType imageType, int imageIndex)
 22103            => GetImageInfo(imageType, imageIndex)?.Path;
 2104
 2105        /// <summary>
 2106        /// Gets the image information.
 2107        /// </summary>
 2108        /// <param name="imageType">Type of the image.</param>
 2109        /// <param name="imageIndex">Index of the image.</param>
 2110        /// <returns>ItemImageInfo.</returns>
 2111        public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
 2112        {
 2962113            if (imageType == ImageType.Chapter)
 2114            {
 02115                var chapter = ChapterManager.GetChapter(Id, imageIndex);
 2116
 02117                if (chapter is null)
 2118                {
 02119                    return null;
 2120                }
 2121
 02122                var path = chapter.ImagePath;
 2123
 02124                if (string.IsNullOrEmpty(path))
 2125                {
 02126                    return null;
 2127                }
 2128
 02129                return new ItemImageInfo
 02130                {
 02131                    Path = path,
 02132                    DateModified = chapter.ImageDateModified,
 02133                    Type = imageType
 02134                };
 2135            }
 2136
 2962137            return GetImages(imageType)
 2962138                .ElementAtOrDefault(imageIndex);
 2139        }
 2140
 2141        /// <summary>
 2142        /// Computes image index for given image or raises if no matching image found.
 2143        /// </summary>
 2144        /// <param name="image">Image to compute index for.</param>
 2145        /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
 2146        /// </exception>
 2147        /// <returns>Image index.</returns>
 2148        public int GetImageIndex(ItemImageInfo image)
 2149        {
 02150            ArgumentNullException.ThrowIfNull(image);
 2151
 02152            if (image.Type == ImageType.Chapter)
 2153            {
 02154                var chapters = ChapterManager.GetChapters(Id);
 02155                for (var i = 0; i < chapters.Count; i++)
 2156                {
 02157                    if (chapters[i].ImagePath == image.Path)
 2158                    {
 02159                        return i;
 2160                    }
 2161                }
 2162
 02163                throw new ArgumentException("No chapter index found for image path", image.Path);
 2164            }
 2165
 02166            var images = GetImages(image.Type).ToArray();
 02167            for (var i = 0; i < images.Length; i++)
 2168            {
 02169                if (images[i].Path == image.Path)
 2170                {
 02171                    return i;
 2172                }
 2173            }
 2174
 02175            throw new ArgumentException("No image index found for image path", image.Path);
 2176        }
 2177
 2178        public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
 2179        {
 2180            if (imageType == ImageType.Chapter)
 2181            {
 2182                throw new ArgumentException("No image info for chapter images");
 2183            }
 2184
 2185            // Yield return is more performant than LINQ Where on an Array
 2186            for (var i = 0; i < ImageInfos.Length; i++)
 2187            {
 2188                var imageInfo = ImageInfos[i];
 2189                if (imageInfo.Type == imageType)
 2190                {
 2191                    yield return imageInfo;
 2192                }
 2193            }
 2194        }
 2195
 2196        /// <summary>
 2197        /// Adds the images, updating metadata if they already are part of this item.
 2198        /// </summary>
 2199        /// <param name="imageType">Type of the image.</param>
 2200        /// <param name="images">The images.</param>
 2201        /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
 2202        /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
 2203        public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
 2204        {
 42205            if (imageType == ImageType.Chapter)
 2206            {
 02207                throw new ArgumentException("Cannot call AddImages with chapter images");
 2208            }
 2209
 42210            var existingImages = GetImages(imageType)
 42211                .ToList();
 2212
 42213            var newImageList = new List<FileSystemMetadata>();
 42214            var imageUpdated = false;
 2215
 242216            foreach (var newImage in images)
 2217            {
 82218                if (newImage is null)
 2219                {
 02220                    throw new ArgumentException("null image found in list");
 2221                }
 2222
 82223                var existing = existingImages
 82224                    .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
 2225
 82226                if (existing is null)
 2227                {
 42228                    newImageList.Add(newImage);
 2229                }
 2230                else
 2231                {
 42232                    if (existing.IsLocalFile)
 2233                    {
 42234                        var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
 2235
 2236                        // If date changed then we need to reset saved image dimensions
 42237                        if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
 2238                        {
 22239                            existing.Width = 0;
 22240                            existing.Height = 0;
 22241                            imageUpdated = true;
 2242                        }
 2243
 42244                        existing.DateModified = newDateModified;
 2245                    }
 2246                }
 2247            }
 2248
 42249            if (newImageList.Count > 0)
 2250            {
 22251                ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
 2252            }
 2253
 42254            return imageUpdated || newImageList.Count > 0;
 2255        }
 2256
 2257        private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
 2258        {
 502259            return new ItemImageInfo
 502260            {
 502261                Path = file.FullName,
 502262                Type = type,
 502263                DateModified = FileSystem.GetLastWriteTimeUtc(file)
 502264            };
 2265        }
 2266
 2267        /// <summary>
 2268        /// Gets the file system path to delete when the item is to be deleted.
 2269        /// </summary>
 2270        /// <returns>The metadata for the deleted paths.</returns>
 2271        public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
 2272        {
 02273            return new[]
 02274            {
 02275                FileSystem.GetFileSystemInfo(Path)
 02276            }.Concat(GetLocalMetadataFilesToDelete());
 2277        }
 2278
 2279        protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
 2280        {
 02281            if (IsFolder || !IsInMixedFolder)
 2282            {
 02283                return [];
 2284            }
 2285
 02286            var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
 2287
 02288            return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
 02289                .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison
 02290                .ToList();
 2291        }
 2292
 2293        public bool AllowsMultipleImages(ImageType type)
 2294        {
 182295            return type == ImageType.Backdrop || type == ImageType.Chapter;
 2296        }
 2297
 2298        public Task SwapImagesAsync(ImageType type, int index1, int index2)
 2299        {
 02300            if (!AllowsMultipleImages(type))
 2301            {
 02302                throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots
 2303            }
 2304
 02305            var info1 = GetImageInfo(type, index1);
 02306            var info2 = GetImageInfo(type, index2);
 2307
 02308            if (info1 is null || info2 is null)
 2309            {
 2310                // Nothing to do
 02311                return Task.CompletedTask;
 2312            }
 2313
 02314            if (!info1.IsLocalFile || !info2.IsLocalFile)
 2315            {
 2316                // TODO: Not supported  yet
 02317                return Task.CompletedTask;
 2318            }
 2319
 02320            var path1 = info1.Path;
 02321            var path2 = info2.Path;
 2322
 02323            FileSystem.SwapFiles(path1, path2);
 2324
 2325            // Refresh these values
 02326            info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
 02327            info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
 2328
 02329            info1.Width = 0;
 02330            info1.Height = 0;
 02331            info2.Width = 0;
 02332            info2.Height = 0;
 2333
 02334            return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
 2335        }
 2336
 2337        public virtual bool IsPlayed(User user, UserItemData userItemData)
 2338        {
 02339            userItemData ??= UserDataManager.GetUserData(user, this);
 2340
 02341            return userItemData is not null && userItemData.Played;
 2342        }
 2343
 2344        public bool IsFavoriteOrLiked(User user, UserItemData userItemData)
 2345        {
 02346            userItemData ??= UserDataManager.GetUserData(user, this);
 2347
 02348            return userItemData is not null && (userItemData.IsFavorite || (userItemData.Likes ?? false));
 2349        }
 2350
 2351        public virtual bool IsUnplayed(User user, UserItemData userItemData)
 2352        {
 02353            ArgumentNullException.ThrowIfNull(user);
 2354
 02355            userItemData ??= UserDataManager.GetUserData(user, this);
 2356
 02357            return userItemData is null || !userItemData.Played;
 2358        }
 2359
 2360        ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
 2361        {
 332362            return GetItemLookupInfo<ItemLookupInfo>();
 2363        }
 2364
 2365        protected T GetItemLookupInfo<T>()
 2366            where T : ItemLookupInfo, new()
 2367        {
 332368            return new T
 332369            {
 332370                Path = Path,
 332371                MetadataCountryCode = GetPreferredMetadataCountryCode(),
 332372                MetadataLanguage = GetPreferredMetadataLanguage(),
 332373                Name = GetNameForMetadataLookup(),
 332374                OriginalTitle = OriginalTitle,
 332375                ProviderIds = ProviderIds,
 332376                IndexNumber = IndexNumber,
 332377                ParentIndexNumber = ParentIndexNumber,
 332378                Year = ProductionYear,
 332379                PremiereDate = PremiereDate
 332380            };
 2381        }
 2382
 2383        protected virtual string GetNameForMetadataLookup()
 2384        {
 332385            return Name;
 2386        }
 2387
 2388        /// <summary>
 2389        /// This is called before any metadata refresh and returns true if changes were made.
 2390        /// </summary>
 2391        /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
 2392        /// <returns>true if the item has change, else false.</returns>
 2393        public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
 2394        {
 332395            _sortName = null;
 2396
 332397            var hasChanges = false;
 2398
 332399            if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
 2400            {
 02401                Name = System.IO.Path.GetFileNameWithoutExtension(Path);
 02402                hasChanges = true;
 2403            }
 2404
 332405            return hasChanges;
 2406        }
 2407
 2408        protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
 2409        {
 02410            if (protocol == MediaProtocol.File)
 2411            {
 02412                return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
 2413            }
 2414
 02415            return path;
 2416        }
 2417
 2418        public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User 
 2419        {
 02420            if (RunTimeTicks.HasValue)
 2421            {
 02422                double pct = RunTimeTicks.Value;
 2423
 02424                if (pct > 0)
 2425                {
 02426                    pct = userData.PlaybackPositionTicks / pct;
 2427
 02428                    if (pct > 0)
 2429                    {
 02430                        dto.PlayedPercentage = 100 * pct;
 2431                    }
 2432                }
 2433            }
 02434        }
 2435
 2436        protected async Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOpti
 2437        {
 2438            var newOptions = new MetadataRefreshOptions(options)
 2439            {
 2440                SearchResult = null
 2441            };
 2442
 2443            var item = this;
 2444
 2445            if (copyTitleMetadata)
 2446            {
 2447                // Take some data from the main item, for querying purposes
 2448                if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
 2449                {
 2450                    newOptions.ForceSave = true;
 2451                    ownedItem.Genres = item.Genres;
 2452                }
 2453
 2454                if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
 2455                {
 2456                    newOptions.ForceSave = true;
 2457                    ownedItem.Studios = item.Studios;
 2458                }
 2459
 2460                if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
 2461                {
 2462                    newOptions.ForceSave = true;
 2463                    ownedItem.ProductionLocations = item.ProductionLocations;
 2464                }
 2465
 2466                if (item.CommunityRating != ownedItem.CommunityRating)
 2467                {
 2468                    ownedItem.CommunityRating = item.CommunityRating;
 2469                    newOptions.ForceSave = true;
 2470                }
 2471
 2472                if (item.CriticRating != ownedItem.CriticRating)
 2473                {
 2474                    ownedItem.CriticRating = item.CriticRating;
 2475                    newOptions.ForceSave = true;
 2476                }
 2477
 2478                if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
 2479                {
 2480                    ownedItem.Overview = item.Overview;
 2481                    newOptions.ForceSave = true;
 2482                }
 2483
 2484                if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
 2485                {
 2486                    ownedItem.OfficialRating = item.OfficialRating;
 2487                    newOptions.ForceSave = true;
 2488                }
 2489
 2490                if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
 2491                {
 2492                    ownedItem.CustomRating = item.CustomRating;
 2493                    newOptions.ForceSave = true;
 2494                }
 2495            }
 2496
 2497            await ownedItem.RefreshMetadata(newOptions, cancellationToken).ConfigureAwait(false);
 2498        }
 2499
 2500        protected async Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string
 2501        {
 2502            var newOptions = new MetadataRefreshOptions(options)
 2503            {
 2504                SearchResult = null
 2505            };
 2506
 2507            var id = LibraryManager.GetNewItemId(path, typeof(Video));
 2508
 2509            // Try to retrieve it from the db. If we don't find it, use the resolved version
 2510            if (LibraryManager.GetItemById(id) is not Video video)
 2511            {
 2512                video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
 2513
 2514                newOptions.ForceSave = true;
 2515            }
 2516
 2517            if (video is null)
 2518            {
 2519                return;
 2520            }
 2521
 2522            if (video.OwnerId.IsEmpty())
 2523            {
 2524                video.OwnerId = Id;
 2525            }
 2526
 2527            await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(fa
 2528        }
 2529
 2530        public string GetEtag(User user)
 2531        {
 62532            var list = GetEtagValues(user);
 2533
 62534            return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
 2535        }
 2536
 2537        protected virtual List<string> GetEtagValues(User user)
 2538        {
 62539            return
 62540            [
 62541                DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
 62542            ];
 2543        }
 2544
 2545        public virtual IEnumerable<Guid> GetAncestorIds()
 2546        {
 1092547            return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
 2548        }
 2549
 2550        public BaseItem GetTopParent()
 2551        {
 1092552            if (IsTopParent)
 2553            {
 212554                return this;
 2555            }
 2556
 882557            return GetParents().FirstOrDefault(parent => parent.IsTopParent);
 2558        }
 2559
 2560        public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
 2561        {
 432562            return [Id];
 2563        }
 2564
 2565        public virtual double? GetRefreshProgress()
 2566        {
 02567            return null;
 2568        }
 2569
 2570        public virtual ItemUpdateType OnMetadataChanged()
 2571        {
 1112572            var updateType = ItemUpdateType.None;
 2573
 1112574            var item = this;
 2575
 1112576            var rating = item.GetParentalRatingScore();
 1112577            if (rating is not null)
 2578            {
 02579                if (rating.Score != item.InheritedParentalRatingValue)
 2580                {
 02581                    item.InheritedParentalRatingValue = rating.Score;
 02582                    updateType |= ItemUpdateType.MetadataImport;
 2583                }
 2584
 02585                if (rating.SubScore != item.InheritedParentalRatingSubValue)
 2586                {
 02587                    item.InheritedParentalRatingSubValue = rating.SubScore;
 02588                    updateType |= ItemUpdateType.MetadataImport;
 2589                }
 2590            }
 2591            else
 2592            {
 1112593                if (item.InheritedParentalRatingValue is not null)
 2594                {
 02595                    item.InheritedParentalRatingValue = null;
 02596                    item.InheritedParentalRatingSubValue = null;
 02597                    updateType |= ItemUpdateType.MetadataImport;
 2598                }
 2599            }
 2600
 1112601            return updateType;
 2602        }
 2603
 2604        /// <summary>
 2605        /// Updates the official rating based on content and returns true or false indicating if it changed.
 2606        /// </summary>
 2607        /// <param name="children">Media children.</param>
 2608        /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
 2609        public bool UpdateRatingToItems(IReadOnlyList<BaseItem> children)
 2610        {
 02611            var currentOfficialRating = OfficialRating;
 2612
 2613            // Gather all possible ratings
 02614            var ratings = children
 02615                .Select(i => i.OfficialRating)
 02616                .Where(i => !string.IsNullOrEmpty(i))
 02617                .Distinct(StringComparer.OrdinalIgnoreCase)
 02618                .Select(rating => (rating, LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode())
 02619                .OrderBy(i => i.Item2 is null ? 1001 : i.Item2.Score)
 02620                .ThenBy(i => i.Item2 is null ? 1001 : i.Item2.SubScore)
 02621                .Select(i => i.rating);
 2622
 02623            OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
 2624
 02625            return !string.Equals(
 02626                currentOfficialRating ?? string.Empty,
 02627                OfficialRating ?? string.Empty,
 02628                StringComparison.OrdinalIgnoreCase);
 2629        }
 2630
 2631        public IReadOnlyList<BaseItem> GetThemeSongs(User user = null)
 2632        {
 02633            return GetThemeSongs(user, Array.Empty<(ItemSortBy, SortOrder)>());
 2634        }
 2635
 2636        public IReadOnlyList<BaseItem> GetThemeSongs(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> or
 2637        {
 02638            return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong), user, 
 2639        }
 2640
 2641        public IReadOnlyList<BaseItem> GetThemeVideos(User user = null)
 2642        {
 02643            return GetThemeVideos(user, Array.Empty<(ItemSortBy, SortOrder)>());
 2644        }
 2645
 2646        public IReadOnlyList<BaseItem> GetThemeVideos(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> o
 2647        {
 02648            return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo), user,
 2649        }
 2650
 2651        /// <summary>
 2652        /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
 2653        /// </summary>
 2654        /// <returns>An enumerable containing the items.</returns>
 2655        public IEnumerable<BaseItem> GetExtras()
 2656        {
 62657            return ExtraIds
 62658                .Select(LibraryManager.GetItemById)
 62659                .Where(i => i is not null)
 62660                .OrderBy(i => i.SortName);
 2661        }
 2662
 2663        /// <summary>
 2664        /// Get all extras with specific types that are associated with this item.
 2665        /// </summary>
 2666        /// <param name="extraTypes">The types of extras to retrieve.</param>
 2667        /// <returns>An enumerable containing the extras.</returns>
 2668        public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
 2669        {
 02670            return ExtraIds
 02671                .Select(LibraryManager.GetItemById)
 02672                .Where(i => i is not null)
 02673                .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value))
 02674                .OrderBy(i => i.SortName);
 2675        }
 2676
 2677        public virtual long GetRunTimeTicksForPlayState()
 2678        {
 02679            return RunTimeTicks ?? 0;
 2680        }
 2681
 2682        /// <inheritdoc />
 2683        public override bool Equals(object obj)
 2684        {
 02685            return obj is BaseItem baseItem && this.Equals(baseItem);
 2686        }
 2687
 2688        /// <inheritdoc />
 52689        public bool Equals(BaseItem other) => other is not null && other.Id.Equals(Id);
 2690
 2691        /// <inheritdoc />
 602692        public override int GetHashCode() => HashCode.Combine(Id);
 2693    }
 2694}

Methods/Properties

.cctor()
.ctor()
get_SupportsAddingToPlaylist()
get_AlwaysScanInternalMetadataPath()
get_SupportsPlayedStatus()
get_SupportsPositionTicksResume()
get_SupportsRemoteImageDownloading()
get_Name()
set_Name(System.String)
get_IsUnaired()
get_IsThemeMedia()
get_DisplayPreferencesId()
get_SourceType()
get_ContainingFolderPath()
get_IsHidden()
get_LocationType()
get_PathProtocol()
get_IsFileProtocol()
get_HasPathProtocol()
get_SupportsLocalMetadata()
get_FileNameWithoutExtension()
get_EnableAlphaNumericSorting()
get_IsHD()
get_PrimaryImagePath()
get_MediaType()
get_PhysicalLocations()
get_EnableMediaSourceDisplay()
get_ForcedSortName()
set_ForcedSortName(System.String)
get_SortName()
set_SortName(System.String)
get_DisplayParentId()
get_DisplayParent()
get_HasLocalAlternateVersions()
get_OfficialRatingForComparison()
get_CustomRatingForComparison()
get_LatestItemsIndexContainer()
get_EnableRememberingTrackSelections()
get_IsTopParent()
get_SupportsAncestors()
get_SupportsOwnedItems()
get_SupportsPeople()
get_SupportsThemeMedia()
get_SupportsInheritedParentImages()
get_IsFolder()
get_IsDisplayedAsFolder()
GetCustomRatingForComparision(System.Collections.Generic.HashSet`1<System.Guid>)
GetDefaultPrimaryImageAspectRatio()
CreatePresentationUniqueKey()
CanDelete()
IsAuthorizedToDelete(Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.Folder>)
GetOwner()
CanDelete(Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.List`1<MediaBrowser.Controller.Entities.Folder>)
CanDelete(Jellyfin.Database.Implementations.Entities.User)
CanDownload()
IsAuthorizedToDownload(Jellyfin.Database.Implementations.Entities.User)
CanDownload(Jellyfin.Database.Implementations.Entities.User)
ToString()
GetInternalMetadataPath()
GetInternalMetadataPath(System.String)
CreateSortName()
ModifySortChunks(System.ReadOnlySpan`1<System.Char>)
GetParent()
FindParent()
GetPlayAccess(Jellyfin.Database.Implementations.Entities.User)
GetMediaStreams()
IsActiveRecording()
GetMediaSources(System.Boolean)
GetAllItemsForMediaSources()
GetVersionInfo(System.Boolean,MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Model.Dto.MediaSourceType)
GetMediaSourceName(MediaBrowser.Controller.Entities.BaseItem)
RefreshMetadata(System.Threading.CancellationToken)
IsVisibleStandaloneInternal(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
SetParent(MediaBrowser.Controller.Entities.Folder)
GetFileSystemChildren(MediaBrowser.Controller.Providers.IDirectoryService)
GetPresentationUniqueKey()
RequiresRefresh()
GetUserDataKeys()
UpdateFromResolvedItem(MediaBrowser.Controller.Entities.BaseItem)
AfterMetadataRefresh()
GetPreferredMetadataLanguage()
GetPreferredMetadataCountryCode()
IsSaveLocalMetadataEnabled()
IsParentalAllowed(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
GetParentalRatingScore()
GetInheritedTags()
IsVisibleViaTags(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
GetBlockUnratedType()
GetBlockUnratedValue(Jellyfin.Database.Implementations.Entities.User)
IsVisible(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
IsVisibleStandalone(Jellyfin.Database.Implementations.Entities.User)
GetClientTypeName()
GetBaseItemKind()
GetLinkedChild(MediaBrowser.Controller.Entities.LinkedChild)
FindLinkedChild(MediaBrowser.Controller.Entities.LinkedChild)
AddStudio(System.String)
SetStudios(System.Collections.Generic.IEnumerable`1<System.String>)
AddGenre(System.String)
MarkPlayed(Jellyfin.Database.Implementations.Entities.User,System.Nullable`1<System.DateTime>,System.Boolean)
MarkUnplayed(Jellyfin.Database.Implementations.Entities.User)
ChangedExternally()
HasImage(MediaBrowser.Model.Entities.ImageType,System.Int32)
SetImage(MediaBrowser.Controller.Entities.ItemImageInfo,System.Int32)
SetImagePath(MediaBrowser.Model.Entities.ImageType,System.Int32,MediaBrowser.Model.IO.FileSystemMetadata)
RemoveImage(MediaBrowser.Controller.Entities.ItemImageInfo)
RemoveImages(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.ItemImageInfo>)
AddImage(MediaBrowser.Controller.Entities.ItemImageInfo)
ValidateImages()
GetImagePath(MediaBrowser.Model.Entities.ImageType,System.Int32)
GetImageInfo(MediaBrowser.Model.Entities.ImageType,System.Int32)
GetImageIndex(MediaBrowser.Controller.Entities.ItemImageInfo)
AddImages(MediaBrowser.Model.Entities.ImageType,System.Collections.Generic.List`1<MediaBrowser.Model.IO.FileSystemMetadata>)
GetImageInfo(MediaBrowser.Model.IO.FileSystemMetadata,MediaBrowser.Model.Entities.ImageType)
GetDeletePaths()
GetLocalMetadataFilesToDelete()
AllowsMultipleImages(MediaBrowser.Model.Entities.ImageType)
SwapImagesAsync(MediaBrowser.Model.Entities.ImageType,System.Int32,System.Int32)
IsPlayed(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.UserItemData)
IsFavoriteOrLiked(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.UserItemData)
IsUnplayed(Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Entities.UserItemData)
MediaBrowser.Controller.Providers.IHasLookupInfo<MediaBrowser.Controller.Providers.ItemLookupInfo>.GetLookupInfo()
GetItemLookupInfo()
GetNameForMetadataLookup()
BeforeMetadataRefresh(System.Boolean)
GetMappedPath(MediaBrowser.Controller.Entities.BaseItem,System.String,System.Nullable`1<MediaBrowser.Model.MediaInfo.MediaProtocol>)
FillUserDataDtoValues(MediaBrowser.Model.Dto.UserItemDataDto,MediaBrowser.Controller.Entities.UserItemData,MediaBrowser.Model.Dto.BaseItemDto,Jellyfin.Database.Implementations.Entities.User,MediaBrowser.Controller.Dto.DtoOptions)
GetEtag(Jellyfin.Database.Implementations.Entities.User)
GetEtagValues(Jellyfin.Database.Implementations.Entities.User)
GetAncestorIds()
GetTopParent()
GetIdsForAncestorQuery()
GetRefreshProgress()
OnMetadataChanged()
UpdateRatingToItems(System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Controller.Entities.BaseItem>)
GetThemeSongs(Jellyfin.Database.Implementations.Entities.User)
GetThemeSongs(Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.IEnumerable`1<System.ValueTuple`2<Jellyfin.Data.Enums.ItemSortBy,Jellyfin.Database.Implementations.Enums.SortOrder>>)
GetThemeVideos(Jellyfin.Database.Implementations.Entities.User)
GetThemeVideos(Jellyfin.Database.Implementations.Entities.User,System.Collections.Generic.IEnumerable`1<System.ValueTuple`2<Jellyfin.Data.Enums.ItemSortBy,Jellyfin.Database.Implementations.Enums.SortOrder>>)
GetExtras()
GetExtras(System.Collections.Generic.IReadOnlyCollection`1<MediaBrowser.Model.Entities.ExtraType>)
GetRunTimeTicksForPlayState()
Equals(System.Object)
Equals(MediaBrowser.Controller.Entities.BaseItem)
GetHashCode()