< Summary - Jellyfin

Information
Class: MediaBrowser.Controller.Entities.BaseItem
Assembly: MediaBrowser.Controller
File(s): /srv/git/jellyfin/MediaBrowser.Controller/Entities/BaseItem.cs
Line coverage
60%
Covered lines: 603
Uncovered lines: 388
Coverable lines: 991
Total lines: 3124
Line coverage: 60.8%
Branch coverage
48%
Covered branches: 317
Total branches: 654
Branch coverage: 48.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/9/2026 - 12:15:41 AM Line coverage: 45.5% (404/887) Branch coverage: 36.5% (202/552) Total lines: 27735/20/2026 - 12:15:44 AM Line coverage: 45.5% (404/887) Branch coverage: 32.4% (179/552) Total lines: 27735/27/2026 - 12:15:38 AM Line coverage: 45.6% (406/890) Branch coverage: 32.6% (182/558) Total lines: 27886/2/2026 - 12:15:49 AM Line coverage: 45.9% (408/888) Branch coverage: 33.2% (183/550) Total lines: 27796/6/2026 - 12:15:50 AM Line coverage: 45.9% (408/888) Branch coverage: 33.2% (183/550) Total lines: 27817/6/2026 - 12:16:28 AM Line coverage: 54.4% (505/927) Branch coverage: 41% (244/594) Total lines: 29137/26/2026 - 12:17:51 AM Line coverage: 55% (519/943) Branch coverage: 42% (258/614) Total lines: 29708/3/2026 - 12:16:46 AM Line coverage: 54.5% (519/952) Branch coverage: 41.7% (258/618) Total lines: 30028/6/2026 - 12:17:15 AM Line coverage: 56.9% (547/961) Branch coverage: 43.2% (270/624) Total lines: 302010/29/2026 - 12:17:11 AM Line coverage: 60.8% (603/991) Branch coverage: 48.4% (317/654) Total lines: 3124 5/9/2026 - 12:15:41 AM Line coverage: 45.5% (404/887) Branch coverage: 36.5% (202/552) Total lines: 27735/20/2026 - 12:15:44 AM Line coverage: 45.5% (404/887) Branch coverage: 32.4% (179/552) Total lines: 27735/27/2026 - 12:15:38 AM Line coverage: 45.6% (406/890) Branch coverage: 32.6% (182/558) Total lines: 27886/2/2026 - 12:15:49 AM Line coverage: 45.9% (408/888) Branch coverage: 33.2% (183/550) Total lines: 27796/6/2026 - 12:15:50 AM Line coverage: 45.9% (408/888) Branch coverage: 33.2% (183/550) Total lines: 27817/6/2026 - 12:16:28 AM Line coverage: 54.4% (505/927) Branch coverage: 41% (244/594) Total lines: 29137/26/2026 - 12:17:51 AM Line coverage: 55% (519/943) Branch coverage: 42% (258/614) Total lines: 29708/3/2026 - 12:16:46 AM Line coverage: 54.5% (519/952) Branch coverage: 41.7% (258/618) Total lines: 30028/6/2026 - 12:17:15 AM Line coverage: 56.9% (547/961) Branch coverage: 43.2% (270/624) Total lines: 302010/29/2026 - 12:17:11 AM Line coverage: 60.8% (603/991) Branch coverage: 48.4% (317/654) Total lines: 3124

Coverage delta

Coverage delta 9 -9

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor()100%11100%
get_LUFS()100%11100%
set_LUFS(...)100%11100%
get_NormalizationGain()100%11100%
set_NormalizationGain(...)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_OriginalLanguage()100%11100%
set_OriginalLanguage(...)50%66100%
get_DisplayPreferencesId()50%22100%
get_SourceType()50%2266.66%
get_ContainingFolderPath()100%22100%
get_IsHidden()100%210%
get_LocationType()33.33%7666.66%
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()100%44100%
set_SortName(...)100%11100%
get_DisplayParentId()100%11100%
get_DisplayParent()100%22100%
get_CriticRating()100%11100%
set_CriticRating(...)100%11100%
get_CommunityRating()100%11100%
set_CommunityRating(...)100%11100%
get_HasLocalAlternateVersions()100%210%
get_OfficialRatingForComparison()75%4485.71%
get_CustomRatingForComparison()100%11100%
get_LatestItemsIndexContainer()100%210%
get_EnableRememberingTrackSelections()100%11100%
get_IsTopParent()80%121075%
get_SupportsAncestors()100%11100%
get_SupportsOwnedItems()100%22100%
get_SearchesContainingFolderForExtras()50%1414100%
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()100%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()100%11100%
GetItemByNameFolderName(...)60%111081.81%
GetSortName(...)85.71%141487.5%
ModifySortChunks(...)87.5%8893.75%
GetParent()100%22100%
GetParents()100%22100%
FindParent()50%7440%
GetPlayAccess(...)50%2266.66%
GetMediaStreams()100%210%
IsActiveRecording()100%210%
GetMediaSources(...)75%9877.77%
GetAllItemsForMediaSources()100%210%
GetVersionInfo(...)36.95%594681.63%
GetMediaSourceName(...)57.14%834271.42%
FiniteOrNull(...)100%44100%
GetCommonNamePrefix(...)80%101087.5%
GetCommonVersionPrefix(...)96.15%2626100%
IsDecimalPoint(...)78.57%141487.5%
RefreshMetadata(...)100%11100%
RefreshMetadata()62.5%8882.35%
IsVisibleStandaloneInternal(...)0%342180%
SetParent(...)50%22100%
RefreshedOwnedItems()87.5%8887.5%
GetFileSystemChildren(...)100%11100%
RefreshExtras()36.36%1452236.73%
GetPresentationUniqueKey()0%620%
RequiresRefresh()66.66%66100%
GetUserDataKeys()25%5466.66%
UpdateFromResolvedItem(...)50%2260%
AfterMetadataRefresh()100%11100%
GetPreferredMetadataLanguage()50%88100%
GetPreferredMetadataCountryCode()50%88100%
GetInheritedOriginalLanguage()100%210%
IsSaveLocalMetadataEnabled()50%2275%
IsParentalAllowed(...)18.75%641642.85%
GetParentalRatingScore()100%44100%
GetInheritedTags()100%44100%
IsVisibleViaTags(...)36.36%482262.5%
GetBlockUnratedType()50%2266.66%
GetBlockUnratedValue(...)100%44100%
IsVisible(...)100%11100%
IsVisibleStandalone(...)0%2040%
GetClientTypeName()70%141066.66%
GetBaseItemKind()100%22100%
GetLinkedChild(...)0%7280%
FindLinkedChild(...)0%210140%
AddStudio(...)50%4475%
SetStudios(...)100%11100%
AddGenre(...)50%22100%
MarkPlayed(...)0%110100%
MarkUnplayed(...)100%210%
ResetPlayedState(...)100%11100%
ChangedExternally()100%210%
HasImage(...)100%11100%
SetImage(...)75%4490.9%
SetImagePath(...)75%4490.9%
DeleteImageAsync()0%4260%
RemoveImage(...)100%210%
RemoveImages(...)100%11100%
AddImage(...)100%11100%
UpdateToRepositoryAsync()100%11100%
ReattachUserDataAsync()100%11100%
ValidateImages()91.66%1212100%
GetImagePath(...)50%22100%
GetImageInfo(...)16.66%24620%
GetImageIndex(...)0%110100%
GetImages()83.33%6685.71%
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(...)25%5466.66%
GetMappedPath(...)0%620%
FillUserDataDtoValues(...)0%4260%
InheritDatesFromOwner(...)91.66%1212100%
RefreshMetadataForOwnedItem()0%420200%
RefreshMetadataForOwnedVideo()0%4260%
GetEtag(...)100%11100%
GetEtagValues(...)100%11100%
GetAncestorIds()100%11100%
GetTopParent()100%22100%
GetIdsForAncestorQuery()100%11100%
GetRefreshProgress()100%210%
OnMetadataChanged()62.5%8886.66%
UpdateRatingToItems(...)0%4260%
GetThemeSongs(...)100%210%
GetThemeSongs(...)100%210%
GetThemeVideos(...)100%210%
GetThemeVideos(...)100%210%
GetExtraOwnerIds()100%11100%
GetOwnedVersionIds()100%210%
GetOwnerIdForExtra(...)100%210%
GetExtras(...)100%11100%
GetExtras(...)100%210%
GetRunTimeTicksForPlayState()100%210%
Equals(...)50%22100%
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.Library;
 27using MediaBrowser.Controller.MediaSegments;
 28using MediaBrowser.Controller.Persistence;
 29using MediaBrowser.Controller.Providers;
 30using MediaBrowser.Model.Configuration;
 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        // Well below the 255 byte limit of the common Linux filesystems and the 255 character limit
 52        // of Windows, so the files inside the folder still fit within MAX_PATH.
 53        private const int MaxItemByNameFolderNameBytes = 128;
 54
 55        /// <summary>
 56        /// The supported image extensions.
 57        /// </summary>
 558        public static readonly string[] SupportedImageExtensions
 559            = [".png", ".jpg", ".jpeg", ".webp", ".tbn", ".gif", ".svg"];
 60
 561        private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
 562        {
 563            ".nfo",
 564            ".xml",
 565            ".srt",
 566            ".vtt",
 567            ".sub",
 568            ".sup",
 569            ".idx",
 570            ".txt",
 571            ".edl",
 572            ".bif",
 573            ".smi",
 574            ".ttml",
 575            ".lrc",
 576            ".elrc"
 577        };
 78
 79        /// <summary>
 80        /// Extra types that should be counted and displayed as "Special Features" in the UI.
 81        /// </summary>
 582        public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
 583        {
 584            Model.Entities.ExtraType.Unknown,
 585            Model.Entities.ExtraType.BehindTheScenes,
 586            Model.Entities.ExtraType.Clip,
 587            Model.Entities.ExtraType.DeletedScene,
 588            Model.Entities.ExtraType.Interview,
 589            Model.Entities.ExtraType.Sample,
 590            Model.Entities.ExtraType.Scene,
 591            Model.Entities.ExtraType.Featurette,
 592            Model.Entities.ExtraType.Short
 593        };
 94
 595        private protected static readonly char[] VersionDelimiters = ['-', '_', '.'];
 96
 97        private string _sortName;
 98
 99        private string _forcedSortName;
 100
 101        private string _name;
 102
 103        private string _originalLanguage;
 104
 105        private float? _lufs;
 106
 107        private float? _normalizationGain;
 108
 109        private float? _criticRating;
 110
 111        private float? _communityRating;
 112
 113        public const char SlugChar = '-';
 114
 115        protected BaseItem()
 116        {
 3911117            Tags = Array.Empty<string>();
 3911118            Genres = Array.Empty<string>();
 3911119            Studios = Array.Empty<string>();
 3911120            ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 3911121            LockedFields = Array.Empty<MetadataField>();
 3911122            ImageInfos = Array.Empty<ItemImageInfo>();
 3911123            ProductionLocations = Array.Empty<string>();
 3911124            RemoteTrailers = Array.Empty<MediaUrl>();
 3911125            UserData = [];
 3911126        }
 127
 128        /// <summary>
 129        /// Gets or Sets the user data collection as cached from the last Db query.
 130        /// </summary>
 131        [JsonIgnore]
 132        public ICollection<UserData> UserData { get; set; }
 133
 134        [JsonIgnore]
 135        public string PreferredMetadataCountryCode { get; set; }
 136
 137        [JsonIgnore]
 138        public string PreferredMetadataLanguage { get; set; }
 139
 140        public long? Size { get; set; }
 141
 142        public string Container { get; set; }
 143
 144        [JsonIgnore]
 145        public string Tagline { get; set; }
 146
 147        [JsonIgnore]
 148        public virtual ItemImageInfo[] ImageInfos { get; set; }
 149
 150        [JsonIgnore]
 151        public bool IsVirtualItem { get; set; }
 152
 153        /// <summary>
 154        /// Gets or sets the album.
 155        /// </summary>
 156        /// <value>The album.</value>
 157        [JsonIgnore]
 158        public string Album { get; set; }
 159
 160        /// <summary>
 161        /// Gets or sets the LUFS value.
 162        /// </summary>
 163        /// <value>The LUFS Value.</value>
 164        [JsonIgnore]
 165        public float? LUFS
 166        {
 267167            get => _lufs;
 274168            set => _lufs = FiniteOrNull(value);
 169        }
 170
 171        /// <summary>
 172        /// Gets or sets the gain required for audio normalization.
 173        /// </summary>
 174        /// <value>The gain required for audio normalization.</value>
 175        [JsonIgnore]
 176        public float? NormalizationGain
 177        {
 267178            get => _normalizationGain;
 274179            set => _normalizationGain = FiniteOrNull(value);
 180        }
 181
 182        /// <summary>
 183        /// Gets or sets the channel identifier.
 184        /// </summary>
 185        /// <value>The channel identifier.</value>
 186        [JsonIgnore]
 187        public Guid ChannelId { get; set; }
 188
 189        [JsonIgnore]
 0190        public virtual bool SupportsAddingToPlaylist => false;
 191
 192        [JsonIgnore]
 49193        public virtual bool AlwaysScanInternalMetadataPath => false;
 194
 195        /// <summary>
 196        /// Gets or sets a value indicating whether this instance is in mixed folder.
 197        /// </summary>
 198        /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
 199        [JsonIgnore]
 200        public bool IsInMixedFolder { get; set; }
 201
 202        [JsonIgnore]
 0203        public virtual bool SupportsPlayedStatus => false;
 204
 205        [JsonIgnore]
 0206        public virtual bool SupportsPositionTicksResume => false;
 207
 208        [JsonIgnore]
 18209        public virtual bool SupportsRemoteImageDownloading => true;
 210
 211        /// <summary>
 212        /// Gets or sets the name.
 213        /// </summary>
 214        /// <value>The name.</value>
 215        [JsonIgnore]
 216        public virtual string Name
 217        {
 1407218            get => _name;
 219            set
 220            {
 918221                _name = value;
 222
 223                // lazy load this again
 918224                _sortName = null;
 918225            }
 226        }
 227
 228        [JsonIgnore]
 0229        public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
 230
 231        [JsonIgnore]
 232        public int? TotalBitrate { get; set; }
 233
 234        [JsonIgnore]
 235        public ExtraType? ExtraType { get; set; }
 236
 237        [JsonIgnore]
 0238        public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || Extr
 239
 240        [JsonIgnore]
 241        public string OriginalTitle { get; set; }
 242
 243        [JsonIgnore]
 244        public string OriginalLanguage
 245        {
 540246            get => _originalLanguage;
 449247            set => _originalLanguage = LocalizationManager?.FindLanguageInfo(value)?.TwoLetterISOLanguageName ?? value;
 248        }
 249
 250        /// <summary>
 251        /// Gets or sets the id.
 252        /// </summary>
 253        /// <value>The id.</value>
 254        [JsonIgnore]
 255        public Guid Id { get; set; }
 256
 257        [JsonIgnore]
 258        public Guid OwnerId { get; set; }
 259
 260        /// <summary>
 261        /// Gets or sets the audio.
 262        /// </summary>
 263        /// <value>The audio.</value>
 264        [JsonIgnore]
 265        public ProgramAudio? Audio { get; set; }
 266
 267        /// <summary>
 268        /// Gets the id that should be used to key display prefs for this item.
 269        /// Default is based on the type for everything except actual generic folders.
 270        /// </summary>
 271        /// <value>The display prefs id.</value>
 272        [JsonIgnore]
 273        public virtual Guid DisplayPreferencesId
 274        {
 275            get
 276            {
 6277                var thisType = GetType();
 6278                return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
 279            }
 280        }
 281
 282        /// <summary>
 283        /// Gets or sets the path.
 284        /// </summary>
 285        /// <value>The path.</value>
 286        [JsonIgnore]
 287        public virtual string Path { get; set; }
 288
 289        [JsonIgnore]
 290        public virtual SourceType SourceType
 291        {
 292            get
 293            {
 5381294                if (!ChannelId.IsEmpty())
 295                {
 0296                    return SourceType.Channel;
 297                }
 298
 5381299                return SourceType.Library;
 300            }
 301        }
 302
 303        /// <summary>
 304        /// Gets the folder containing the item.
 305        /// If the item is a folder, it returns the folder itself.
 306        /// </summary>
 307        [JsonIgnore]
 308        public virtual string ContainingFolderPath
 309        {
 310            get
 311            {
 736312                if (IsFolder)
 313                {
 626314                    return Path;
 315                }
 316
 110317                return System.IO.Path.GetDirectoryName(Path);
 318            }
 319        }
 320
 321        /// <summary>
 322        /// Gets or sets the name of the service.
 323        /// </summary>
 324        /// <value>The name of the service.</value>
 325        [JsonIgnore]
 326        public string ServiceName { get; set; }
 327
 328        /// <summary>
 329        /// Gets or sets the external id.
 330        /// </summary>
 331        /// <remarks>
 332        /// If this content came from an external service, the id of the content on that service.
 333        /// </remarks>
 334        [JsonIgnore]
 335        public string ExternalId { get; set; }
 336
 337        [JsonIgnore]
 338        public string ExternalSeriesId { get; set; }
 339
 340        [JsonIgnore]
 0341        public virtual bool IsHidden => false;
 342
 343        /// <summary>
 344        /// Gets the type of the location.
 345        /// </summary>
 346        /// <value>The type of the location.</value>
 347        [JsonIgnore]
 348        public virtual LocationType LocationType
 349        {
 350            get
 351            {
 33352                var path = Path;
 33353                if (string.IsNullOrEmpty(path))
 354                {
 17355                    if (SourceType == SourceType.Channel)
 356                    {
 0357                        return LocationType.Remote;
 358                    }
 359
 17360                    return LocationType.Virtual;
 361                }
 362
 16363                return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
 364            }
 365        }
 366
 367        [JsonIgnore]
 368        public MediaProtocol? PathProtocol
 369        {
 370            get
 371            {
 3906372                var path = Path;
 373
 3906374                if (string.IsNullOrEmpty(path))
 375                {
 131376                    return null;
 377                }
 378
 3775379                return MediaSourceManager.GetPathProtocol(path);
 380            }
 381        }
 382
 383        [JsonIgnore]
 3863384        public bool IsFileProtocol => PathProtocol == MediaProtocol.File;
 385
 386        [JsonIgnore]
 0387        public bool HasPathProtocol => PathProtocol.HasValue;
 388
 389        [JsonIgnore]
 390        public virtual bool SupportsLocalMetadata
 391        {
 392            get
 393            {
 1865394                if (SourceType == SourceType.Channel)
 395                {
 0396                    return false;
 397                }
 398
 1865399                return IsFileProtocol;
 400            }
 401        }
 402
 403        [JsonIgnore]
 404        public virtual string FileNameWithoutExtension
 405        {
 406            get
 407            {
 0408                if (IsFileProtocol)
 409                {
 0410                    return System.IO.Path.GetFileNameWithoutExtension(Path);
 411                }
 412
 0413                return null;
 414            }
 415        }
 416
 417        [JsonIgnore]
 157418        public virtual bool EnableAlphaNumericSorting => true;
 419
 191420        public virtual bool IsHD => Height >= 720;
 421
 422        public bool IsShortcut { get; set; }
 423
 424        public string ShortcutPath { get; set; }
 425
 426        public int Width { get; set; }
 427
 428        public int Height { get; set; }
 429
 430        /// <summary>
 431        /// Gets the primary image path.
 432        /// </summary>
 433        /// <remarks>
 434        /// This is just a helper for convenience.
 435        /// </remarks>
 436        /// <value>The primary image path.</value>
 437        [JsonIgnore]
 0438        public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
 439
 440        /// <summary>
 441        /// Gets or sets the date created.
 442        /// </summary>
 443        /// <value>The date created.</value>
 444        [JsonIgnore]
 445        public DateTime DateCreated { get; set; }
 446
 447        /// <summary>
 448        /// Gets or sets the date modified.
 449        /// </summary>
 450        /// <value>The date modified.</value>
 451        [JsonIgnore]
 452        public DateTime DateModified { get; set; }
 453
 454        public DateTime DateLastSaved { get; set; }
 455
 456        [JsonIgnore]
 457        public DateTime DateLastRefreshed { get; set; }
 458
 459        [JsonIgnore]
 460        public bool IsLocked { get; set; }
 461
 462        /// <summary>
 463        /// Gets or sets the locked fields.
 464        /// </summary>
 465        /// <value>The locked fields.</value>
 466        [JsonIgnore]
 467        public MetadataField[] LockedFields { get; set; }
 468
 469        /// <summary>
 470        /// Gets the type of the media.
 471        /// </summary>
 472        /// <value>The type of the media.</value>
 473        [JsonIgnore]
 188474        public virtual MediaType MediaType => MediaType.Unknown;
 475
 476        [JsonIgnore]
 477        public virtual string[] PhysicalLocations
 478        {
 479            get
 480            {
 0481                if (!IsFileProtocol)
 482                {
 0483                    return Array.Empty<string>();
 484                }
 485
 0486                return [Path];
 487            }
 488        }
 489
 490        [JsonIgnore]
 491        public bool EnableMediaSourceDisplay
 492        {
 493            get
 494            {
 6495                if (SourceType == SourceType.Channel)
 496                {
 0497                    return ChannelManager.EnableMediaSourceDisplay(this);
 498                }
 499
 6500                return true;
 501            }
 502        }
 503
 504        [JsonIgnore]
 505        public Guid ParentId { get; set; }
 506
 507        /// <summary>
 508        /// Gets or sets the logger.
 509        /// </summary>
 510        public static ILogger<BaseItem> Logger { get; set; }
 511
 512        public static ILibraryManager LibraryManager { get; set; }
 513
 514        public static IServerConfigurationManager ConfigurationManager { get; set; }
 515
 516        public static IProviderManager ProviderManager { get; set; }
 517
 518        public static ILocalizationManager LocalizationManager { get; set; }
 519
 520        public static IItemRepository ItemRepository { get; set; }
 521
 522        public static IItemCountService ItemCountService { get; set; }
 523
 524        public static IChapterManager ChapterManager { get; set; }
 525
 526        public static IFileSystem FileSystem { get; set; }
 527
 528        public static IUserDataManager UserDataManager { get; set; }
 529
 530        public static IChannelManager ChannelManager { get; set; }
 531
 532        public static IMediaSourceManager MediaSourceManager { get; set; }
 533
 534        public static IMediaSegmentManager MediaSegmentManager { get; set; }
 535
 536        /// <summary>
 537        /// Gets or sets the name of the forced sort.
 538        /// </summary>
 539        /// <value>The name of the forced sort.</value>
 540        [JsonIgnore]
 541        public string ForcedSortName
 542        {
 654543            get => _forcedSortName;
 544            set
 545            {
 302546                _forcedSortName = value;
 302547                _sortName = null;
 302548            }
 549        }
 550
 551        /// <summary>
 552        /// Gets or sets the name of the sort.
 553        /// </summary>
 554        /// <value>The name of the sort.</value>
 555        [JsonIgnore]
 556        public string SortName
 557        {
 558            get
 559            {
 246560                if (_sortName is null)
 561                {
 157562                    if (!string.IsNullOrEmpty(ForcedSortName))
 563                    {
 564                        // Run the forced sort name through the same cleaning as auto-generated sort names.
 1565                        _sortName = GetSortName(ForcedSortName, EnableAlphaNumericSorting, ConfigurationManager.Configur
 566                    }
 567                    else
 568                    {
 156569                        _sortName = CreateSortName();
 570                    }
 571                }
 572
 246573                return _sortName;
 574            }
 575
 336576            set => _sortName = value;
 577        }
 578
 579        [JsonIgnore]
 1055580        public virtual Guid DisplayParentId => ParentId;
 581
 582        [JsonIgnore]
 583        public BaseItem DisplayParent
 584        {
 585            get
 586            {
 1068587                var id = DisplayParentId;
 1068588                if (id.IsEmpty())
 589                {
 782590                    return null;
 591                }
 592
 286593                return LibraryManager.GetItemById(id);
 594            }
 595        }
 596
 597        /// <summary>
 598        /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be
 599        /// </summary>
 600        /// <value>The premiere date.</value>
 601        [JsonIgnore]
 602        public DateTime? PremiereDate { get; set; }
 603
 604        /// <summary>
 605        /// Gets or sets the end date.
 606        /// </summary>
 607        /// <value>The end date.</value>
 608        [JsonIgnore]
 609        public DateTime? EndDate { get; set; }
 610
 611        /// <summary>
 612        /// Gets or sets the official rating.
 613        /// </summary>
 614        /// <value>The official rating.</value>
 615        [JsonIgnore]
 616        public string OfficialRating { get; set; }
 617
 618        [JsonIgnore]
 619        public int? InheritedParentalRatingValue { get; set; }
 620
 621        [JsonIgnore]
 622        public int? InheritedParentalRatingSubValue { get; set; }
 623
 624        /// <summary>
 625        /// Gets or sets the critic rating.
 626        /// </summary>
 627        /// <value>The critic rating.</value>
 628        [JsonIgnore]
 629        public float? CriticRating
 630        {
 512631            get => _criticRating;
 443632            set => _criticRating = FiniteOrNull(value);
 633        }
 634
 635        /// <summary>
 636        /// Gets or sets the custom rating.
 637        /// </summary>
 638        /// <value>The custom rating.</value>
 639        [JsonIgnore]
 640        public string CustomRating { get; set; }
 641
 642        /// <summary>
 643        /// Gets or sets the overview.
 644        /// </summary>
 645        /// <value>The overview.</value>
 646        [JsonIgnore]
 647        public string Overview { get; set; }
 648
 649        /// <summary>
 650        /// Gets or sets the studios.
 651        /// </summary>
 652        /// <value>The studios.</value>
 653        [JsonIgnore]
 654        public string[] Studios { get; set; }
 655
 656        /// <summary>
 657        /// Gets or sets the genres.
 658        /// </summary>
 659        /// <value>The genres.</value>
 660        [JsonIgnore]
 661        public string[] Genres { get; set; }
 662
 663        /// <summary>
 664        /// Gets or sets the tags.
 665        /// </summary>
 666        /// <value>The tags.</value>
 667        [JsonIgnore]
 668        public string[] Tags { get; set; }
 669
 670        [JsonIgnore]
 671        public string[] ProductionLocations { get; set; }
 672
 673        /// <summary>
 674        /// Gets or sets the home page URL.
 675        /// </summary>
 676        /// <value>The home page URL.</value>
 677        [JsonIgnore]
 678        public string HomePageUrl { get; set; }
 679
 680        /// <summary>
 681        /// Gets or sets the community rating.
 682        /// </summary>
 683        /// <value>The community rating.</value>
 684        [JsonIgnore]
 685        public float? CommunityRating
 686        {
 514687            get => _communityRating;
 463688            set => _communityRating = FiniteOrNull(value);
 689        }
 690
 691        /// <summary>
 692        /// Gets or sets the run time ticks.
 693        /// </summary>
 694        /// <value>The run time ticks.</value>
 695        [JsonIgnore]
 696        public long? RunTimeTicks { get; set; }
 697
 698        /// <summary>
 699        /// Gets or sets the production year.
 700        /// </summary>
 701        /// <value>The production year.</value>
 702        [JsonIgnore]
 703        public int? ProductionYear { get; set; }
 704
 705        /// <summary>
 706        /// Gets or sets the index number. If the item is part of a series, this is it's number in the series.
 707        /// This could be episode number, album track number, etc.
 708        /// </summary>
 709        /// <value>The index number.</value>
 710        [JsonIgnore]
 711        public int? IndexNumber { get; set; }
 712
 713        /// <summary>
 714        /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this cou
 715        /// </summary>
 716        /// <value>The parent index number.</value>
 717        [JsonIgnore]
 718        public int? ParentIndexNumber { get; set; }
 719
 720        [JsonIgnore]
 0721        public virtual bool HasLocalAlternateVersions => false;
 722
 723        [JsonIgnore]
 724        public string OfficialRatingForComparison
 725        {
 726            get
 727            {
 534728                var officialRating = OfficialRating;
 534729                if (!string.IsNullOrEmpty(officialRating))
 730                {
 11731                    return officialRating;
 732                }
 733
 523734                var parent = DisplayParent;
 523735                if (parent is not null)
 736                {
 140737                    return parent.OfficialRatingForComparison;
 738                }
 739
 383740                return null;
 741            }
 742        }
 743
 744        [JsonIgnore]
 745        public string CustomRatingForComparison
 746        {
 747            get
 748            {
 400749                return GetCustomRatingForComparision();
 750            }
 751        }
 752
 753        /// <summary>
 754        /// Gets or sets the provider ids.
 755        /// </summary>
 756        /// <value>The provider ids.</value>
 757        [JsonIgnore]
 758        public Dictionary<string, string> ProviderIds { get; set; }
 759
 760        [JsonIgnore]
 0761        public virtual Folder LatestItemsIndexContainer => null;
 762
 763        [JsonIgnore]
 764        public string PresentationUniqueKey { get; set; }
 765
 766        [JsonIgnore]
 39767        public virtual bool EnableRememberingTrackSelections => true;
 768
 769        [JsonIgnore]
 770        public virtual bool IsTopParent
 771        {
 772            get
 773            {
 408774                if (this is BasePluginFolder || this is Channel)
 775                {
 77776                    return true;
 777                }
 778
 331779                if (this is IHasCollectionType view)
 780                {
 54781                    if (view.CollectionType == CollectionType.livetv)
 782                    {
 0783                        return true;
 784                    }
 785                }
 786
 331787                if (GetParent() is AggregateFolder)
 788                {
 0789                    return true;
 790                }
 791
 331792                return false;
 793            }
 794        }
 795
 796        [JsonIgnore]
 688797        public virtual bool SupportsAncestors => true;
 798
 799        [JsonIgnore]
 182800        protected virtual bool SupportsOwnedItems => !ParentId.IsEmpty() && IsFileProtocol;
 801
 802        /// <summary>
 803        /// Gets a value indicating whether this item searches the folder it lives in for its own extras.
 804        /// </summary>
 805        [JsonIgnore]
 806        protected virtual bool SearchesContainingFolderForExtras =>
 77807            IsFileProtocol
 77808            && SupportsOwnedItems
 77809            && !IsInMixedFolder
 77810            && this is not (ICollectionFolder or UserRootFolder or AggregateFolder)
 77811            && GetType() != typeof(Folder);
 812
 813        [JsonIgnore]
 78814        public virtual bool SupportsPeople => false;
 815
 816        [JsonIgnore]
 0817        public virtual bool SupportsThemeMedia => false;
 818
 819        [JsonIgnore]
 0820        public virtual bool SupportsInheritedParentImages => false;
 821
 822        /// <summary>
 823        /// Gets a value indicating whether this instance is folder.
 824        /// </summary>
 825        /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
 826        [JsonIgnore]
 165827        public virtual bool IsFolder => false;
 828
 829        [JsonIgnore]
 0830        public virtual bool IsDisplayedAsFolder => false;
 831
 832        /// <summary>
 833        /// Gets or sets the remote trailers.
 834        /// </summary>
 835        /// <value>The remote trailers.</value>
 836        public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
 837
 838        private string GetCustomRatingForComparision(HashSet<Guid> callstack = null)
 839        {
 540840            callstack ??= new();
 540841            var customRating = CustomRating;
 540842            if (!string.IsNullOrEmpty(customRating))
 843            {
 6844                return customRating;
 845            }
 846
 534847            callstack.Add(Id);
 848
 534849            var parent = DisplayParent;
 534850            if (parent is not null && !callstack.Contains(parent.Id))
 851            {
 140852                return parent.GetCustomRatingForComparision(callstack);
 853            }
 854
 394855            return null;
 856        }
 857
 858        public virtual double GetDefaultPrimaryImageAspectRatio()
 859        {
 0860            return 0;
 861        }
 862
 863        public virtual string CreatePresentationUniqueKey()
 864        {
 114865            return Id.ToString("N", CultureInfo.InvariantCulture);
 866        }
 867
 868        public virtual bool CanDelete()
 869        {
 0870            if (SourceType == SourceType.Channel)
 871            {
 0872                return ChannelManager.CanDelete(this);
 873            }
 874
 0875            return IsFileProtocol;
 876        }
 877
 878        public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
 879        {
 0880            if (user.HasPermission(PermissionKind.EnableContentDeletion))
 881            {
 0882                return true;
 883            }
 884
 0885            var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
 886
 0887            if (SourceType == SourceType.Channel)
 888            {
 0889                return allowed.Contains(ChannelId);
 890            }
 891
 0892            var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
 893
 0894            foreach (var folder in collectionFolders)
 895            {
 0896                if (allowed.Contains(folder.Id))
 897                {
 0898                    return true;
 899                }
 900            }
 901
 0902            return false;
 0903        }
 904
 905        public BaseItem GetOwner()
 906        {
 972907            var ownerId = OwnerId;
 972908            return ownerId.IsEmpty() ? null : LibraryManager.GetItemById(ownerId);
 909        }
 910
 911        public bool CanDelete(User user, List<Folder> allCollectionFolders)
 912        {
 6913            return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
 914        }
 915
 916        public virtual bool CanDelete(User user)
 917        {
 6918            var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
 919
 6920            return CanDelete(user, allCollectionFolders);
 921        }
 922
 923        public virtual bool CanDownload()
 924        {
 6925            return false;
 926        }
 927
 928        public virtual bool IsAuthorizedToDownload(User user)
 929        {
 0930            return user.HasPermission(PermissionKind.EnableContentDownloading);
 931        }
 932
 933        public bool CanDownload(User user)
 934        {
 6935            return CanDownload() && IsAuthorizedToDownload(user);
 936        }
 937
 938        /// <inheritdoc />
 939        public override string ToString()
 940        {
 69941            return Name;
 942        }
 943
 944        public virtual string GetInternalMetadataPath()
 945        {
 94946            var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
 947
 94948            return GetInternalMetadataPath(basePath);
 949        }
 950
 951        protected virtual string GetInternalMetadataPath(string basePath)
 952        {
 94953            if (SourceType == SourceType.Channel)
 954            {
 0955                return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), 
 956            }
 957
 94958            ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
 959
 94960            return System.IO.Path.Join(basePath, "library", idString[..2], idString);
 961        }
 962
 963        /// <summary>
 964        /// Creates the name of the sort.
 965        /// </summary>
 966        /// <returns>System.String.</returns>
 967        protected virtual string CreateSortName()
 968        {
 156969            return GetSortName(Name, EnableAlphaNumericSorting, ConfigurationManager.Configuration);
 970        }
 971
 972        /// <summary>
 973        /// Turns an item-by-name entity's name into a folder name every supported filesystem accepts.
 974        /// </summary>
 975        /// <param name="name">The entity's name.</param>
 976        /// <returns>The folder name.</returns>
 977        public static string GetItemByNameFolderName(string name)
 978        {
 979            // Trim the period at the end because windows will have a hard time with that
 7980            var validName = FileSystem.GetValidFilename(name).Trim().TrimEnd('.');
 981
 982            // Most Linux filesystems cap a path component at 255 bytes, so a name past that cannot be
 983            // turned into a folder at all - and an entity with no folder can never be created, which
 984            // leaves the credit behind it stuck: not refreshable, not deletable, retried on every scan.
 985            // Only broken provider data gets this long, but it still has to resolve to something, so
 986            // keep a readable prefix and let a hash of the whole name tell two of them apart.
 7987            if (Encoding.UTF8.GetByteCount(validName) <= MaxItemByNameFolderNameBytes)
 988            {
 2989                return validName;
 990            }
 991
 5992            var suffix = "-" + validName.GetMD5().ToString("N", CultureInfo.InvariantCulture);
 5993            var budget = MaxItemByNameFolderNameBytes - suffix.Length;
 5994            var length = Math.Min(validName.Length, budget);
 5995            while (length > 0 && Encoding.UTF8.GetByteCount(validName.AsSpan(0, length)) > budget)
 996            {
 0997                length--;
 998            }
 999
 1000            // Never cut a surrogate pair in half, the lone half is not a valid file name character.
 51001            if (length > 0 && char.IsHighSurrogate(validName[length - 1]))
 1002            {
 01003                length--;
 1004            }
 1005
 51006            return string.Concat(validName.AsSpan(0, length).TrimEnd().TrimEnd('.'), suffix);
 1007        }
 1008
 1009        /// <summary>
 1010        /// Cleans a raw name into its sortable form by applying the configured sort rules.
 1011        /// </summary>
 1012        /// <param name="name">The raw name to clean.</param>
 1013        /// <param name="enableAlphaNumericSorting">Whether alphanumeric sorting rules should be applied.</param>
 1014        /// <param name="configuration">The server configuration providing the sort rules.</param>
 1015        /// <returns>The cleaned, sortable name, or <c>null</c> if <paramref name="name"/> is <c>null</c>.</returns>
 1016        public static string GetSortName(string name, bool enableAlphaNumericSorting, ServerConfiguration configuration)
 1017        {
 1631018            if (name is null)
 1019            {
 01020                return null; // some items may not have name filled in properly
 1021            }
 1022
 1631023            if (!enableAlphaNumericSorting)
 1024            {
 11025                return name.TrimStart();
 1026            }
 1027
 1621028            var sortable = name.Trim().ToLowerInvariant();
 1029
 12961030            foreach (var search in configuration.SortRemoveWords)
 1031            {
 1032                // Remove from beginning if a space follows
 4861033                if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
 1034                {
 41035                    sortable = sortable.Remove(0, search.Length + 1);
 1036                }
 1037
 1038                // Remove from middle if surrounded by spaces
 4861039                sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
 1040
 1041                // Remove from end if preceeded by a space
 4861042                if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
 1043                {
 01044                    sortable = sortable.Remove(sortable.Length - (search.Length + 1));
 1045                }
 1046            }
 1047
 22681048            foreach (var removeChar in configuration.SortRemoveCharacters)
 1049            {
 9721050                sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
 1051            }
 1052
 12961053            foreach (var replaceChar in configuration.SortReplaceCharacters)
 1054            {
 4861055                sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
 1056            }
 1057
 1621058            return ModifySortChunks(sortable);
 1059        }
 1060
 1061        internal static string ModifySortChunks(ReadOnlySpan<char> name)
 1062        {
 1063            static void AppendChunk(StringBuilder builder, bool isDigitChunk, ReadOnlySpan<char> chunk)
 1064            {
 1065                if (isDigitChunk && chunk.Length < 10)
 1066                {
 1067                    builder.Append('0', 10 - chunk.Length);
 1068                }
 1069
 1070                builder.Append(chunk);
 1071            }
 1072
 1681073            if (name.IsEmpty)
 1074            {
 11075                return string.Empty;
 1076            }
 1077
 1671078            var builder = new StringBuilder(name.Length);
 1079
 1671080            int chunkStart = 0;
 1671081            bool isDigitChunk = char.IsDigit(name[0]);
 29441082            for (int i = 0; i < name.Length; i++)
 1083            {
 13051084                var isDigit = char.IsDigit(name[i]);
 13051085                if (isDigit != isDigitChunk)
 1086                {
 61087                    AppendChunk(builder, isDigitChunk, name.Slice(chunkStart, i - chunkStart));
 61088                    chunkStart = i;
 61089                    isDigitChunk = isDigit;
 1090                }
 1091            }
 1092
 1671093            AppendChunk(builder, isDigitChunk, name.Slice(chunkStart));
 1094
 1095            // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
 1671096            var result = builder.ToString().RemoveDiacritics();
 1671097            if (!result.All(char.IsAscii))
 1098            {
 01099                result = result.Transliterated();
 1100            }
 1101
 1671102            return result;
 1103        }
 1104
 1105        public BaseItem GetParent()
 1106        {
 30641107            var parentId = ParentId;
 30641108            if (parentId.IsEmpty())
 1109            {
 24841110                return null;
 1111            }
 1112
 5801113            return LibraryManager.GetItemById(parentId);
 1114        }
 1115
 1116        public IEnumerable<BaseItem> GetParents()
 1117        {
 9781118            var parent = GetParent();
 1119
 11261120            while (parent is not null)
 1121            {
 1491122                yield return parent;
 1123
 1481124                parent = parent.GetParent();
 1125            }
 9771126        }
 1127
 1128        /// <summary>
 1129        /// Finds a parent of a given type.
 1130        /// </summary>
 1131        /// <typeparam name="T">Type of parent.</typeparam>
 1132        /// <returns>``0.</returns>
 1133        public T FindParent<T>()
 1134            where T : Folder
 1135        {
 841136            foreach (var parent in GetParents())
 1137            {
 01138                if (parent is T item)
 1139                {
 01140                    return item;
 1141                }
 1142            }
 1143
 421144            return null;
 01145        }
 1146
 1147        /// <summary>
 1148        /// Gets the play access.
 1149        /// </summary>
 1150        /// <param name="user">The user.</param>
 1151        /// <returns>PlayAccess.</returns>
 1152        public PlayAccess GetPlayAccess(User user)
 1153        {
 61154            if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
 1155            {
 01156                return PlayAccess.None;
 1157            }
 1158
 1159            // if (!user.IsParentalScheduleAllowed())
 1160            // {
 1161            //    return PlayAccess.None;
 1162            // }
 1163
 61164            return PlayAccess.Full;
 1165        }
 1166
 1167        public virtual IReadOnlyList<MediaStream> GetMediaStreams()
 1168        {
 01169            return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
 01170            {
 01171                ItemId = Id
 01172            });
 1173        }
 1174
 1175        protected virtual bool IsActiveRecording()
 1176        {
 01177            return false;
 1178        }
 1179
 1180        public virtual IReadOnlyList<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
 1181        {
 81182            if (SourceType == SourceType.Channel)
 1183            {
 01184                var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
 01185                           .ToList();
 1186
 01187                if (sources.Count > 0)
 1188                {
 01189                    return sources;
 1190                }
 1191            }
 1192
 81193            var list = GetAllItemsForMediaSources().ToList();
 81194            var commonPrefix = GetCommonNamePrefix(list);
 81195            var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item, i.MediaSourceType, commonPrefix
 1196
 81197            if (IsActiveRecording())
 1198            {
 121199                foreach (var mediaSource in result)
 1200                {
 41201                    mediaSource.Type = MediaSourceType.Placeholder;
 1202                }
 1203            }
 1204
 1205            // The source belonging to the item being queried sorts first so it is the default the client plays.
 81206            var selfId = Id.ToString("N", CultureInfo.InvariantCulture);
 1207
 81208            return result
 81209                .OrderByDescending(i => string.Equals(i.Id, selfId, StringComparison.OrdinalIgnoreCase))
 81210                .ThenBy(i => i.VideoType == VideoType.VideoFile ? 0 : 1)
 81211                .ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
 81212                .ThenByDescending(i => i, new MediaSourceWidthComparator())
 81213                .ToArray();
 1214        }
 1215
 1216        protected virtual IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
 1217        {
 01218            return Enumerable.Empty<(BaseItem, MediaSourceType)>();
 1219        }
 1220
 1221        private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type, string 
 1222        {
 221223            ArgumentNullException.ThrowIfNull(item);
 1224
 221225            var protocol = item.PathProtocol;
 221226            var itemPath = item.Path;
 1227
 221228            var info = new MediaSourceInfo
 221229            {
 221230                Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
 221231                Protocol = protocol ?? MediaProtocol.File,
 221232                MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
 221233                MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
 221234                Name = GetMediaSourceName(item, commonPrefix),
 221235                Path = enablePathSubstitution ? GetMappedPath(item, itemPath, protocol) : itemPath,
 221236                RunTimeTicks = item.RunTimeTicks,
 221237                Container = item.Container,
 221238                Size = item.Size,
 221239                Type = type,
 221240                HasSegments = MediaSegmentManager.IsTypeSupported(item)
 221241                    && (protocol is null or MediaProtocol.File)
 221242                    && MediaSegmentManager.HasSegments(item.Id)
 221243            };
 1244
 221245            if (string.IsNullOrEmpty(info.Path))
 1246            {
 01247                info.Type = MediaSourceType.Placeholder;
 1248            }
 1249
 221250            if (info.Protocol == MediaProtocol.File)
 1251            {
 221252                info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", Cultur
 1253            }
 1254
 221255            var video = item as Video;
 221256            if (video is not null)
 1257            {
 221258                info.IsoType = video.IsoType;
 221259                info.VideoType = video.VideoType;
 221260                info.Video3DFormat = video.Video3DFormat;
 221261                info.Timestamp = video.Timestamp;
 1262
 221263                if (video.IsShortcut && !string.IsNullOrEmpty(video.ShortcutPath))
 1264                {
 01265                    var shortcutProtocol = MediaSourceManager.GetPathProtocol(video.ShortcutPath);
 1266
 1267                    // Only allow remote shortcut paths — local file paths in .strm files
 1268                    // could be used to read arbitrary files from the server.
 01269                    if (shortcutProtocol != MediaProtocol.File)
 1270                    {
 01271                        info.IsRemote = true;
 01272                        info.Path = video.ShortcutPath;
 01273                        info.Protocol = shortcutProtocol;
 1274                    }
 1275                }
 1276
 221277                if (string.IsNullOrEmpty(info.Container))
 1278                {
 221279                    if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
 1280                    {
 221281                        if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1282                        {
 221283                            info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1284                        }
 1285                    }
 1286                }
 1287            }
 1288
 221289            if (string.IsNullOrEmpty(info.Container))
 1290            {
 01291                if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1292                {
 01293                    info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1294                }
 1295            }
 1296
 221297            if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
 1298            {
 221299                info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
 1300            }
 1301
 221302            if (video is not null && video.VideoType != VideoType.VideoFile)
 1303            {
 01304                info.SupportsDirectStream = false;
 1305            }
 1306
 221307            info.Bitrate = item.TotalBitrate;
 221308            info.InferTotalBitrate();
 1309
 221310            return info;
 1311        }
 1312
 1313        internal string GetMediaSourceName(BaseItem item, string commonPrefix = null)
 1314        {
 481315            var terms = new List<string>();
 1316
 481317            var path = item.Path;
 481318            if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
 1319            {
 481320                var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
 1321
 1322                // Prefer the suffix that differs from the other versions: strip the prefix shared by
 1323                // all sibling files. This works regardless of folder layout, so it also labels episode
 1324                // versions that share a season folder (e.g. "Greyscale" instead of the full
 1325                // "Show - S01E02 - Title - Greyscale"). The prefix is already retreated to a delimiter
 1326                // boundary (see GetCommonVersionPrefix).
 481327                if (!string.IsNullOrEmpty(commonPrefix)
 481328                    && displayName.Length > commonPrefix.Length
 481329                    && displayName.StartsWith(commonPrefix, StringComparison.OrdinalIgnoreCase))
 1330                {
 351331                    var name = displayName.AsSpan(commonPrefix.Length).TrimStart([' ', .. VersionDelimiters]);
 351332                    if (!name.IsWhiteSpace())
 1333                    {
 351334                        terms.Add(name.ToString());
 1335                    }
 1336                }
 1337
 1338                // Fall back to the containing folder name (the common layout for movie versions, and
 1339                // the path taken when no common prefix could be derived).
 481340                if (terms.Count == 0 && HasLocalAlternateVersions)
 1341                {
 81342                    var containingFolderName = System.IO.Path.GetFileName(ContainingFolderPath);
 81343                    if (displayName.Length > containingFolderName.Length && displayName.StartsWith(containingFolderName,
 1344                    {
 21345                        var name = displayName.AsSpan(containingFolderName.Length).TrimStart([' ', .. VersionDelimiters]
 21346                        if (!name.IsWhiteSpace())
 1347                        {
 21348                            terms.Add(name.ToString());
 1349                        }
 1350                    }
 1351                }
 1352
 481353                if (terms.Count == 0)
 1354                {
 111355                    terms.Add(displayName);
 1356                }
 1357            }
 1358
 481359            if (terms.Count == 0)
 1360            {
 01361                terms.Add(item.Name);
 1362            }
 1363
 481364            if (item is Video video)
 1365            {
 481366                if (video.Video3DFormat.HasValue)
 1367                {
 01368                    terms.Add("3D");
 1369                }
 1370
 481371                if (video.VideoType == VideoType.BluRay)
 1372                {
 01373                    terms.Add("Bluray");
 1374                }
 481375                else if (video.VideoType == VideoType.Dvd)
 1376                {
 01377                    terms.Add("DVD");
 1378                }
 481379                else if (video.VideoType == VideoType.Iso)
 1380                {
 01381                    if (video.IsoType.HasValue)
 1382                    {
 01383                        if (video.IsoType.Value == IsoType.BluRay)
 1384                        {
 01385                            terms.Add("Bluray");
 1386                        }
 01387                        else if (video.IsoType.Value == IsoType.Dvd)
 1388                        {
 01389                            terms.Add("DVD");
 1390                        }
 1391                    }
 1392                    else
 1393                    {
 01394                        terms.Add("ISO");
 1395                    }
 1396                }
 1397            }
 1398
 481399            return string.Join('/', terms);
 1400        }
 1401
 1402        /// <summary>
 1403        /// Treats a rating or gain that is not a finite number as no value, since NaN and infinity
 1404        /// cannot be stored by every database or written as JSON.
 1405        /// </summary>
 1406        /// <param name="value">The value to check.</param>
 1407        /// <returns><paramref name="value"/> when it is finite or has no value, otherwise <see langword="null"/>.</retu
 1408        private static float? FiniteOrNull(float? value)
 14541409            => value.HasValue && !float.IsFinite(value.Value) ? null : value;
 1410
 1411        /// <summary>
 1412        /// Derives the prefix shared by the supplied media source items' file names, used to strip the
 1413        /// common part and surface a short version label per source. Returns null when there are fewer
 1414        /// than two file-based sources, since there is nothing to differentiate.
 1415        /// </summary>
 1416        /// <param name="items">The media source items.</param>
 1417        /// <returns>The shared prefix, or null when no useful prefix exists.</returns>
 1418        private static string GetCommonNamePrefix(IReadOnlyList<(BaseItem Item, MediaSourceType MediaSourceType)> items)
 1419        {
 81420            var fileNames = new List<string>();
 601421            foreach (var (item, _) in items)
 1422            {
 221423                if (item.IsFileProtocol && !string.IsNullOrEmpty(item.Path))
 1424                {
 221425                    fileNames.Add(System.IO.Path.GetFileNameWithoutExtension(item.Path));
 1426                }
 1427            }
 1428
 81429            if (fileNames.Count < 2)
 1430            {
 01431                return null;
 1432            }
 1433
 81434            var prefix = GetCommonVersionPrefix(fileNames);
 81435            return string.IsNullOrEmpty(prefix) ? null : prefix;
 1436        }
 1437
 1438        /// <summary>
 1439        /// Computes the case-insensitive longest common prefix of the supplied version file names,
 1440        /// retreated to the last delimiter boundary. Retreating keeps the differing suffix intact:
 1441        /// it avoids slicing through a word every version shares (e.g. "Grey" in "Greyscale" and
 1442        /// "Greyish") while still trimming the common part when every version is suffixed (e.g.
 1443        /// "- Greyscale" / "- Colorized"). It prefers a structural delimiter ('-', '_', '.') so a
 1444        /// token shared by the descriptors but separated only by spaces (e.g. a common "2160p ") is
 1445        /// kept in the label, falling back to a space only when no structural delimiter is shared. The
 1446        /// separators mirror the version delimiters recognised by the naming layer (Emby.Naming
 1447        /// VideoFlagDelimiters), except that a dot between digits is a decimal point rather than a
 1448        /// delimiter, so numeric version labels stay whole.
 1449        /// </summary>
 1450        /// <param name="fileNames">The version file names without extension; must contain at least one entry.</param>
 1451        /// <returns>The shared prefix retreated to a separator boundary, or an empty string when none is shared.</retur
 1452        internal static string GetCommonVersionPrefix(IReadOnlyList<string> fileNames)
 1453        {
 201454            var prefix = fileNames[0];
 941455            for (var i = 1; i < fileNames.Count && prefix.Length > 0; i++)
 1456            {
 271457                var name = fileNames[i];
 271458                var length = Math.Min(prefix.Length, name.Length);
 271459                var common = 0;
 4331460                while (common < length && char.ToUpperInvariant(prefix[common]) == char.ToUpperInvariant(name[common]))
 1461                {
 4061462                    common++;
 1463                }
 1464
 271465                prefix = prefix[..common];
 1466            }
 1467
 1468            // If the common prefix is itself a whole file name then one version is unlabelled (the
 1469            // base name); the boundary already sits at the end of that name, so don't retreat into it.
 201470            var prefixIsWholeName = false;
 941471            for (var i = 0; i < fileNames.Count; i++)
 1472            {
 361473                if (fileNames[i].Length == prefix.Length)
 1474                {
 91475                    prefixIsWholeName = true;
 91476                    break;
 1477                }
 1478            }
 1479
 201480            if (!prefixIsWholeName)
 1481            {
 1482                // Retreat to the last structural delimiter ('-', '_', '.'), skipping dots that are
 1483                // decimal points within a number rather than delimiters (see IsDecimalPoint).
 111484                var cut = prefix.Length;
 711485                while (cut > 0
 711486                    && (Array.IndexOf(VersionDelimiters, prefix[cut - 1]) < 0
 711487                        || IsDecimalPoint(prefix, cut - 1, fileNames)))
 1488                {
 601489                    cut--;
 1490                }
 1491
 111492                if (cut == 0)
 1493                {
 21494                    cut = prefix.Length;
 51495                    while (cut > 0 && prefix[cut - 1] != ' ')
 1496                    {
 31497                        cut--;
 1498                    }
 1499                }
 1500
 111501                prefix = prefix[..cut];
 1502            }
 1503
 201504            return prefix;
 1505        }
 1506
 1507        private static bool IsDecimalPoint(string prefix, int index, IReadOnlyList<string> fileNames)
 1508        {
 121509            if (index == 0 || prefix[index] != '.' || !char.IsDigit(prefix[index - 1]))
 1510            {
 81511                return false;
 1512            }
 1513
 41514            if (index + 1 < prefix.Length)
 1515            {
 01516                return char.IsDigit(prefix[index + 1]);
 1517            }
 1518
 1519            // The dot ends the prefix, so the character after it is the first one that differs between
 1520            // the versions: only a decimal point when every version continues the number.
 221521            for (var i = 0; i < fileNames.Count; i++)
 1522            {
 81523                if (fileNames[i].Length <= index + 1 || !char.IsDigit(fileNames[i][index + 1]))
 1524                {
 11525                    return false;
 1526                }
 1527            }
 1528
 31529            return true;
 1530        }
 1531
 1532        public Task RefreshMetadata(CancellationToken cancellationToken)
 1533        {
 831534            return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
 1535        }
 1536
 1537        /// <summary>
 1538        /// The base implementation to refresh metadata.
 1539        /// </summary>
 1540        /// <param name="options">The options.</param>
 1541        /// <param name="cancellationToken">The cancellation token.</param>
 1542        /// <returns>true if a provider reports we changed.</returns>
 1543        public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellation
 1544        {
 1071545            var requiresSave = false;
 1546
 1071547            if (SupportsOwnedItems)
 1548            {
 1549                try
 1550                {
 731551                    if (IsFileProtocol)
 1552                    {
 731553                        requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService
 1554                    }
 1555
 731556                    await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties i
 731557                }
 01558                catch (Exception ex)
 1559                {
 01560                    Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
 01561                }
 1562            }
 1563
 1071564            var refreshOptions = requiresSave
 1071565                ? new MetadataRefreshOptions(options)
 1071566                {
 1071567                    ForceSave = true
 1071568                }
 1071569                : options;
 1570
 1071571            return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false
 1071572        }
 1573
 1574        protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
 1575        {
 01576            if (!IsVisible(user))
 1577            {
 01578                return false;
 1579            }
 1580
 01581            var parents = GetParents().ToList();
 01582            if (parents.Any(i => !i.IsVisible(user, true)))
 1583            {
 01584                return false;
 1585            }
 1586
 01587            if (checkFolders)
 1588            {
 01589                var topParent = parents.Count > 0 ? parents[^1] : this;
 1590
 01591                if (string.IsNullOrEmpty(topParent.Path))
 1592                {
 01593                    return true;
 1594                }
 1595
 01596                var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
 1597
 01598                if (itemCollectionFolders.Count > 0)
 1599                {
 01600                    var blockedMediaFolders = user.GetPreferenceValues<Guid>(PreferenceKind.BlockedMediaFolders);
 1601                    IEnumerable<Guid> userCollectionFolderIds;
 01602                    if (blockedMediaFolders.Length > 0)
 1603                    {
 1604                        // User has blocked folders - get all library folders and exclude blocked ones
 01605                        userCollectionFolderIds = LibraryManager.GetUserRootFolder().Children
 01606                            .Select(i => i.Id)
 01607                            .Where(id => !blockedMediaFolders.Contains(id));
 1608                    }
 01609                    else if (user.HasPermission(PermissionKind.EnableAllFolders))
 1610                    {
 1611                        // User can access all folders - no need to filter
 01612                        return true;
 1613                    }
 1614                    else
 1615                    {
 1616                        // User has specific enabled folders
 01617                        userCollectionFolderIds = user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders);
 1618                    }
 1619
 01620                    if (!itemCollectionFolders.Any(userCollectionFolderIds.Contains))
 1621                    {
 01622                        return false;
 1623                    }
 1624                }
 1625            }
 1626
 01627            return true;
 1628        }
 1629
 1630        public void SetParent(Folder parent)
 1631        {
 251632            ParentId = parent is null ? Guid.Empty : parent.Id;
 251633        }
 1634
 1635        /// <summary>
 1636        /// Refreshes owned items such as trailers, theme videos, special features, etc.
 1637        /// Returns true or false indicating if changes were found.
 1638        /// </summary>
 1639        /// <param name="options">The metadata refresh options.</param>
 1640        /// <param name="fileSystemChildren">The list of filesystem children.</param>
 1641        /// <param name="cancellationToken">The cancellation token.</param>
 1642        /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
 1643        protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemM
 1644        {
 751645            if (!SearchesContainingFolderForExtras)
 1646            {
 731647                return false;
 1648            }
 1649
 21650            if (GetParent() is Folder container
 21651                && container.SearchesContainingFolderForExtras
 21652                && string.Equals(container.Path, ContainingFolderPath, StringComparison.OrdinalIgnoreCase))
 1653            {
 11654                return false;
 1655            }
 1656
 11657            return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
 751658        }
 1659
 1660        protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
 1661        {
 581662            return directoryService.GetFileSystemEntries(ContainingFolderPath);
 1663        }
 1664
 1665        private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMe
 1666        {
 1667            // An extra is owned by the version it is named after, so all of them are maintained together.
 11668            var currentExtras = LibraryManager.GetItemList(new InternalItemsQuery()
 11669            {
 11670                OwnerIds = item.GetOwnedVersionIds()
 11671            }).Where(e => e.ExtraType.HasValue).ToList();
 1672
 11673            var currentExtraIds = currentExtras.Select(e => e.Id).ToArray();
 1674
 1675            // Snapshot the persisted names before resolving, as FindExtras corrects the name on the
 1676            // items it hands back and may well hand back these very instances.
 11677            var currentExtraNames = new Dictionary<Guid, string>();
 21678            foreach (var extra in currentExtras)
 1679            {
 01680                currentExtraNames[extra.Id] = extra.Name;
 1681            }
 1682
 11683            var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
 11684            var newExtraIds = Array.ConvertAll(extras, x => x.Id);
 1685
 11686            var renamedExtraIds = extras
 11687                .Where(e => currentExtraNames.TryGetValue(e.Id, out var oldName) && !string.Equals(oldName, e.Name, Stri
 11688                .Select(e => e.Id)
 11689                .ToHashSet();
 1690
 11691            var extrasChanged = !currentExtraIds.OrderBy(x => x).SequenceEqual(newExtraIds.OrderBy(x => x));
 1692
 11693            if (!extrasChanged && renamedExtraIds.Count == 0 && !options.ReplaceAllMetadata && options.MetadataRefreshMo
 1694            {
 1695                // The owner's dates may only have become known after its extras were created, so keep
 1696                // them in sync even when there is nothing to refresh.
 21697                foreach (var extra in currentExtras)
 1698                {
 01699                    if (extra.ExtraType is not null && InheritDatesFromOwner(item, extra))
 1700                    {
 01701                        await extra.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwa
 1702                    }
 1703                }
 1704
 11705                return false;
 1706            }
 1707
 01708            var tasks = extras.Select(i =>
 01709            {
 01710                var ownerId = item.GetOwnerIdForExtra(i);
 01711                var subOptions = new MetadataRefreshOptions(options);
 01712                if (!i.OwnerId.Equals(ownerId) || !i.ParentId.IsEmpty() || renamedExtraIds.Contains(i.Id))
 01713                {
 01714                    subOptions.ForceSave = true;
 01715                }
 01716
 01717                i.OwnerId = ownerId;
 01718                i.ParentId = Guid.Empty;
 01719
 01720                return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
 01721            });
 1722
 01723            var removedExtraIds = currentExtraIds.Where(e => !newExtraIds.Contains(e)).ToArray();
 01724            if (removedExtraIds.Length > 0)
 1725            {
 01726                var removedExtras = LibraryManager.GetItemList(new InternalItemsQuery()
 01727                {
 01728                    ItemIds = removedExtraIds
 01729                });
 01730                foreach (var removedExtra in removedExtras)
 1731                {
 1732                    // Only delete items that are actual extras (have ExtraType set)
 1733                    // Items with OwnerId but no ExtraType might be alternate versions, not extras
 01734                    if (removedExtra.ExtraType.HasValue)
 1735                    {
 01736                        LibraryManager.DeleteItem(removedExtra, new DeleteOptions()
 01737                        {
 01738                            DeleteFileLocation = false
 01739                        });
 1740                    }
 1741                }
 1742            }
 1743
 01744            await Task.WhenAll(tasks).ConfigureAwait(false);
 1745
 01746            return true;
 11747        }
 1748
 1749        public string GetPresentationUniqueKey()
 1750        {
 01751            return PresentationUniqueKey ?? CreatePresentationUniqueKey();
 1752        }
 1753
 1754        public virtual bool RequiresRefresh()
 1755        {
 1071756            if (string.IsNullOrEmpty(Path) || DateModified == DateTime.MinValue)
 1757            {
 1021758                return false;
 1759            }
 1760
 51761            var info = FileSystem.GetFileSystemInfo(Path);
 1762
 51763            return info.Exists && this.HasChanged(info.LastWriteTimeUtc);
 1764        }
 1765
 1766        public virtual List<string> GetUserDataKeys()
 1767        {
 2491768            var list = new List<string>();
 1769
 2491770            if (SourceType == SourceType.Channel)
 1771            {
 01772                if (!string.IsNullOrEmpty(ExternalId))
 1773                {
 01774                    list.Add(ExternalId);
 1775                }
 1776            }
 1777
 2491778            list.Add(Id.ToString());
 2491779            return list;
 1780        }
 1781
 1782        internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
 1783        {
 131784            var updateType = ItemUpdateType.None;
 1785
 131786            if (IsInMixedFolder != newItem.IsInMixedFolder)
 1787            {
 01788                IsInMixedFolder = newItem.IsInMixedFolder;
 01789                updateType |= ItemUpdateType.MetadataImport;
 1790            }
 1791
 131792            return updateType;
 1793        }
 1794
 1795        public void AfterMetadataRefresh()
 1796        {
 1141797            _sortName = null;
 1141798        }
 1799
 1800        /// <summary>
 1801        /// Gets the preferred metadata language.
 1802        /// </summary>
 1803        /// <returns>System.String.</returns>
 1804        public string GetPreferredMetadataLanguage()
 1805        {
 501806            string lang = PreferredMetadataLanguage;
 1807
 501808            if (string.IsNullOrEmpty(lang))
 1809            {
 471810                lang = GetParents()
 471811                    .Select(i => i.PreferredMetadataLanguage)
 471812                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1813            }
 1814
 501815            if (string.IsNullOrEmpty(lang))
 1816            {
 471817                lang = LibraryManager.GetCollectionFolders(this)
 471818                    .Select(i => i.PreferredMetadataLanguage)
 471819                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1820            }
 1821
 501822            if (string.IsNullOrEmpty(lang))
 1823            {
 471824                lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
 1825            }
 1826
 501827            if (string.IsNullOrEmpty(lang))
 1828            {
 471829                lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
 1830            }
 1831
 501832            return lang;
 1833        }
 1834
 1835        /// <summary>
 1836        /// Gets the preferred metadata country code.
 1837        /// </summary>
 1838        /// <returns>System.String.</returns>
 1839        public string GetPreferredMetadataCountryCode()
 1840        {
 671841            string lang = PreferredMetadataCountryCode;
 1842
 671843            if (string.IsNullOrEmpty(lang))
 1844            {
 471845                lang = GetParents()
 471846                    .Select(i => i.PreferredMetadataCountryCode)
 471847                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1848            }
 1849
 671850            if (string.IsNullOrEmpty(lang))
 1851            {
 471852                lang = LibraryManager.GetCollectionFolders(this)
 471853                    .Select(i => i.PreferredMetadataCountryCode)
 471854                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1855            }
 1856
 671857            if (string.IsNullOrEmpty(lang))
 1858            {
 471859                lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
 1860            }
 1861
 671862            if (string.IsNullOrEmpty(lang))
 1863            {
 471864                lang = ConfigurationManager.Configuration.MetadataCountryCode;
 1865            }
 1866
 671867            return lang;
 1868        }
 1869
 1870        /// <summary>
 1871        /// Gets the original language of the item, inheriting from parent items if necessary.
 1872        /// </summary>
 1873        /// <returns>System.String.</returns>
 1874        public virtual string GetInheritedOriginalLanguage()
 1875        {
 01876            return OriginalLanguage;
 1877        }
 1878
 1879        public virtual bool IsSaveLocalMetadataEnabled()
 1880        {
 1161881            if (SourceType == SourceType.Channel)
 1882            {
 01883                return false;
 1884            }
 1885
 1161886            var libraryOptions = LibraryManager.GetLibraryOptions(this);
 1887
 1161888            return libraryOptions.SaveLocalMetadata;
 1889        }
 1890
 1891        /// <summary>
 1892        /// Determines if a given user has access to this item.
 1893        /// </summary>
 1894        /// <param name="user">The user.</param>
 1895        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 1896        /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
 1897        /// <exception cref="ArgumentNullException">If user is null.</exception>
 1898        public bool IsParentalAllowed(User user, bool skipAllowedTagsCheck)
 1899        {
 111900            ArgumentNullException.ThrowIfNull(user);
 1901
 111902            if (!IsVisibleViaTags(user, skipAllowedTagsCheck))
 1903            {
 01904                return false;
 1905            }
 1906
 111907            var maxAllowedRating = user.MaxParentalRatingScore;
 111908            var maxAllowedSubRating = user.MaxParentalRatingSubScore;
 111909            var rating = CustomRatingForComparison;
 1910
 111911            if (string.IsNullOrEmpty(rating))
 1912            {
 111913                rating = OfficialRatingForComparison;
 1914            }
 1915
 111916            if (string.IsNullOrEmpty(rating))
 1917            {
 111918                return !GetBlockUnratedValue(user);
 1919            }
 1920
 01921            var ratingScore = LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1922
 1923            // Could not determine rating level
 01924            if (ratingScore is null)
 1925            {
 01926                var isAllowed = !GetBlockUnratedValue(user);
 1927
 01928                if (!isAllowed)
 1929                {
 01930                    Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
 1931                }
 1932
 01933                return isAllowed;
 1934            }
 1935
 01936            if (!maxAllowedRating.HasValue)
 1937            {
 01938                return true;
 1939            }
 1940
 01941            if (ratingScore.Score != maxAllowedRating.Value)
 1942            {
 01943                return ratingScore.Score < maxAllowedRating.Value;
 1944            }
 1945
 01946            return !maxAllowedSubRating.HasValue || (ratingScore.SubScore ?? 0) <= maxAllowedSubRating.Value;
 1947        }
 1948
 1949        public ParentalRatingScore GetParentalRatingScore()
 1950        {
 3891951            var rating = CustomRatingForComparison;
 1952
 3891953            if (string.IsNullOrEmpty(rating))
 1954            {
 3831955                rating = OfficialRatingForComparison;
 1956            }
 1957
 3891958            if (string.IsNullOrEmpty(rating))
 1959            {
 3721960                return null;
 1961            }
 1962
 171963            return LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1964        }
 1965
 1966        public List<string> GetInheritedTags()
 1967        {
 1731968            var list = new List<string>();
 1731969            list.AddRange(Tags);
 1970
 4421971            foreach (var parent in GetParents())
 1972            {
 481973                list.AddRange(parent.Tags);
 1974            }
 1975
 3641976            foreach (var folder in LibraryManager.GetCollectionFolders(this))
 1977            {
 91978                list.AddRange(folder.Tags);
 1979            }
 1980
 1731981            return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
 1982        }
 1983
 1984        protected bool IsVisibleViaTags(User user, bool skipAllowedTagsCheck)
 1985        {
 111986            var blockedTags = user.GetPreference(PreferenceKind.BlockedTags);
 111987            var allowedTags = user.GetPreference(PreferenceKind.AllowedTags);
 1988
 111989            if (blockedTags.Length == 0 && allowedTags.Length == 0)
 1990            {
 101991                return true;
 1992            }
 1993
 1994            // Normalize tags using the same logic as database queries
 11995            var normalizedBlockedTags = blockedTags
 11996                .Where(t => !string.IsNullOrWhiteSpace(t))
 11997                .Select(t => t.GetCleanValue())
 11998                .ToHashSet(StringComparer.Ordinal);
 1999
 12000            var normalizedItemTags = GetInheritedTags()
 12001                .Select(t => t.GetCleanValue())
 12002                .ToHashSet(StringComparer.Ordinal);
 2003
 2004            // Check blocked tags - item is hidden if it has any blocked tag
 12005            if (normalizedBlockedTags.Overlaps(normalizedItemTags))
 2006            {
 02007                return false;
 2008            }
 2009
 12010            var parent = GetParents().FirstOrDefault() ?? this;
 12011            if (parent is UserRootFolder or AggregateFolder or UserView)
 2012            {
 12013                return true;
 2014            }
 2015
 2016            // Check allowed tags - item must have at least one allowed tag
 02017            if (!skipAllowedTagsCheck && allowedTags.Length > 0)
 2018            {
 02019                var normalizedAllowedTags = allowedTags
 02020                    .Where(t => !string.IsNullOrWhiteSpace(t))
 02021                    .Select(t => t.GetCleanValue())
 02022                    .ToHashSet(StringComparer.Ordinal);
 2023
 02024                if (!normalizedAllowedTags.Overlaps(normalizedItemTags))
 2025                {
 02026                    return false;
 2027                }
 2028            }
 2029
 02030            return true;
 2031        }
 2032
 2033        public virtual UnratedItem GetBlockUnratedType()
 2034        {
 1582035            if (SourceType == SourceType.Channel)
 2036            {
 02037                return UnratedItem.ChannelContent;
 2038            }
 2039
 1582040            return UnratedItem.Other;
 2041        }
 2042
 2043        /// <summary>
 2044        /// Gets a bool indicating if access to the unrated item is blocked or not.
 2045        /// </summary>
 2046        /// <param name="user">The configuration.</param>
 2047        /// <returns><c>true</c> if blocked, <c>false</c> otherwise.</returns>
 2048        protected virtual bool GetBlockUnratedValue(User user)
 2049        {
 2050            // Don't block plain folders that are unrated. Let the media underneath get blocked
 2051            // Special folders like series and albums will override this method.
 112052            if (IsFolder || this is IItemByName)
 2053            {
 82054                return false;
 2055            }
 2056
 32057            return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType(
 2058        }
 2059
 2060        /// <summary>
 2061        /// Determines if this folder should be visible to a given user.
 2062        /// Default is just parental allowed. Can be overridden for more functionality.
 2063        /// </summary>
 2064        /// <param name="user">The user.</param>
 2065        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 2066        /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
 2067        /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
 2068        public virtual bool IsVisible(User user, bool skipAllowedTagsCheck = false)
 2069        {
 82070            ArgumentNullException.ThrowIfNull(user);
 2071
 82072            return IsParentalAllowed(user, skipAllowedTagsCheck);
 2073        }
 2074
 2075        public virtual bool IsVisibleStandalone(User user)
 2076        {
 02077            if (SourceType == SourceType.Channel)
 2078            {
 02079                return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
 2080            }
 2081
 02082            return IsVisibleStandaloneInternal(user, true);
 2083        }
 2084
 2085        public virtual string GetClientTypeName()
 2086        {
 1842087            if (IsFolder && SourceType == SourceType.Channel && this is not Channel && this is not Season && this is not
 2088            {
 02089                return "ChannelFolderItem";
 2090            }
 2091
 1842092            return GetType().Name;
 2093        }
 2094
 2095        public BaseItemKind GetBaseItemKind()
 2096        {
 4302097            return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
 2098        }
 2099
 2100        /// <summary>
 2101        /// Gets the linked child.
 2102        /// </summary>
 2103        /// <param name="info">The info.</param>
 2104        /// <returns>BaseItem.</returns>
 2105        protected BaseItem GetLinkedChild(LinkedChild info)
 2106        {
 2107            // First get using the cached Id
 02108            if (info.ItemId.HasValue)
 2109            {
 02110                if (info.ItemId.Value.IsEmpty())
 2111                {
 02112                    return null;
 2113                }
 2114
 02115                var itemById = LibraryManager.GetItemById(info.ItemId.Value);
 2116
 02117                if (itemById is not null)
 2118                {
 02119                    return itemById;
 2120                }
 2121            }
 2122
 02123            var item = FindLinkedChild(info);
 2124
 2125            // If still null, log
 02126            if (item is null)
 2127            {
 2128                // Don't keep searching over and over
 02129                info.ItemId = Guid.Empty;
 2130            }
 2131            else
 2132            {
 2133                // Cache the id for next time
 02134                info.ItemId = item.Id;
 2135            }
 2136
 02137            return item;
 2138        }
 2139
 2140#pragma warning disable CS0618 // Type or member is obsolete - fallback for legacy LinkedChild data
 2141        private BaseItem FindLinkedChild(LinkedChild info)
 2142        {
 2143            // First try to find by ItemId (new preferred method)
 02144            if (info.ItemId.HasValue && !info.ItemId.Value.Equals(Guid.Empty))
 2145            {
 02146                var item = LibraryManager.GetItemById(info.ItemId.Value);
 02147                if (item is not null)
 2148                {
 02149                    return item;
 2150                }
 2151
 02152                Logger.LogWarning("Unable to find linked item by ItemId {0}", info.ItemId);
 2153            }
 2154
 2155            // Fall back to Path (legacy method)
 02156            var path = info.Path;
 02157            if (!string.IsNullOrEmpty(path))
 2158            {
 02159                path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
 2160
 02161                var itemByPath = LibraryManager.FindByPath(path, null);
 2162
 02163                if (itemByPath is null)
 2164                {
 02165                    Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
 2166                }
 2167
 02168                return itemByPath;
 2169            }
 2170
 2171            // Fall back to LibraryItemId (legacy method)
 02172            if (!string.IsNullOrEmpty(info.LibraryItemId))
 2173            {
 02174                var item = LibraryManager.GetItemById(info.LibraryItemId);
 2175
 02176                if (item is null)
 2177                {
 02178                    Logger.LogWarning("Unable to find linked item by LibraryItemId {0}", info.LibraryItemId);
 2179                }
 2180
 02181                return item;
 2182            }
 2183
 02184            return null;
 2185        }
 2186#pragma warning restore CS0618
 2187
 2188        /// <summary>
 2189        /// Adds a studio to the item.
 2190        /// </summary>
 2191        /// <param name="name">The name.</param>
 2192        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 2193        public void AddStudio(string name)
 2194        {
 42195            ArgumentException.ThrowIfNullOrEmpty(name);
 42196            var current = Studios;
 2197
 42198            if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
 2199            {
 42200                int curLen = current.Length;
 42201                if (curLen == 0)
 2202                {
 42203                    Studios = [name];
 2204                }
 2205                else
 2206                {
 02207                    Studios = [.. current, name];
 2208                }
 2209            }
 02210        }
 2211
 2212        public void SetStudios(IEnumerable<string> names)
 2213        {
 52214            Studios = names.Trimmed().Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 52215        }
 2216
 2217        /// <summary>
 2218        /// Adds a genre to the item.
 2219        /// </summary>
 2220        /// <param name="name">The name.</param>
 2221        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 2222        public void AddGenre(string name)
 2223        {
 132224            ArgumentException.ThrowIfNullOrEmpty(name);
 2225
 132226            var genres = Genres;
 132227            if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
 2228            {
 132229                Genres = [.. genres, name];
 2230            }
 132231        }
 2232
 2233        /// <summary>
 2234        /// Marks the played.
 2235        /// </summary>
 2236        /// <param name="user">The user.</param>
 2237        /// <param name="datePlayed">The date played.</param>
 2238        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 2239        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 2240        public virtual void MarkPlayed(
 2241            User user,
 2242            DateTime? datePlayed,
 2243            bool resetPosition)
 2244        {
 02245            ArgumentNullException.ThrowIfNull(user);
 2246
 02247            var data = UserDataManager.GetUserData(user, this) ?? new UserItemData()
 02248            {
 02249                Key = GetUserDataKeys().First(),
 02250            };
 2251
 02252            if (datePlayed.HasValue)
 2253            {
 2254                // Increment
 02255                data.PlayCount++;
 2256            }
 2257
 2258            // Ensure it's at least one
 02259            data.PlayCount = Math.Max(data.PlayCount, 1);
 2260
 02261            if (resetPosition)
 2262            {
 02263                data.PlaybackPositionTicks = 0;
 2264            }
 2265
 02266            data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
 02267            data.Played = true;
 2268
 02269            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 02270        }
 2271
 2272        /// <summary>
 2273        /// Marks the unplayed.
 2274        /// </summary>
 2275        /// <param name="user">The user.</param>
 2276        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 2277        public virtual void MarkUnplayed(User user)
 2278        {
 02279            ArgumentNullException.ThrowIfNull(user);
 2280
 02281            var data = UserDataManager.GetUserData(user, this);
 2282
 2283            // I think it is okay to do this here.
 2284            // if this is only called when a user is manually forcing something to un-played
 2285            // then it probably is what we want to do...
 02286            ResetPlayedState(data);
 2287
 02288            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 02289        }
 2290
 2291        /// <summary>
 2292        /// Clears the played state on the supplied user data.
 2293        /// </summary>
 2294        /// <param name="data">The user data to reset.</param>
 2295        protected static void ResetPlayedState(UserItemData data)
 2296        {
 22297            ArgumentNullException.ThrowIfNull(data);
 2298
 22299            data.PlayCount = 0;
 22300            data.PlaybackPositionTicks = 0;
 22301            data.LastPlayedDate = null;
 22302            data.Played = false;
 22303        }
 2304
 2305        /// <summary>
 2306        /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
 2307        /// </summary>
 2308        public virtual void ChangedExternally()
 2309        {
 02310            ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriori
 02311        }
 2312
 2313        /// <summary>
 2314        /// Gets an image.
 2315        /// </summary>
 2316        /// <param name="type">The type.</param>
 2317        /// <param name="imageIndex">Index of the image.</param>
 2318        /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
 2319        /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
 2320        public bool HasImage(ImageType type, int imageIndex)
 2321        {
 1532322            return GetImageInfo(type, imageIndex) is not null;
 2323        }
 2324
 2325        public void SetImage(ItemImageInfo image, int index)
 2326        {
 242327            if (image.Type == ImageType.Chapter)
 2328            {
 02329                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 2330            }
 2331
 242332            var existingImage = GetImageInfo(image.Type, index);
 2333
 242334            if (existingImage is null)
 2335            {
 222336                AddImage(image);
 2337            }
 2338            else
 2339            {
 22340                existingImage.Path = image.Path;
 22341                existingImage.DateModified = image.DateModified;
 22342                existingImage.Width = image.Width;
 22343                existingImage.Height = image.Height;
 22344                existingImage.BlurHash = image.BlurHash;
 2345            }
 22346        }
 2347
 2348        public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
 2349        {
 492350            if (type == ImageType.Chapter)
 2351            {
 02352                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 2353            }
 2354
 492355            var image = GetImageInfo(type, index);
 2356
 492357            if (image is null)
 2358            {
 482359                AddImage(GetImageInfo(file, type));
 2360            }
 2361            else
 2362            {
 12363                var imageInfo = GetImageInfo(file, type);
 2364
 12365                image.Path = file.FullName;
 12366                image.DateModified = imageInfo.DateModified;
 2367
 2368                // reset these values
 12369                image.Width = 0;
 12370                image.Height = 0;
 2371            }
 12372        }
 2373
 2374        /// <summary>
 2375        /// Deletes the image.
 2376        /// </summary>
 2377        /// <param name="type">The type.</param>
 2378        /// <param name="index">The index.</param>
 2379        /// <returns>A task.</returns>
 2380        public async Task DeleteImageAsync(ImageType type, int index)
 2381        {
 02382            var info = GetImageInfo(type, index);
 2383
 02384            if (info is null)
 2385            {
 2386                // Nothing to do
 02387                return;
 2388            }
 2389
 2390            // Remove from file system
 02391            var path = info.Path;
 02392            if (info.IsLocalFile && !string.IsNullOrWhiteSpace(path))
 2393            {
 02394                FileSystem.DeleteFile(path);
 2395            }
 2396
 2397            // Remove from item
 02398            RemoveImage(info);
 2399
 02400            await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
 02401        }
 2402
 2403        public void RemoveImage(ItemImageInfo image)
 2404        {
 02405            RemoveImages([image]);
 02406        }
 2407
 2408        public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
 2409        {
 92410            ImageInfos = ImageInfos.Except(deletedImages).ToArray();
 92411        }
 2412
 2413        public void AddImage(ItemImageInfo image)
 2414        {
 702415            ImageInfos = [.. ImageInfos, image];
 702416        }
 2417
 2418        public virtual async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationTok
 1632419         => await LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken).ConfigureAwait(fals
 2420
 2421        public async Task ReattachUserDataAsync(CancellationToken cancellationToken) =>
 462422            await LibraryManager.ReattachUserDataAsync(this, cancellationToken).ConfigureAwait(false);
 2423
 2424        /// <summary>
 2425        /// Validates that images within the item are still on the filesystem.
 2426        /// </summary>
 2427        /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
 2428        public bool ValidateImages()
 2429        {
 1302430            List<ItemImageInfo> deletedImages = null;
 2962431            foreach (var imageInfo in ImageInfos)
 2432            {
 182433                if (!imageInfo.IsLocalFile)
 2434                {
 2435                    continue;
 2436                }
 2437
 182438                if (File.Exists(imageInfo.Path))
 2439                {
 2440                    continue;
 2441                }
 2442
 32443                (deletedImages ??= []).Add(imageInfo);
 2444            }
 2445
 1302446            var anyImagesRemoved = deletedImages?.Count > 0;
 1302447            if (anyImagesRemoved)
 2448            {
 22449                RemoveImages(deletedImages);
 2450            }
 2451
 1302452            return anyImagesRemoved;
 2453        }
 2454
 2455        /// <summary>
 2456        /// Gets the image path.
 2457        /// </summary>
 2458        /// <param name="imageType">Type of the image.</param>
 2459        /// <param name="imageIndex">Index of the image.</param>
 2460        /// <returns>System.String.</returns>
 2461        /// <exception cref="ArgumentNullException">Item is null.</exception>
 2462        public string GetImagePath(ImageType imageType, int imageIndex)
 22463            => GetImageInfo(imageType, imageIndex)?.Path;
 2464
 2465        /// <summary>
 2466        /// Gets the image information.
 2467        /// </summary>
 2468        /// <param name="imageType">Type of the image.</param>
 2469        /// <param name="imageIndex">Index of the image.</param>
 2470        /// <returns>ItemImageInfo.</returns>
 2471        public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
 2472        {
 3852473            if (imageType == ImageType.Chapter)
 2474            {
 02475                var chapter = ChapterManager.GetChapter(Id, imageIndex);
 2476
 02477                if (chapter is null)
 2478                {
 02479                    return null;
 2480                }
 2481
 02482                var path = chapter.ImagePath;
 2483
 02484                if (string.IsNullOrEmpty(path))
 2485                {
 02486                    return null;
 2487                }
 2488
 02489                return new ItemImageInfo
 02490                {
 02491                    Path = path,
 02492                    DateModified = chapter.ImageDateModified,
 02493                    Type = imageType
 02494                };
 2495            }
 2496
 3852497            return GetImages(imageType)
 3852498                .ElementAtOrDefault(imageIndex);
 2499        }
 2500
 2501        /// <summary>
 2502        /// Computes image index for given image or raises if no matching image found.
 2503        /// </summary>
 2504        /// <param name="image">Image to compute index for.</param>
 2505        /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
 2506        /// </exception>
 2507        /// <returns>Image index.</returns>
 2508        public int GetImageIndex(ItemImageInfo image)
 2509        {
 02510            ArgumentNullException.ThrowIfNull(image);
 2511
 02512            if (image.Type == ImageType.Chapter)
 2513            {
 02514                var chapters = ChapterManager.GetChapters(Id);
 02515                for (var i = 0; i < chapters.Count; i++)
 2516                {
 02517                    if (chapters[i].ImagePath == image.Path)
 2518                    {
 02519                        return i;
 2520                    }
 2521                }
 2522
 02523                throw new ArgumentException("No chapter index found for image path", image.Path);
 2524            }
 2525
 02526            var images = GetImages(image.Type).ToArray();
 02527            for (var i = 0; i < images.Length; i++)
 2528            {
 02529                if (images[i].Path == image.Path)
 2530                {
 02531                    return i;
 2532                }
 2533            }
 2534
 02535            throw new ArgumentException("No image index found for image path", image.Path);
 2536        }
 2537
 2538        public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
 2539        {
 5052540            if (imageType == ImageType.Chapter)
 2541            {
 02542                throw new ArgumentException("No image info for chapter images");
 2543            }
 2544
 2545            // Yield return is more performant than LINQ Where on an Array
 15842546            for (var i = 0; i < ImageInfos.Length; i++)
 2547            {
 3132548                var imageInfo = ImageInfos[i];
 3132549                if (imageInfo.Type == imageType)
 2550                {
 1672551                    yield return imageInfo;
 2552                }
 2553            }
 4792554        }
 2555
 2556        /// <summary>
 2557        /// Adds the images, updating metadata if they already are part of this item.
 2558        /// </summary>
 2559        /// <param name="imageType">Type of the image.</param>
 2560        /// <param name="images">The images.</param>
 2561        /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
 2562        /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
 2563        public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
 2564        {
 52565            if (imageType == ImageType.Chapter)
 2566            {
 02567                throw new ArgumentException("Cannot call AddImages with chapter images");
 2568            }
 2569
 52570            var existingImages = GetImages(imageType)
 52571                .ToList();
 2572
 52573            var newImageList = new List<FileSystemMetadata>();
 52574            var imageUpdated = false;
 2575
 302576            foreach (var newImage in images)
 2577            {
 102578                if (newImage is null)
 2579                {
 02580                    throw new ArgumentException("null image found in list");
 2581                }
 2582
 102583                var existing = existingImages
 102584                    .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
 2585
 102586                if (existing is null)
 2587                {
 42588                    newImageList.Add(newImage);
 2589                }
 2590                else
 2591                {
 62592                    if (existing.IsLocalFile)
 2593                    {
 62594                        var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
 2595
 2596                        // If date changed then we need to reset saved image dimensions. Stores such as PostgreSQL keep
 2597                        // only microseconds, so an exact comparison would treat every unchanged image as modified.
 62598                        if (Math.Abs((existing.DateModified - newDateModified).TotalSeconds) > 1 && (existing.Width > 0 
 2599                        {
 22600                            existing.Width = 0;
 22601                            existing.Height = 0;
 22602                            imageUpdated = true;
 2603                        }
 2604
 62605                        existing.DateModified = newDateModified;
 2606                    }
 2607                }
 2608            }
 2609
 52610            if (newImageList.Count > 0)
 2611            {
 22612                ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
 2613            }
 2614
 52615            return imageUpdated || newImageList.Count > 0;
 2616        }
 2617
 2618        private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
 2619        {
 532620            return new ItemImageInfo
 532621            {
 532622                Path = file.FullName,
 532623                Type = type,
 532624                DateModified = FileSystem.GetLastWriteTimeUtc(file)
 532625            };
 2626        }
 2627
 2628        /// <summary>
 2629        /// Gets the file system path to delete when the item is to be deleted.
 2630        /// </summary>
 2631        /// <returns>The metadata for the deleted paths.</returns>
 2632        public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
 2633        {
 02634            return new[]
 02635            {
 02636                FileSystem.GetFileSystemInfo(Path)
 02637            }.Concat(GetLocalMetadataFilesToDelete());
 2638        }
 2639
 2640        protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
 2641        {
 02642            if (IsFolder || !IsInMixedFolder)
 2643            {
 02644                return [];
 2645            }
 2646
 02647            var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
 2648
 02649            return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
 02650                .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison
 02651                .ToList();
 2652        }
 2653
 2654        public bool AllowsMultipleImages(ImageType type)
 2655        {
 232656            return type == ImageType.Backdrop || type == ImageType.Chapter;
 2657        }
 2658
 2659        public Task SwapImagesAsync(ImageType type, int index1, int index2)
 2660        {
 02661            if (!AllowsMultipleImages(type))
 2662            {
 02663                throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots
 2664            }
 2665
 02666            var info1 = GetImageInfo(type, index1);
 02667            var info2 = GetImageInfo(type, index2);
 2668
 02669            if (info1 is null || info2 is null)
 2670            {
 2671                // Nothing to do
 02672                return Task.CompletedTask;
 2673            }
 2674
 02675            if (!info1.IsLocalFile || !info2.IsLocalFile)
 2676            {
 2677                // TODO: Not supported  yet
 02678                return Task.CompletedTask;
 2679            }
 2680
 02681            var path1 = info1.Path;
 02682            var path2 = info2.Path;
 2683
 02684            FileSystem.SwapFiles(path1, path2);
 2685
 2686            // Refresh these values
 02687            info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
 02688            info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
 2689
 02690            info1.Width = 0;
 02691            info1.Height = 0;
 02692            info2.Width = 0;
 02693            info2.Height = 0;
 2694
 02695            return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
 2696        }
 2697
 2698        public virtual bool IsPlayed(User user, UserItemData userItemData)
 2699        {
 02700            userItemData ??= UserDataManager.GetUserData(user, this);
 2701
 02702            return userItemData is not null && userItemData.Played;
 2703        }
 2704
 2705        public bool IsFavoriteOrLiked(User user, UserItemData userItemData)
 2706        {
 02707            userItemData ??= UserDataManager.GetUserData(user, this);
 2708
 02709            return userItemData is not null && (userItemData.IsFavorite || (userItemData.Likes ?? false));
 2710        }
 2711
 2712        public virtual bool IsUnplayed(User user, UserItemData userItemData)
 2713        {
 02714            ArgumentNullException.ThrowIfNull(user);
 2715
 02716            userItemData ??= UserDataManager.GetUserData(user, this);
 2717
 02718            return userItemData is null || !userItemData.Played;
 2719        }
 2720
 2721        ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
 2722        {
 502723            return GetItemLookupInfo<ItemLookupInfo>();
 2724        }
 2725
 2726        protected T GetItemLookupInfo<T>()
 2727            where T : ItemLookupInfo, new()
 2728        {
 502729            return new T
 502730            {
 502731                Path = Path,
 502732                MetadataCountryCode = GetPreferredMetadataCountryCode(),
 502733                MetadataLanguage = GetPreferredMetadataLanguage(),
 502734                Name = GetNameForMetadataLookup(),
 502735                OriginalTitle = OriginalTitle,
 502736                ProviderIds = ProviderIds,
 502737                IndexNumber = IndexNumber,
 502738                ParentIndexNumber = ParentIndexNumber,
 502739                Year = ProductionYear,
 502740                PremiereDate = PremiereDate
 502741            };
 2742        }
 2743
 2744        protected virtual string GetNameForMetadataLookup()
 2745        {
 502746            return Name;
 2747        }
 2748
 2749        /// <summary>
 2750        /// This is called before any metadata refresh and returns true if changes were made.
 2751        /// </summary>
 2752        /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
 2753        /// <returns>true if the item has change, else false.</returns>
 2754        public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
 2755        {
 472756            _sortName = null;
 2757
 472758            var hasChanges = false;
 2759
 472760            if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
 2761            {
 02762                Name = System.IO.Path.GetFileNameWithoutExtension(Path);
 02763                hasChanges = true;
 2764            }
 2765
 472766            return hasChanges;
 2767        }
 2768
 2769        protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
 2770        {
 02771            if (protocol == MediaProtocol.File)
 2772            {
 02773                return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
 2774            }
 2775
 02776            return path;
 2777        }
 2778
 2779        public virtual void FillUserDataDtoValues(
 2780            UserItemDataDto dto,
 2781            UserItemData userData,
 2782            BaseItemDto itemDto,
 2783            User user,
 2784            DtoOptions fields,
 2785            (int Played, int Total)? precomputedCounts = null)
 2786        {
 02787            if (RunTimeTicks.HasValue)
 2788            {
 02789                double pct = RunTimeTicks.Value;
 2790
 02791                if (pct > 0)
 2792                {
 02793                    pct = userData.PlaybackPositionTicks / pct;
 2794
 02795                    if (pct > 0)
 2796                    {
 02797                        dto.PlayedPercentage = 100 * pct;
 2798                    }
 2799                }
 2800            }
 02801        }
 2802
 2803        /// <summary>
 2804        /// Applies the owner's premiere date and production year to an owned item, returning whether anything changed.
 2805        /// </summary>
 2806        /// <param name="owner">The owner.</param>
 2807        /// <param name="ownedItem">The owned item.</param>
 2808        /// <returns><c>true</c> if the owned item was changed, else <c>false</c>.</returns>
 2809        internal static bool InheritDatesFromOwner(BaseItem owner, BaseItem ownedItem)
 2810        {
 2811            // Extras have no release date of their own, so the owner's is authoritative.
 42812            var changed = false;
 2813
 42814            if (owner.ProductionYear is not null && ownedItem.ProductionYear != owner.ProductionYear)
 2815            {
 22816                ownedItem.ProductionYear = owner.ProductionYear;
 22817                changed = true;
 2818            }
 2819
 42820            if (owner.PremiereDate is not null && ownedItem.PremiereDate != owner.PremiereDate)
 2821            {
 22822                ownedItem.PremiereDate = owner.PremiereDate;
 22823                changed = true;
 2824            }
 2825
 42826            return changed;
 2827        }
 2828
 2829        protected async Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOpti
 2830        {
 02831            var newOptions = new MetadataRefreshOptions(options)
 02832            {
 02833                SearchResult = null
 02834            };
 2835
 02836            var item = this;
 2837
 02838            if (copyTitleMetadata)
 2839            {
 2840                // Take some data from the main item, for querying purposes
 02841                if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
 2842                {
 02843                    newOptions.ForceSave = true;
 02844                    ownedItem.Genres = item.Genres;
 2845                }
 2846
 02847                if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
 2848                {
 02849                    newOptions.ForceSave = true;
 02850                    ownedItem.Studios = item.Studios;
 2851                }
 2852
 02853                if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
 2854                {
 02855                    newOptions.ForceSave = true;
 02856                    ownedItem.ProductionLocations = item.ProductionLocations;
 2857                }
 2858
 02859                if (item.CommunityRating != ownedItem.CommunityRating)
 2860                {
 02861                    ownedItem.CommunityRating = item.CommunityRating;
 02862                    newOptions.ForceSave = true;
 2863                }
 2864
 02865                if (item.CriticRating != ownedItem.CriticRating)
 2866                {
 02867                    ownedItem.CriticRating = item.CriticRating;
 02868                    newOptions.ForceSave = true;
 2869                }
 2870
 02871                if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
 2872                {
 02873                    ownedItem.Overview = item.Overview;
 02874                    newOptions.ForceSave = true;
 2875                }
 2876
 02877                if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
 2878                {
 02879                    ownedItem.OfficialRating = item.OfficialRating;
 02880                    newOptions.ForceSave = true;
 2881                }
 2882
 02883                if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
 2884                {
 02885                    ownedItem.CustomRating = item.CustomRating;
 02886                    newOptions.ForceSave = true;
 2887                }
 2888
 02889                if (InheritDatesFromOwner(item, ownedItem))
 2890                {
 02891                    newOptions.ForceSave = true;
 2892                }
 2893            }
 2894
 02895            await ownedItem.RefreshMetadata(newOptions, cancellationToken).ConfigureAwait(false);
 02896        }
 2897
 2898        protected async Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string
 2899        {
 02900            var newOptions = new MetadataRefreshOptions(options)
 02901            {
 02902                SearchResult = null
 02903            };
 2904
 02905            var id = LibraryManager.GetNewItemId(path, typeof(Video));
 2906
 2907            // Try to retrieve it from the db. If we don't find it, use the resolved version
 02908            if (LibraryManager.GetItemById(id) is not Video video)
 2909            {
 02910                video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
 2911
 02912                newOptions.ForceSave = true;
 2913            }
 2914
 02915            if (video is null)
 2916            {
 02917                return;
 2918            }
 2919
 02920            if (video.OwnerId.IsEmpty())
 2921            {
 02922                video.OwnerId = Id;
 2923            }
 2924
 02925            await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(fa
 02926        }
 2927
 2928        public string GetEtag(User user)
 2929        {
 62930            var list = GetEtagValues(user);
 2931
 62932            return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
 2933        }
 2934
 2935        protected virtual List<string> GetEtagValues(User user)
 2936        {
 62937            return
 62938            [
 62939                DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
 62940            ];
 2941        }
 2942
 2943        public virtual IEnumerable<Guid> GetAncestorIds()
 2944        {
 1722945            return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
 2946        }
 2947
 2948        public BaseItem GetTopParent()
 2949        {
 1722950            if (IsTopParent)
 2951            {
 272952                return this;
 2953            }
 2954
 1452955            return GetParents().FirstOrDefault(parent => parent.IsTopParent);
 2956        }
 2957
 2958        public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
 2959        {
 1042960            return [Id];
 2961        }
 2962
 2963        public virtual double? GetRefreshProgress()
 2964        {
 02965            return null;
 2966        }
 2967
 2968        public virtual ItemUpdateType OnMetadataChanged()
 2969        {
 3892970            var updateType = ItemUpdateType.None;
 2971
 3892972            var item = this;
 2973
 3892974            var rating = item.GetParentalRatingScore();
 3892975            if (rating is not null)
 2976            {
 22977                if (rating.Score != item.InheritedParentalRatingValue)
 2978                {
 22979                    item.InheritedParentalRatingValue = rating.Score;
 22980                    updateType |= ItemUpdateType.MetadataImport;
 2981                }
 2982
 22983                if (rating.SubScore != item.InheritedParentalRatingSubValue)
 2984                {
 02985                    item.InheritedParentalRatingSubValue = rating.SubScore;
 02986                    updateType |= ItemUpdateType.MetadataImport;
 2987                }
 2988            }
 2989            else
 2990            {
 3872991                if (item.InheritedParentalRatingValue is not null)
 2992                {
 12993                    item.InheritedParentalRatingValue = null;
 12994                    item.InheritedParentalRatingSubValue = null;
 12995                    updateType |= ItemUpdateType.MetadataImport;
 2996                }
 2997            }
 2998
 3892999            return updateType;
 3000        }
 3001
 3002        /// <summary>
 3003        /// Updates the official rating based on content and returns true or false indicating if it changed.
 3004        /// </summary>
 3005        /// <param name="children">Media children.</param>
 3006        /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
 3007        public bool UpdateRatingToItems(IReadOnlyList<BaseItem> children)
 3008        {
 03009            var currentOfficialRating = OfficialRating;
 3010
 3011            // Gather all possible ratings
 03012            var ratings = children
 03013                .Select(i => i.OfficialRating)
 03014                .Where(i => !string.IsNullOrEmpty(i))
 03015                .Distinct(StringComparer.OrdinalIgnoreCase)
 03016                .Select(rating => (rating, LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode())
 03017                .OrderBy(i => i.Item2 is null ? 1001 : i.Item2.Score)
 03018                .ThenBy(i => i.Item2 is null ? 1001 : i.Item2.SubScore)
 03019                .Select(i => i.rating);
 3020
 03021            OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
 3022
 03023            return !string.Equals(
 03024                currentOfficialRating ?? string.Empty,
 03025                OfficialRating ?? string.Empty,
 03026                StringComparison.OrdinalIgnoreCase);
 3027        }
 3028
 3029        public IReadOnlyList<BaseItem> GetThemeSongs(User user = null)
 3030        {
 03031            return GetThemeSongs(user, Array.Empty<(ItemSortBy, SortOrder)>());
 3032        }
 3033
 3034        public IReadOnlyList<BaseItem> GetThemeSongs(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> or
 3035        {
 03036            return LibraryManager.Sort(GetExtras(user).Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong), us
 3037        }
 3038
 3039        public IReadOnlyList<BaseItem> GetThemeVideos(User user = null)
 3040        {
 03041            return GetThemeVideos(user, Array.Empty<(ItemSortBy, SortOrder)>());
 3042        }
 3043
 3044        public IReadOnlyList<BaseItem> GetThemeVideos(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> o
 3045        {
 03046            return LibraryManager.Sort(GetExtras(user).Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo), u
 3047        }
 3048
 3049        /// <summary>
 3050        /// Gets the ids of the items whose owned extras belong to this item.
 3051        /// </summary>
 3052        /// <returns>An array containing the owner ids.</returns>
 3053        protected virtual Guid[] GetExtraOwnerIds()
 3054        {
 63055            return [Id];
 3056        }
 3057
 3058        /// <summary>
 3059        /// Gets the ids of this item and the versions of it whose extras it maintains.
 3060        /// </summary>
 3061        /// <returns>An array containing the version ids.</returns>
 3062        protected virtual Guid[] GetOwnedVersionIds()
 3063        {
 03064            return [Id];
 3065        }
 3066
 3067        /// <summary>
 3068        /// Gets the id of the version an extra belongs to.
 3069        /// </summary>
 3070        /// <param name="extra">The extra.</param>
 3071        /// <returns>The id of the owning version.</returns>
 3072        protected virtual Guid GetOwnerIdForExtra(BaseItem extra)
 3073        {
 03074            return Id;
 3075        }
 3076
 3077        /// <summary>
 3078        /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
 3079        /// </summary>
 3080        /// <param name="user">The user to apply parental restrictions for, or <c>null</c> to skip restriction checks.</
 3081        /// <returns>An enumerable containing the items.</returns>
 3082        public IEnumerable<BaseItem> GetExtras(User user = null)
 3083        {
 63084            return LibraryManager.GetItemList(new InternalItemsQuery(user)
 63085            {
 63086                OwnerIds = GetExtraOwnerIds(),
 63087                OrderBy = [(ItemSortBy.SortName, SortOrder.Ascending)]
 63088            });
 3089        }
 3090
 3091        /// <summary>
 3092        /// Get all extras with specific types that are associated with this item.
 3093        /// </summary>
 3094        /// <param name="extraTypes">The types of extras to retrieve.</param>
 3095        /// <param name="user">The user to apply parental restrictions for, or <c>null</c> to skip restriction checks.</
 3096        /// <returns>An enumerable containing the extras.</returns>
 3097        public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes, User user = null)
 3098        {
 03099            return LibraryManager.GetItemList(new InternalItemsQuery(user)
 03100            {
 03101                OwnerIds = GetExtraOwnerIds(),
 03102                ExtraTypes = extraTypes.ToArray(),
 03103                OrderBy = [(ItemSortBy.SortName, SortOrder.Ascending)]
 03104            });
 3105        }
 3106
 3107        public virtual long GetRunTimeTicksForPlayState()
 3108        {
 03109            return RunTimeTicks ?? 0;
 3110        }
 3111
 3112        /// <inheritdoc />
 3113        public override bool Equals(object obj)
 3114        {
 1383115            return obj is BaseItem baseItem && this.Equals(baseItem);
 3116        }
 3117
 3118        /// <inheritdoc />
 3503119        public bool Equals(BaseItem other) => other is not null && other.Id.Equals(Id);
 3120
 3121        /// <inheritdoc />
 1463122        public override int GetHashCode() => HashCode.Combine(Id);
 3123    }
 3124}

Methods/Properties

.cctor()
.ctor()
get_LUFS()
set_LUFS(System.Nullable`1<System.Single>)
get_NormalizationGain()
set_NormalizationGain(System.Nullable`1<System.Single>)
get_SupportsAddingToPlaylist()
get_AlwaysScanInternalMetadataPath()
get_SupportsPlayedStatus()
get_SupportsPositionTicksResume()
get_SupportsRemoteImageDownloading()
get_Name()
set_Name(System.String)
get_IsUnaired()
get_IsThemeMedia()
get_OriginalLanguage()
set_OriginalLanguage(System.String)
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_CriticRating()
set_CriticRating(System.Nullable`1<System.Single>)
get_CommunityRating()
set_CommunityRating(System.Nullable`1<System.Single>)
get_HasLocalAlternateVersions()
get_OfficialRatingForComparison()
get_CustomRatingForComparison()
get_LatestItemsIndexContainer()
get_EnableRememberingTrackSelections()
get_IsTopParent()
get_SupportsAncestors()
get_SupportsOwnedItems()
get_SearchesContainingFolderForExtras()
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()
GetItemByNameFolderName(System.String)
GetSortName(System.String,System.Boolean,MediaBrowser.Model.Configuration.ServerConfiguration)
ModifySortChunks(System.ReadOnlySpan`1<System.Char>)
GetParent()
GetParents()
FindParent()
GetPlayAccess(Jellyfin.Database.Implementations.Entities.User)
GetMediaStreams()
IsActiveRecording()
GetMediaSources(System.Boolean)
GetAllItemsForMediaSources()
GetVersionInfo(System.Boolean,MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Model.Dto.MediaSourceType,System.String)
GetMediaSourceName(MediaBrowser.Controller.Entities.BaseItem,System.String)
FiniteOrNull(System.Nullable`1<System.Single>)
GetCommonNamePrefix(System.Collections.Generic.IReadOnlyList`1<System.ValueTuple`2<MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Model.Dto.MediaSourceType>>)
GetCommonVersionPrefix(System.Collections.Generic.IReadOnlyList`1<System.String>)
IsDecimalPoint(System.String,System.Int32,System.Collections.Generic.IReadOnlyList`1<System.String>)
RefreshMetadata(System.Threading.CancellationToken)
RefreshMetadata()
IsVisibleStandaloneInternal(Jellyfin.Database.Implementations.Entities.User,System.Boolean)
SetParent(MediaBrowser.Controller.Entities.Folder)
RefreshedOwnedItems()
GetFileSystemChildren(MediaBrowser.Controller.Providers.IDirectoryService)
RefreshExtras()
GetPresentationUniqueKey()
RequiresRefresh()
GetUserDataKeys()
UpdateFromResolvedItem(MediaBrowser.Controller.Entities.BaseItem)
AfterMetadataRefresh()
GetPreferredMetadataLanguage()
GetPreferredMetadataCountryCode()
GetInheritedOriginalLanguage()
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)
ResetPlayedState(MediaBrowser.Controller.Entities.UserItemData)
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)
DeleteImageAsync()
RemoveImage(MediaBrowser.Controller.Entities.ItemImageInfo)
RemoveImages(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Entities.ItemImageInfo>)
AddImage(MediaBrowser.Controller.Entities.ItemImageInfo)
UpdateToRepositoryAsync()
ReattachUserDataAsync()
ValidateImages()
GetImagePath(MediaBrowser.Model.Entities.ImageType,System.Int32)
GetImageInfo(MediaBrowser.Model.Entities.ImageType,System.Int32)
GetImageIndex(MediaBrowser.Controller.Entities.ItemImageInfo)
GetImages()
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,System.Nullable`1<System.ValueTuple`2<System.Int32,System.Int32>>)
InheritDatesFromOwner(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Controller.Entities.BaseItem)
RefreshMetadataForOwnedItem()
RefreshMetadataForOwnedVideo()
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>>)
GetExtraOwnerIds()
GetOwnedVersionIds()
GetOwnerIdForExtra(MediaBrowser.Controller.Entities.BaseItem)
GetExtras(Jellyfin.Database.Implementations.Entities.User)
GetExtras(System.Collections.Generic.IReadOnlyCollection`1<MediaBrowser.Model.Entities.ExtraType>,Jellyfin.Database.Implementations.Entities.User)
GetRunTimeTicksForPlayState()
Equals(System.Object)
Equals(MediaBrowser.Controller.Entities.BaseItem)
GetHashCode()