< Summary - Jellyfin

Information
Class: MediaBrowser.Controller.Entities.BaseItem
Assembly: MediaBrowser.Controller
File(s): /srv/git/jellyfin/MediaBrowser.Controller/Entities/BaseItem.cs
Line coverage
51%
Covered lines: 375
Uncovered lines: 356
Coverable lines: 731
Total lines: 2688
Line coverage: 51.2%
Branch coverage
40%
Covered branches: 185
Total branches: 460
Branch coverage: 40.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 12/2/2025 - 12:10:22 AM Line coverage: 51.2% (376/733) Branch coverage: 40.3% (188/466) Total lines: 269212/29/2025 - 12:13:19 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 26971/19/2026 - 12:13:54 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 27003/3/2026 - 12:13:24 AM Line coverage: 51.2% (375/731) Branch coverage: 40.2% (185/460) Total lines: 2688 12/2/2025 - 12:10:22 AM Line coverage: 51.2% (376/733) Branch coverage: 40.3% (188/466) Total lines: 269212/29/2025 - 12:13:19 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 26971/19/2026 - 12:13:54 AM Line coverage: 51.1% (376/735) Branch coverage: 40.3% (188/466) Total lines: 27003/3/2026 - 12:13:24 AM Line coverage: 51.2% (375/731) Branch coverage: 40.2% (185/460) Total lines: 2688

Coverage delta

Coverage delta 1 -1

Metrics

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

File(s)

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

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CS1591, SA1401
 4
 5using System;
 6using System.Collections.Generic;
 7using System.Collections.Immutable;
 8using System.Globalization;
 9using System.IO;
 10using System.Linq;
 11using System.Text;
 12using System.Text.Json.Serialization;
 13using System.Threading;
 14using System.Threading.Tasks;
 15using Jellyfin.Data;
 16using Jellyfin.Data.Enums;
 17using Jellyfin.Database.Implementations.Entities;
 18using Jellyfin.Database.Implementations.Enums;
 19using Jellyfin.Extensions;
 20using MediaBrowser.Common.Extensions;
 21using MediaBrowser.Controller.Channels;
 22using MediaBrowser.Controller.Chapters;
 23using MediaBrowser.Controller.Configuration;
 24using MediaBrowser.Controller.Dto;
 25using MediaBrowser.Controller.Entities.TV;
 26using MediaBrowser.Controller.IO;
 27using MediaBrowser.Controller.Library;
 28using MediaBrowser.Controller.MediaSegments;
 29using MediaBrowser.Controller.Persistence;
 30using MediaBrowser.Controller.Providers;
 31using MediaBrowser.Model.Dto;
 32using MediaBrowser.Model.Entities;
 33using MediaBrowser.Model.Globalization;
 34using MediaBrowser.Model.IO;
 35using MediaBrowser.Model.Library;
 36using MediaBrowser.Model.LiveTv;
 37using MediaBrowser.Model.MediaInfo;
 38using Microsoft.Extensions.Logging;
 39
 40namespace MediaBrowser.Controller.Entities
 41{
 42    /// <summary>
 43    /// Class BaseItem.
 44    /// </summary>
 45    public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
 46    {
 47        private BaseItemKind? _baseItemKind;
 48
 49        public const string ThemeSongFileName = "theme";
 50
 51        /// <summary>
 52        /// The supported image extensions.
 53        /// </summary>
 454        public static readonly string[] SupportedImageExtensions
 455            = [".png", ".jpg", ".jpeg", ".webp", ".tbn", ".gif", ".svg"];
 56
 457        private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
 458        {
 459            ".nfo",
 460            ".xml",
 461            ".srt",
 462            ".vtt",
 463            ".sub",
 464            ".sup",
 465            ".idx",
 466            ".txt",
 467            ".edl",
 468            ".bif",
 469            ".smi",
 470            ".ttml",
 471            ".lrc",
 472            ".elrc"
 473        };
 74
 75        /// <summary>
 76        /// Extra types that should be counted and displayed as "Special Features" in the UI.
 77        /// </summary>
 478        public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
 479        {
 480            Model.Entities.ExtraType.Unknown,
 481            Model.Entities.ExtraType.BehindTheScenes,
 482            Model.Entities.ExtraType.Clip,
 483            Model.Entities.ExtraType.DeletedScene,
 484            Model.Entities.ExtraType.Interview,
 485            Model.Entities.ExtraType.Sample,
 486            Model.Entities.ExtraType.Scene,
 487            Model.Entities.ExtraType.Featurette,
 488            Model.Entities.ExtraType.Short
 489        };
 90
 91        private string _sortName;
 92
 93        private string _forcedSortName;
 94
 95        private string _name;
 96
 97        public const char SlugChar = '-';
 98
 99        protected BaseItem()
 100        {
 952101            Tags = Array.Empty<string>();
 952102            Genres = Array.Empty<string>();
 952103            Studios = Array.Empty<string>();
 952104            ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 952105            LockedFields = Array.Empty<MetadataField>();
 952106            ImageInfos = Array.Empty<ItemImageInfo>();
 952107            ProductionLocations = Array.Empty<string>();
 952108            RemoteTrailers = Array.Empty<MediaUrl>();
 952109            ExtraIds = Array.Empty<Guid>();
 952110            UserData = [];
 952111        }
 112
 113        /// <summary>
 114        /// Gets or Sets the user data collection as cached from the last Db query.
 115        /// </summary>
 116        [JsonIgnore]
 117        public ICollection<UserData> UserData { get; set; }
 118
 119        [JsonIgnore]
 120        public string PreferredMetadataCountryCode { get; set; }
 121
 122        [JsonIgnore]
 123        public string PreferredMetadataLanguage { get; set; }
 124
 125        public long? Size { get; set; }
 126
 127        public string Container { get; set; }
 128
 129        [JsonIgnore]
 130        public string Tagline { get; set; }
 131
 132        [JsonIgnore]
 133        public virtual ItemImageInfo[] ImageInfos { get; set; }
 134
 135        [JsonIgnore]
 136        public bool IsVirtualItem { get; set; }
 137
 138        /// <summary>
 139        /// Gets or sets the album.
 140        /// </summary>
 141        /// <value>The album.</value>
 142        [JsonIgnore]
 143        public string Album { get; set; }
 144
 145        /// <summary>
 146        /// Gets or sets the LUFS value.
 147        /// </summary>
 148        /// <value>The LUFS Value.</value>
 149        [JsonIgnore]
 150        public float? LUFS { get; set; }
 151
 152        /// <summary>
 153        /// Gets or sets the gain required for audio normalization.
 154        /// </summary>
 155        /// <value>The gain required for audio normalization.</value>
 156        [JsonIgnore]
 157        public float? NormalizationGain { get; set; }
 158
 159        /// <summary>
 160        /// Gets or sets the channel identifier.
 161        /// </summary>
 162        /// <value>The channel identifier.</value>
 163        [JsonIgnore]
 164        public Guid ChannelId { get; set; }
 165
 166        [JsonIgnore]
 0167        public virtual bool SupportsAddingToPlaylist => false;
 168
 169        [JsonIgnore]
 14170        public virtual bool AlwaysScanInternalMetadataPath => false;
 171
 172        /// <summary>
 173        /// Gets or sets a value indicating whether this instance is in mixed folder.
 174        /// </summary>
 175        /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
 176        [JsonIgnore]
 177        public bool IsInMixedFolder { get; set; }
 178
 179        [JsonIgnore]
 0180        public virtual bool SupportsPlayedStatus => false;
 181
 182        [JsonIgnore]
 0183        public virtual bool SupportsPositionTicksResume => false;
 184
 185        [JsonIgnore]
 17186        public virtual bool SupportsRemoteImageDownloading => true;
 187
 188        /// <summary>
 189        /// Gets or sets the name.
 190        /// </summary>
 191        /// <value>The name.</value>
 192        [JsonIgnore]
 193        public virtual string Name
 194        {
 971195            get => _name;
 196            set
 197            {
 350198                _name = value;
 199
 200                // lazy load this again
 350201                _sortName = null;
 350202            }
 203        }
 204
 205        [JsonIgnore]
 0206        public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
 207
 208        [JsonIgnore]
 209        public int? TotalBitrate { get; set; }
 210
 211        [JsonIgnore]
 212        public ExtraType? ExtraType { get; set; }
 213
 214        [JsonIgnore]
 0215        public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || Extr
 216
 217        [JsonIgnore]
 218        public string OriginalTitle { get; set; }
 219
 220        /// <summary>
 221        /// Gets or sets the id.
 222        /// </summary>
 223        /// <value>The id.</value>
 224        [JsonIgnore]
 225        public Guid Id { get; set; }
 226
 227        [JsonIgnore]
 228        public Guid OwnerId { get; set; }
 229
 230        /// <summary>
 231        /// Gets or sets the audio.
 232        /// </summary>
 233        /// <value>The audio.</value>
 234        [JsonIgnore]
 235        public ProgramAudio? Audio { get; set; }
 236
 237        /// <summary>
 238        /// Gets the id that should be used to key display prefs for this item.
 239        /// Default is based on the type for everything except actual generic folders.
 240        /// </summary>
 241        /// <value>The display prefs id.</value>
 242        [JsonIgnore]
 243        public virtual Guid DisplayPreferencesId
 244        {
 245            get
 246            {
 6247                var thisType = GetType();
 6248                return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
 249            }
 250        }
 251
 252        /// <summary>
 253        /// Gets or sets the path.
 254        /// </summary>
 255        /// <value>The path.</value>
 256        [JsonIgnore]
 257        public virtual string Path { get; set; }
 258
 259        [JsonIgnore]
 260        public virtual SourceType SourceType
 261        {
 262            get
 263            {
 2070264                if (!ChannelId.IsEmpty())
 265                {
 0266                    return SourceType.Channel;
 267                }
 268
 2070269                return SourceType.Library;
 270            }
 271        }
 272
 273        /// <summary>
 274        /// Gets the folder containing the item.
 275        /// If the item is a folder, it returns the folder itself.
 276        /// </summary>
 277        [JsonIgnore]
 278        public virtual string ContainingFolderPath
 279        {
 280            get
 281            {
 432282                if (IsFolder)
 283                {
 373284                    return Path;
 285                }
 286
 59287                return System.IO.Path.GetDirectoryName(Path);
 288            }
 289        }
 290
 291        /// <summary>
 292        /// Gets or sets the name of the service.
 293        /// </summary>
 294        /// <value>The name of the service.</value>
 295        [JsonIgnore]
 296        public string ServiceName { get; set; }
 297
 298        /// <summary>
 299        /// Gets or sets the external id.
 300        /// </summary>
 301        /// <remarks>
 302        /// If this content came from an external service, the id of the content on that service.
 303        /// </remarks>
 304        [JsonIgnore]
 305        public string ExternalId { get; set; }
 306
 307        [JsonIgnore]
 308        public string ExternalSeriesId { get; set; }
 309
 310        [JsonIgnore]
 0311        public virtual bool IsHidden => false;
 312
 313        /// <summary>
 314        /// Gets the type of the location.
 315        /// </summary>
 316        /// <value>The type of the location.</value>
 317        [JsonIgnore]
 318        public virtual LocationType LocationType
 319        {
 320            get
 321            {
 9322                var path = Path;
 9323                if (string.IsNullOrEmpty(path))
 324                {
 0325                    if (SourceType == SourceType.Channel)
 326                    {
 0327                        return LocationType.Remote;
 328                    }
 329
 0330                    return LocationType.Virtual;
 331                }
 332
 9333                return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
 334            }
 335        }
 336
 337        [JsonIgnore]
 338        public MediaProtocol? PathProtocol
 339        {
 340            get
 341            {
 2439342                var path = Path;
 343
 2439344                if (string.IsNullOrEmpty(path))
 345                {
 116346                    return null;
 347                }
 348
 2323349                return MediaSourceManager.GetPathProtocol(path);
 350            }
 351        }
 352
 353        [JsonIgnore]
 2418354        public bool IsFileProtocol => PathProtocol == MediaProtocol.File;
 355
 356        [JsonIgnore]
 0357        public bool HasPathProtocol => PathProtocol.HasValue;
 358
 359        [JsonIgnore]
 360        public virtual bool SupportsLocalMetadata
 361        {
 362            get
 363            {
 1286364                if (SourceType == SourceType.Channel)
 365                {
 0366                    return false;
 367                }
 368
 1286369                return IsFileProtocol;
 370            }
 371        }
 372
 373        [JsonIgnore]
 374        public virtual string FileNameWithoutExtension
 375        {
 376            get
 377            {
 0378                if (IsFileProtocol)
 379                {
 0380                    return System.IO.Path.GetFileNameWithoutExtension(Path);
 381                }
 382
 0383                return null;
 384            }
 385        }
 386
 387        [JsonIgnore]
 99388        public virtual bool EnableAlphaNumericSorting => true;
 389
 137390        public virtual bool IsHD => Height >= 720;
 391
 392        public bool IsShortcut { get; set; }
 393
 394        public string ShortcutPath { get; set; }
 395
 396        public int Width { get; set; }
 397
 398        public int Height { get; set; }
 399
 400        public Guid[] ExtraIds { get; set; }
 401
 402        /// <summary>
 403        /// Gets the primary image path.
 404        /// </summary>
 405        /// <remarks>
 406        /// This is just a helper for convenience.
 407        /// </remarks>
 408        /// <value>The primary image path.</value>
 409        [JsonIgnore]
 0410        public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
 411
 412        /// <summary>
 413        /// Gets or sets the date created.
 414        /// </summary>
 415        /// <value>The date created.</value>
 416        [JsonIgnore]
 417        public DateTime DateCreated { get; set; }
 418
 419        /// <summary>
 420        /// Gets or sets the date modified.
 421        /// </summary>
 422        /// <value>The date modified.</value>
 423        [JsonIgnore]
 424        public DateTime DateModified { get; set; }
 425
 426        public DateTime DateLastSaved { get; set; }
 427
 428        [JsonIgnore]
 429        public DateTime DateLastRefreshed { get; set; }
 430
 431        [JsonIgnore]
 432        public bool IsLocked { get; set; }
 433
 434        /// <summary>
 435        /// Gets or sets the locked fields.
 436        /// </summary>
 437        /// <value>The locked fields.</value>
 438        [JsonIgnore]
 439        public MetadataField[] LockedFields { get; set; }
 440
 441        /// <summary>
 442        /// Gets the type of the media.
 443        /// </summary>
 444        /// <value>The type of the media.</value>
 445        [JsonIgnore]
 129446        public virtual MediaType MediaType => MediaType.Unknown;
 447
 448        [JsonIgnore]
 449        public virtual string[] PhysicalLocations
 450        {
 451            get
 452            {
 0453                if (!IsFileProtocol)
 454                {
 0455                    return Array.Empty<string>();
 456                }
 457
 0458                return [Path];
 459            }
 460        }
 461
 462        [JsonIgnore]
 463        public bool EnableMediaSourceDisplay
 464        {
 465            get
 466            {
 6467                if (SourceType == SourceType.Channel)
 468                {
 0469                    return ChannelManager.EnableMediaSourceDisplay(this);
 470                }
 471
 6472                return true;
 473            }
 474        }
 475
 476        [JsonIgnore]
 477        public Guid ParentId { get; set; }
 478
 479        /// <summary>
 480        /// Gets or sets the logger.
 481        /// </summary>
 482        public static ILogger<BaseItem> Logger { get; set; }
 483
 484        public static ILibraryManager LibraryManager { get; set; }
 485
 486        public static IServerConfigurationManager ConfigurationManager { get; set; }
 487
 488        public static IProviderManager ProviderManager { get; set; }
 489
 490        public static ILocalizationManager LocalizationManager { get; set; }
 491
 492        public static IItemRepository ItemRepository { get; set; }
 493
 494        public static IChapterManager ChapterManager { get; set; }
 495
 496        public static IFileSystem FileSystem { get; set; }
 497
 498        public static IUserDataManager UserDataManager { get; set; }
 499
 500        public static IChannelManager ChannelManager { get; set; }
 501
 502        public static IMediaSourceManager MediaSourceManager { get; set; }
 503
 504        public static IMediaSegmentManager MediaSegmentManager { get; set; }
 505
 506        /// <summary>
 507        /// Gets or sets the name of the forced sort.
 508        /// </summary>
 509        /// <value>The name of the forced sort.</value>
 510        [JsonIgnore]
 511        public string ForcedSortName
 512        {
 470513            get => _forcedSortName;
 514            set
 515            {
 88516                _forcedSortName = value;
 88517                _sortName = null;
 88518            }
 519        }
 520
 521        /// <summary>
 522        /// Gets or sets the name of the sort.
 523        /// </summary>
 524        /// <value>The name of the sort.</value>
 525        [JsonIgnore]
 526        public string SortName
 527        {
 528            get
 529            {
 169530                if (_sortName is null)
 531                {
 99532                    if (!string.IsNullOrEmpty(ForcedSortName))
 533                    {
 534                        // Need the ToLower because that's what CreateSortName does
 0535                        _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
 536                    }
 537                    else
 538                    {
 99539                        _sortName = CreateSortName();
 540                    }
 541                }
 542
 169543                return _sortName;
 544            }
 545
 127546            set => _sortName = value;
 547        }
 548
 549        [JsonIgnore]
 342550        public virtual Guid DisplayParentId => ParentId;
 551
 552        [JsonIgnore]
 553        public BaseItem DisplayParent
 554        {
 555            get
 556            {
 336557                var id = DisplayParentId;
 336558                if (id.IsEmpty())
 559                {
 254560                    return null;
 561                }
 562
 82563                return LibraryManager.GetItemById(id);
 564            }
 565        }
 566
 567        /// <summary>
 568        /// Gets or sets the date that the item first debuted. For movies this could be premiere date, episodes would be
 569        /// </summary>
 570        /// <value>The premiere date.</value>
 571        [JsonIgnore]
 572        public DateTime? PremiereDate { get; set; }
 573
 574        /// <summary>
 575        /// Gets or sets the end date.
 576        /// </summary>
 577        /// <value>The end date.</value>
 578        [JsonIgnore]
 579        public DateTime? EndDate { get; set; }
 580
 581        /// <summary>
 582        /// Gets or sets the official rating.
 583        /// </summary>
 584        /// <value>The official rating.</value>
 585        [JsonIgnore]
 586        public string OfficialRating { get; set; }
 587
 588        [JsonIgnore]
 589        public int? InheritedParentalRatingValue { get; set; }
 590
 591        [JsonIgnore]
 592        public int? InheritedParentalRatingSubValue { get; set; }
 593
 594        /// <summary>
 595        /// Gets or sets the critic rating.
 596        /// </summary>
 597        /// <value>The critic rating.</value>
 598        [JsonIgnore]
 599        public float? CriticRating { get; set; }
 600
 601        /// <summary>
 602        /// Gets or sets the custom rating.
 603        /// </summary>
 604        /// <value>The custom rating.</value>
 605        [JsonIgnore]
 606        public string CustomRating { get; set; }
 607
 608        /// <summary>
 609        /// Gets or sets the overview.
 610        /// </summary>
 611        /// <value>The overview.</value>
 612        [JsonIgnore]
 613        public string Overview { get; set; }
 614
 615        /// <summary>
 616        /// Gets or sets the studios.
 617        /// </summary>
 618        /// <value>The studios.</value>
 619        [JsonIgnore]
 620        public string[] Studios { get; set; }
 621
 622        /// <summary>
 623        /// Gets or sets the genres.
 624        /// </summary>
 625        /// <value>The genres.</value>
 626        [JsonIgnore]
 627        public string[] Genres { get; set; }
 628
 629        /// <summary>
 630        /// Gets or sets the tags.
 631        /// </summary>
 632        /// <value>The tags.</value>
 633        [JsonIgnore]
 634        public string[] Tags { get; set; }
 635
 636        [JsonIgnore]
 637        public string[] ProductionLocations { get; set; }
 638
 639        /// <summary>
 640        /// Gets or sets the home page URL.
 641        /// </summary>
 642        /// <value>The home page URL.</value>
 643        [JsonIgnore]
 644        public string HomePageUrl { get; set; }
 645
 646        /// <summary>
 647        /// Gets or sets the community rating.
 648        /// </summary>
 649        /// <value>The community rating.</value>
 650        [JsonIgnore]
 651        public float? CommunityRating { get; set; }
 652
 653        /// <summary>
 654        /// Gets or sets the run time ticks.
 655        /// </summary>
 656        /// <value>The run time ticks.</value>
 657        [JsonIgnore]
 658        public long? RunTimeTicks { get; set; }
 659
 660        /// <summary>
 661        /// Gets or sets the production year.
 662        /// </summary>
 663        /// <value>The production year.</value>
 664        [JsonIgnore]
 665        public int? ProductionYear { get; set; }
 666
 667        /// <summary>
 668        /// Gets or sets the index number. If the item is part of a series, this is it's number in the series.
 669        /// This could be episode number, album track number, etc.
 670        /// </summary>
 671        /// <value>The index number.</value>
 672        [JsonIgnore]
 673        public int? IndexNumber { get; set; }
 674
 675        /// <summary>
 676        /// Gets or sets the parent index number. For an episode this could be the season number, or for a song this cou
 677        /// </summary>
 678        /// <value>The parent index number.</value>
 679        [JsonIgnore]
 680        public int? ParentIndexNumber { get; set; }
 681
 682        [JsonIgnore]
 0683        public virtual bool HasLocalAlternateVersions => false;
 684
 685        [JsonIgnore]
 686        public string OfficialRatingForComparison
 687        {
 688            get
 689            {
 168690                var officialRating = OfficialRating;
 168691                if (!string.IsNullOrEmpty(officialRating))
 692                {
 0693                    return officialRating;
 694                }
 695
 168696                var parent = DisplayParent;
 168697                if (parent is not null)
 698                {
 41699                    return parent.OfficialRatingForComparison;
 700                }
 701
 127702                return null;
 703            }
 704        }
 705
 706        [JsonIgnore]
 707        public string CustomRatingForComparison
 708        {
 709            get
 710            {
 127711                return GetCustomRatingForComparision();
 712            }
 713        }
 714
 715        /// <summary>
 716        /// Gets or sets the provider ids.
 717        /// </summary>
 718        /// <value>The provider ids.</value>
 719        [JsonIgnore]
 720        public Dictionary<string, string> ProviderIds { get; set; }
 721
 722        [JsonIgnore]
 0723        public virtual Folder LatestItemsIndexContainer => null;
 724
 725        [JsonIgnore]
 726        public string PresentationUniqueKey { get; set; }
 727
 728        [JsonIgnore]
 0729        public virtual bool EnableRememberingTrackSelections => true;
 730
 731        [JsonIgnore]
 732        public virtual bool IsTopParent
 733        {
 734            get
 735            {
 261736                if (this is BasePluginFolder || this is Channel)
 737                {
 58738                    return true;
 739                }
 740
 203741                if (this is IHasCollectionType view)
 742                {
 14743                    if (view.CollectionType == CollectionType.livetv)
 744                    {
 0745                        return true;
 746                    }
 747                }
 748
 203749                if (GetParent() is AggregateFolder)
 750                {
 0751                    return true;
 752                }
 753
 203754                return false;
 755            }
 756        }
 757
 758        [JsonIgnore]
 220759        public virtual bool SupportsAncestors => true;
 760
 761        [JsonIgnore]
 92762        protected virtual bool SupportsOwnedItems => !ParentId.IsEmpty() && IsFileProtocol;
 763
 764        [JsonIgnore]
 67765        public virtual bool SupportsPeople => false;
 766
 767        [JsonIgnore]
 0768        public virtual bool SupportsThemeMedia => false;
 769
 770        [JsonIgnore]
 0771        public virtual bool SupportsInheritedParentImages => false;
 772
 773        /// <summary>
 774        /// Gets a value indicating whether this instance is folder.
 775        /// </summary>
 776        /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
 777        [JsonIgnore]
 79778        public virtual bool IsFolder => false;
 779
 780        [JsonIgnore]
 0781        public virtual bool IsDisplayedAsFolder => false;
 782
 783        /// <summary>
 784        /// Gets or sets the remote trailers.
 785        /// </summary>
 786        /// <value>The remote trailers.</value>
 787        public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
 788
 789        private string GetCustomRatingForComparision(HashSet<Guid> callstack = null)
 790        {
 168791            callstack ??= new();
 168792            var customRating = CustomRating;
 168793            if (!string.IsNullOrEmpty(customRating))
 794            {
 0795                return customRating;
 796            }
 797
 168798            callstack.Add(Id);
 799
 168800            var parent = DisplayParent;
 168801            if (parent is not null && !callstack.Contains(parent.Id))
 802            {
 41803                return parent.GetCustomRatingForComparision(callstack);
 804            }
 805
 127806            return null;
 807        }
 808
 809        public virtual double GetDefaultPrimaryImageAspectRatio()
 810        {
 0811            return 0;
 812        }
 813
 814        public virtual string CreatePresentationUniqueKey()
 815        {
 57816            return Id.ToString("N", CultureInfo.InvariantCulture);
 817        }
 818
 819        public virtual bool CanDelete()
 820        {
 0821            if (SourceType == SourceType.Channel)
 822            {
 0823                return ChannelManager.CanDelete(this);
 824            }
 825
 0826            return IsFileProtocol;
 827        }
 828
 829        public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
 830        {
 0831            if (user.HasPermission(PermissionKind.EnableContentDeletion))
 832            {
 0833                return true;
 834            }
 835
 0836            var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
 837
 0838            if (SourceType == SourceType.Channel)
 839            {
 0840                return allowed.Contains(ChannelId);
 841            }
 842
 0843            var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
 844
 0845            foreach (var folder in collectionFolders)
 846            {
 0847                if (allowed.Contains(folder.Id))
 848                {
 0849                    return true;
 850                }
 851            }
 852
 0853            return false;
 0854        }
 855
 856        public BaseItem GetOwner()
 857        {
 623858            var ownerId = OwnerId;
 623859            return ownerId.IsEmpty() ? null : LibraryManager.GetItemById(ownerId);
 860        }
 861
 862        public bool CanDelete(User user, List<Folder> allCollectionFolders)
 863        {
 6864            return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
 865        }
 866
 867        public virtual bool CanDelete(User user)
 868        {
 6869            var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
 870
 6871            return CanDelete(user, allCollectionFolders);
 872        }
 873
 874        public virtual bool CanDownload()
 875        {
 6876            return false;
 877        }
 878
 879        public virtual bool IsAuthorizedToDownload(User user)
 880        {
 0881            return user.HasPermission(PermissionKind.EnableContentDownloading);
 882        }
 883
 884        public bool CanDownload(User user)
 885        {
 6886            return CanDownload() && IsAuthorizedToDownload(user);
 887        }
 888
 889        /// <inheritdoc />
 890        public override string ToString()
 891        {
 69892            return Name;
 893        }
 894
 895        public virtual string GetInternalMetadataPath()
 896        {
 71897            var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
 898
 71899            return GetInternalMetadataPath(basePath);
 900        }
 901
 902        protected virtual string GetInternalMetadataPath(string basePath)
 903        {
 71904            if (SourceType == SourceType.Channel)
 905            {
 0906                return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), 
 907            }
 908
 71909            ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
 910
 71911            return System.IO.Path.Join(basePath, "library", idString[..2], idString);
 912        }
 913
 914        /// <summary>
 915        /// Creates the name of the sort.
 916        /// </summary>
 917        /// <returns>System.String.</returns>
 918        protected virtual string CreateSortName()
 919        {
 99920            if (Name is null)
 921            {
 0922                return null; // some items may not have name filled in properly
 923            }
 924
 99925            if (!EnableAlphaNumericSorting)
 926            {
 0927                return Name.TrimStart();
 928            }
 929
 99930            var sortable = Name.Trim().ToLowerInvariant();
 931
 792932            foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
 933            {
 934                // Remove from beginning if a space follows
 297935                if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
 936                {
 0937                    sortable = sortable.Remove(0, search.Length + 1);
 938                }
 939
 940                // Remove from middle if surrounded by spaces
 297941                sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
 942
 943                // Remove from end if preceeded by a space
 297944                if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
 945                {
 0946                    sortable = sortable.Remove(sortable.Length - (search.Length + 1));
 947                }
 948            }
 949
 1386950            foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
 951            {
 594952                sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
 953            }
 954
 792955            foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
 956            {
 297957                sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
 958            }
 959
 99960            return ModifySortChunks(sortable);
 961        }
 962
 963        internal static string ModifySortChunks(ReadOnlySpan<char> name)
 964        {
 965            static void AppendChunk(StringBuilder builder, bool isDigitChunk, ReadOnlySpan<char> chunk)
 966            {
 967                if (isDigitChunk && chunk.Length < 10)
 968                {
 969                    builder.Append('0', 10 - chunk.Length);
 970                }
 971
 972                builder.Append(chunk);
 973            }
 974
 105975            if (name.IsEmpty)
 976            {
 1977                return string.Empty;
 978            }
 979
 104980            var builder = new StringBuilder(name.Length);
 981
 104982            int chunkStart = 0;
 104983            bool isDigitChunk = char.IsDigit(name[0]);
 1664984            for (int i = 0; i < name.Length; i++)
 985            {
 728986                var isDigit = char.IsDigit(name[i]);
 728987                if (isDigit != isDigitChunk)
 988                {
 5989                    AppendChunk(builder, isDigitChunk, name.Slice(chunkStart, i - chunkStart));
 5990                    chunkStart = i;
 5991                    isDigitChunk = isDigit;
 992                }
 993            }
 994
 104995            AppendChunk(builder, isDigitChunk, name.Slice(chunkStart));
 996
 997            // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
 104998            var result = builder.ToString().RemoveDiacritics();
 104999            if (!result.All(char.IsAscii))
 1000            {
 01001                result = result.Transliterated();
 1002            }
 1003
 1041004            return result;
 1005        }
 1006
 1007        public BaseItem GetParent()
 1008        {
 17641009            var parentId = ParentId;
 17641010            if (parentId.IsEmpty())
 1011            {
 14911012                return null;
 1013            }
 1014
 2731015            return LibraryManager.GetItemById(parentId);
 1016        }
 1017
 1018        public IEnumerable<BaseItem> GetParents()
 1019        {
 1020            var parent = GetParent();
 1021
 1022            while (parent is not null)
 1023            {
 1024                yield return parent;
 1025
 1026                parent = parent.GetParent();
 1027            }
 1028        }
 1029
 1030        /// <summary>
 1031        /// Finds a parent of a given type.
 1032        /// </summary>
 1033        /// <typeparam name="T">Type of parent.</typeparam>
 1034        /// <returns>``0.</returns>
 1035        public T FindParent<T>()
 1036            where T : Folder
 1037        {
 01038            foreach (var parent in GetParents())
 1039            {
 01040                if (parent is T item)
 1041                {
 01042                    return item;
 1043                }
 1044            }
 1045
 01046            return null;
 01047        }
 1048
 1049        /// <summary>
 1050        /// Gets the play access.
 1051        /// </summary>
 1052        /// <param name="user">The user.</param>
 1053        /// <returns>PlayAccess.</returns>
 1054        public PlayAccess GetPlayAccess(User user)
 1055        {
 61056            if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
 1057            {
 01058                return PlayAccess.None;
 1059            }
 1060
 1061            // if (!user.IsParentalScheduleAllowed())
 1062            // {
 1063            //    return PlayAccess.None;
 1064            // }
 1065
 61066            return PlayAccess.Full;
 1067        }
 1068
 1069        public virtual IReadOnlyList<MediaStream> GetMediaStreams()
 1070        {
 01071            return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
 01072            {
 01073                ItemId = Id
 01074            });
 1075        }
 1076
 1077        protected virtual bool IsActiveRecording()
 1078        {
 01079            return false;
 1080        }
 1081
 1082        public virtual IReadOnlyList<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
 1083        {
 01084            if (SourceType == SourceType.Channel)
 1085            {
 01086                var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
 01087                           .ToList();
 1088
 01089                if (sources.Count > 0)
 1090                {
 01091                    return sources;
 1092                }
 1093            }
 1094
 01095            var list = GetAllItemsForMediaSources();
 01096            var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item, i.MediaSourceType)).ToList();
 1097
 01098            if (IsActiveRecording())
 1099            {
 01100                foreach (var mediaSource in result)
 1101                {
 01102                    mediaSource.Type = MediaSourceType.Placeholder;
 1103                }
 1104            }
 1105
 01106            return result.OrderBy(i =>
 01107            {
 01108                if (i.VideoType == VideoType.VideoFile)
 01109                {
 01110                    return 0;
 01111                }
 01112
 01113                return 1;
 01114            }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
 01115            .ThenByDescending(i => i, new MediaSourceWidthComparator())
 01116            .ToArray();
 1117        }
 1118
 1119        protected virtual IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
 1120        {
 01121            return Enumerable.Empty<(BaseItem, MediaSourceType)>();
 1122        }
 1123
 1124        private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
 1125        {
 01126            ArgumentNullException.ThrowIfNull(item);
 1127
 01128            var protocol = item.PathProtocol;
 1129
 1130            // Resolve the item path so everywhere we use the media source it will always point to
 1131            // the correct path even if symlinks are in use. Calling ResolveLinkTarget on a non-link
 1132            // path will return null, so it's safe to check for all paths.
 01133            var itemPath = item.Path;
 01134            if (protocol is MediaProtocol.File && FileSystemHelper.ResolveLinkTarget(itemPath, returnFinalTarget: true) 
 1135            {
 01136                itemPath = linkInfo.FullName;
 1137            }
 1138
 01139            var info = new MediaSourceInfo
 01140            {
 01141                Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
 01142                Protocol = protocol ?? MediaProtocol.File,
 01143                MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
 01144                MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
 01145                Name = GetMediaSourceName(item),
 01146                Path = enablePathSubstitution ? GetMappedPath(item, itemPath, protocol) : itemPath,
 01147                RunTimeTicks = item.RunTimeTicks,
 01148                Container = item.Container,
 01149                Size = item.Size,
 01150                Type = type,
 01151                HasSegments = MediaSegmentManager.IsTypeSupported(item)
 01152                    && (protocol is null or MediaProtocol.File)
 01153                    && MediaSegmentManager.HasSegments(item.Id)
 01154            };
 1155
 01156            if (string.IsNullOrEmpty(info.Path))
 1157            {
 01158                info.Type = MediaSourceType.Placeholder;
 1159            }
 1160
 01161            if (info.Protocol == MediaProtocol.File)
 1162            {
 01163                info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", Cultur
 1164            }
 1165
 01166            var video = item as Video;
 01167            if (video is not null)
 1168            {
 01169                info.IsoType = video.IsoType;
 01170                info.VideoType = video.VideoType;
 01171                info.Video3DFormat = video.Video3DFormat;
 01172                info.Timestamp = video.Timestamp;
 1173
 01174                if (video.IsShortcut)
 1175                {
 01176                    info.IsRemote = true;
 01177                    info.Path = video.ShortcutPath;
 01178                    info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
 1179                }
 1180
 01181                if (string.IsNullOrEmpty(info.Container))
 1182                {
 01183                    if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
 1184                    {
 01185                        if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1186                        {
 01187                            info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1188                        }
 1189                    }
 1190                }
 1191            }
 1192
 01193            if (string.IsNullOrEmpty(info.Container))
 1194            {
 01195                if (protocol.HasValue && protocol.Value == MediaProtocol.File)
 1196                {
 01197                    info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
 1198                }
 1199            }
 1200
 01201            if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
 1202            {
 01203                info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
 1204            }
 1205
 01206            if (video is not null && video.VideoType != VideoType.VideoFile)
 1207            {
 01208                info.SupportsDirectStream = false;
 1209            }
 1210
 01211            info.Bitrate = item.TotalBitrate;
 01212            info.InferTotalBitrate();
 1213
 01214            return info;
 1215        }
 1216
 1217        internal string GetMediaSourceName(BaseItem item)
 1218        {
 41219            var terms = new List<string>();
 1220
 41221            var path = item.Path;
 41222            if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
 1223            {
 41224                var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
 41225                if (HasLocalAlternateVersions)
 1226                {
 41227                    var containingFolderName = System.IO.Path.GetFileName(ContainingFolderPath);
 41228                    if (displayName.Length > containingFolderName.Length && displayName.StartsWith(containingFolderName,
 1229                    {
 21230                        var name = displayName.AsSpan(containingFolderName.Length).TrimStart([' ', '-']);
 21231                        if (!name.IsWhiteSpace())
 1232                        {
 21233                            terms.Add(name.ToString());
 1234                        }
 1235                    }
 1236                }
 1237
 41238                if (terms.Count == 0)
 1239                {
 21240                    terms.Add(displayName);
 1241                }
 1242            }
 1243
 41244            if (terms.Count == 0)
 1245            {
 01246                terms.Add(item.Name);
 1247            }
 1248
 41249            if (item is Video video)
 1250            {
 41251                if (video.Video3DFormat.HasValue)
 1252                {
 01253                    terms.Add("3D");
 1254                }
 1255
 41256                if (video.VideoType == VideoType.BluRay)
 1257                {
 01258                    terms.Add("Bluray");
 1259                }
 41260                else if (video.VideoType == VideoType.Dvd)
 1261                {
 01262                    terms.Add("DVD");
 1263                }
 41264                else if (video.VideoType == VideoType.Iso)
 1265                {
 01266                    if (video.IsoType.HasValue)
 1267                    {
 01268                        if (video.IsoType.Value == IsoType.BluRay)
 1269                        {
 01270                            terms.Add("Bluray");
 1271                        }
 01272                        else if (video.IsoType.Value == IsoType.Dvd)
 1273                        {
 01274                            terms.Add("DVD");
 1275                        }
 1276                    }
 1277                    else
 1278                    {
 01279                        terms.Add("ISO");
 1280                    }
 1281                }
 1282            }
 1283
 41284            return string.Join('/', terms);
 1285        }
 1286
 1287        public Task RefreshMetadata(CancellationToken cancellationToken)
 1288        {
 501289            return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
 1290        }
 1291
 1292        /// <summary>
 1293        /// The base implementation to refresh metadata.
 1294        /// </summary>
 1295        /// <param name="options">The options.</param>
 1296        /// <param name="cancellationToken">The cancellation token.</param>
 1297        /// <returns>true if a provider reports we changed.</returns>
 1298        public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellation
 1299        {
 1300            var requiresSave = false;
 1301
 1302            if (SupportsOwnedItems)
 1303            {
 1304                try
 1305                {
 1306                    if (IsFileProtocol)
 1307                    {
 1308                        requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService
 1309                    }
 1310
 1311                    await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties i
 1312                }
 1313                catch (Exception ex)
 1314                {
 1315                    Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
 1316                }
 1317            }
 1318
 1319            var refreshOptions = requiresSave
 1320                ? new MetadataRefreshOptions(options)
 1321                {
 1322                    ForceSave = true
 1323                }
 1324                : options;
 1325
 1326            return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false
 1327        }
 1328
 1329        protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
 1330        {
 01331            if (!IsVisible(user))
 1332            {
 01333                return false;
 1334            }
 1335
 01336            if (GetParents().Any(i => !i.IsVisible(user, true)))
 1337            {
 01338                return false;
 1339            }
 1340
 01341            if (checkFolders)
 1342            {
 01343                var topParent = GetParents().LastOrDefault() ?? this;
 1344
 01345                if (string.IsNullOrEmpty(topParent.Path))
 1346                {
 01347                    return true;
 1348                }
 1349
 01350                var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
 1351
 01352                if (itemCollectionFolders.Count > 0)
 1353                {
 01354                    var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i
 01355                    if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
 1356                    {
 01357                        return false;
 1358                    }
 1359                }
 1360            }
 1361
 01362            return true;
 1363        }
 1364
 1365        public void SetParent(Folder parent)
 1366        {
 101367            ParentId = parent is null ? Guid.Empty : parent.Id;
 101368        }
 1369
 1370        /// <summary>
 1371        /// Refreshes owned items such as trailers, theme videos, special features, etc.
 1372        /// Returns true or false indicating if changes were found.
 1373        /// </summary>
 1374        /// <param name="options">The metadata refresh options.</param>
 1375        /// <param name="fileSystemChildren">The list of filesystem children.</param>
 1376        /// <param name="cancellationToken">The cancellation token.</param>
 1377        /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
 1378        protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemM
 1379        {
 1380            if (!IsFileProtocol || !SupportsOwnedItems || IsInMixedFolder || this is ICollectionFolder or UserRootFolder
 1381            {
 1382                return false;
 1383            }
 1384
 1385            return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
 1386        }
 1387
 1388        protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
 1389        {
 411390            return directoryService.GetFileSystemEntries(ContainingFolderPath);
 1391        }
 1392
 1393        private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMe
 1394        {
 1395            var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
 1396            var newExtraIds = Array.ConvertAll(extras, x => x.Id);
 1397            var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
 1398
 1399            if (!extrasChanged && !options.ReplaceAllMetadata && options.MetadataRefreshMode != MetadataRefreshMode.Full
 1400            {
 1401                return false;
 1402            }
 1403
 1404            var ownerId = item.Id;
 1405
 1406            var tasks = extras.Select(i =>
 1407            {
 1408                var subOptions = new MetadataRefreshOptions(options);
 1409                if (!i.OwnerId.Equals(ownerId) || !i.ParentId.IsEmpty())
 1410                {
 1411                    i.OwnerId = ownerId;
 1412                    i.ParentId = Guid.Empty;
 1413                    subOptions.ForceSave = true;
 1414                }
 1415
 1416                return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
 1417            });
 1418
 1419            // Cleanup removed extras
 1420            var removedExtraIds = item.ExtraIds.Where(e => !newExtraIds.Contains(e)).ToArray();
 1421            if (removedExtraIds.Length > 0)
 1422            {
 1423                var removedExtras = LibraryManager.GetItemList(new InternalItemsQuery()
 1424                {
 1425                    ItemIds = removedExtraIds
 1426                });
 1427                foreach (var removedExtra in removedExtras)
 1428                {
 1429                    LibraryManager.DeleteItem(removedExtra, new DeleteOptions()
 1430                    {
 1431                        DeleteFileLocation = false
 1432                    });
 1433                }
 1434            }
 1435
 1436            await Task.WhenAll(tasks).ConfigureAwait(false);
 1437
 1438            item.ExtraIds = newExtraIds;
 1439
 1440            return true;
 1441        }
 1442
 1443        public string GetPresentationUniqueKey()
 1444        {
 01445            return PresentationUniqueKey ?? CreatePresentationUniqueKey();
 1446        }
 1447
 1448        public virtual bool RequiresRefresh()
 1449        {
 571450            if (string.IsNullOrEmpty(Path) || DateModified == DateTime.MinValue)
 1451            {
 571452                return false;
 1453            }
 1454
 01455            var info = FileSystem.GetFileSystemInfo(Path);
 1456
 01457            return info.Exists && this.HasChanged(info.LastWriteTimeUtc);
 1458        }
 1459
 1460        public virtual List<string> GetUserDataKeys()
 1461        {
 1501462            var list = new List<string>();
 1463
 1501464            if (SourceType == SourceType.Channel)
 1465            {
 01466                if (!string.IsNullOrEmpty(ExternalId))
 1467                {
 01468                    list.Add(ExternalId);
 1469                }
 1470            }
 1471
 1501472            list.Add(Id.ToString());
 1501473            return list;
 1474        }
 1475
 1476        internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
 1477        {
 61478            var updateType = ItemUpdateType.None;
 1479
 61480            if (IsInMixedFolder != newItem.IsInMixedFolder)
 1481            {
 01482                IsInMixedFolder = newItem.IsInMixedFolder;
 01483                updateType |= ItemUpdateType.MetadataImport;
 1484            }
 1485
 61486            return updateType;
 1487        }
 1488
 1489        public void AfterMetadataRefresh()
 1490        {
 551491            _sortName = null;
 551492        }
 1493
 1494        /// <summary>
 1495        /// Gets the preferred metadata language.
 1496        /// </summary>
 1497        /// <returns>System.String.</returns>
 1498        public string GetPreferredMetadataLanguage()
 1499        {
 341500            string lang = PreferredMetadataLanguage;
 1501
 341502            if (string.IsNullOrEmpty(lang))
 1503            {
 341504                lang = GetParents()
 341505                    .Select(i => i.PreferredMetadataLanguage)
 341506                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1507            }
 1508
 341509            if (string.IsNullOrEmpty(lang))
 1510            {
 341511                lang = LibraryManager.GetCollectionFolders(this)
 341512                    .Select(i => i.PreferredMetadataLanguage)
 341513                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1514            }
 1515
 341516            if (string.IsNullOrEmpty(lang))
 1517            {
 341518                lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
 1519            }
 1520
 341521            if (string.IsNullOrEmpty(lang))
 1522            {
 341523                lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
 1524            }
 1525
 341526            return lang;
 1527        }
 1528
 1529        /// <summary>
 1530        /// Gets the preferred metadata language.
 1531        /// </summary>
 1532        /// <returns>System.String.</returns>
 1533        public string GetPreferredMetadataCountryCode()
 1534        {
 341535            string lang = PreferredMetadataCountryCode;
 1536
 341537            if (string.IsNullOrEmpty(lang))
 1538            {
 341539                lang = GetParents()
 341540                    .Select(i => i.PreferredMetadataCountryCode)
 341541                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1542            }
 1543
 341544            if (string.IsNullOrEmpty(lang))
 1545            {
 341546                lang = LibraryManager.GetCollectionFolders(this)
 341547                    .Select(i => i.PreferredMetadataCountryCode)
 341548                    .FirstOrDefault(i => !string.IsNullOrEmpty(i));
 1549            }
 1550
 341551            if (string.IsNullOrEmpty(lang))
 1552            {
 341553                lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
 1554            }
 1555
 341556            if (string.IsNullOrEmpty(lang))
 1557            {
 341558                lang = ConfigurationManager.Configuration.MetadataCountryCode;
 1559            }
 1560
 341561            return lang;
 1562        }
 1563
 1564        public virtual bool IsSaveLocalMetadataEnabled()
 1565        {
 861566            if (SourceType == SourceType.Channel)
 1567            {
 01568                return false;
 1569            }
 1570
 861571            var libraryOptions = LibraryManager.GetLibraryOptions(this);
 1572
 861573            return libraryOptions.SaveLocalMetadata;
 1574        }
 1575
 1576        /// <summary>
 1577        /// Determines if a given user has access to this item.
 1578        /// </summary>
 1579        /// <param name="user">The user.</param>
 1580        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 1581        /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
 1582        /// <exception cref="ArgumentNullException">If user is null.</exception>
 1583        public bool IsParentalAllowed(User user, bool skipAllowedTagsCheck)
 1584        {
 131585            ArgumentNullException.ThrowIfNull(user);
 1586
 131587            if (!IsVisibleViaTags(user, skipAllowedTagsCheck))
 1588            {
 01589                return false;
 1590            }
 1591
 131592            var maxAllowedRating = user.MaxParentalRatingScore;
 131593            var maxAllowedSubRating = user.MaxParentalRatingSubScore;
 131594            var rating = CustomRatingForComparison;
 1595
 131596            if (string.IsNullOrEmpty(rating))
 1597            {
 131598                rating = OfficialRatingForComparison;
 1599            }
 1600
 131601            if (string.IsNullOrEmpty(rating))
 1602            {
 131603                Logger.LogDebug("{0} has no parental rating set.", Name);
 131604                return !GetBlockUnratedValue(user);
 1605            }
 1606
 01607            var ratingScore = LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1608
 1609            // Could not determine rating level
 01610            if (ratingScore is null)
 1611            {
 01612                var isAllowed = !GetBlockUnratedValue(user);
 1613
 01614                if (!isAllowed)
 1615                {
 01616                    Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
 1617                }
 1618
 01619                return isAllowed;
 1620            }
 1621
 01622            if (!maxAllowedRating.HasValue)
 1623            {
 01624                return true;
 1625            }
 1626
 01627            if (ratingScore.Score != maxAllowedRating.Value)
 1628            {
 01629                return ratingScore.Score < maxAllowedRating.Value;
 1630            }
 1631
 01632            return !maxAllowedSubRating.HasValue || (ratingScore.SubScore ?? 0) <= maxAllowedSubRating.Value;
 1633        }
 1634
 1635        public ParentalRatingScore GetParentalRatingScore()
 1636        {
 1141637            var rating = CustomRatingForComparison;
 1638
 1141639            if (string.IsNullOrEmpty(rating))
 1640            {
 1141641                rating = OfficialRatingForComparison;
 1642            }
 1643
 1141644            if (string.IsNullOrEmpty(rating))
 1645            {
 1141646                return null;
 1647            }
 1648
 01649            return LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode());
 1650        }
 1651
 1652        public List<string> GetInheritedTags()
 1653        {
 1231654            var list = new List<string>();
 1231655            list.AddRange(Tags);
 1656
 3261657            foreach (var parent in GetParents())
 1658            {
 401659                list.AddRange(parent.Tags);
 1660            }
 1661
 2461662            foreach (var folder in LibraryManager.GetCollectionFolders(this))
 1663            {
 01664                list.AddRange(folder.Tags);
 1665            }
 1666
 1231667            return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
 1668        }
 1669
 1670        private bool IsVisibleViaTags(User user, bool skipAllowedTagsCheck)
 1671        {
 131672            var allTags = GetInheritedTags();
 131673            if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => allTags.Contains(i, StringComparison.OrdinalIgno
 1674            {
 01675                return false;
 1676            }
 1677
 131678            var parent = GetParents().FirstOrDefault() ?? this;
 131679            if (parent is UserRootFolder or AggregateFolder or UserView)
 1680            {
 131681                return true;
 1682            }
 1683
 01684            var allowedTagsPreference = user.GetPreference(PreferenceKind.AllowedTags);
 01685            if (!skipAllowedTagsCheck && allowedTagsPreference.Length != 0 && !allowedTagsPreference.Any(i => allTags.Co
 1686            {
 01687                return false;
 1688            }
 1689
 01690            return true;
 1691        }
 1692
 1693        public virtual UnratedItem GetBlockUnratedType()
 1694        {
 1101695            if (SourceType == SourceType.Channel)
 1696            {
 01697                return UnratedItem.ChannelContent;
 1698            }
 1699
 1101700            return UnratedItem.Other;
 1701        }
 1702
 1703        /// <summary>
 1704        /// Gets a bool indicating if access to the unrated item is blocked or not.
 1705        /// </summary>
 1706        /// <param name="user">The configuration.</param>
 1707        /// <returns><c>true</c> if blocked, <c>false</c> otherwise.</returns>
 1708        protected virtual bool GetBlockUnratedValue(User user)
 1709        {
 1710            // Don't block plain folders that are unrated. Let the media underneath get blocked
 1711            // Special folders like series and albums will override this method.
 131712            if (IsFolder || this is IItemByName)
 1713            {
 131714                return false;
 1715            }
 1716
 01717            return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType(
 1718        }
 1719
 1720        /// <summary>
 1721        /// Determines if this folder should be visible to a given user.
 1722        /// Default is just parental allowed. Can be overridden for more functionality.
 1723        /// </summary>
 1724        /// <param name="user">The user.</param>
 1725        /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
 1726        /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
 1727        /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
 1728        public virtual bool IsVisible(User user, bool skipAllowedTagsCheck = false)
 1729        {
 131730            ArgumentNullException.ThrowIfNull(user);
 1731
 131732            return IsParentalAllowed(user, skipAllowedTagsCheck);
 1733        }
 1734
 1735        public virtual bool IsVisibleStandalone(User user)
 1736        {
 01737            if (SourceType == SourceType.Channel)
 1738            {
 01739                return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
 1740            }
 1741
 01742            return IsVisibleStandaloneInternal(user, true);
 1743        }
 1744
 1745        public virtual string GetClientTypeName()
 1746        {
 1101747            if (IsFolder && SourceType == SourceType.Channel && this is not Channel && this is not Season && this is not
 1748            {
 01749                return "ChannelFolderItem";
 1750            }
 1751
 1101752            return GetType().Name;
 1753        }
 1754
 1755        public BaseItemKind GetBaseItemKind()
 1756        {
 2401757            return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
 1758        }
 1759
 1760        /// <summary>
 1761        /// Gets the linked child.
 1762        /// </summary>
 1763        /// <param name="info">The info.</param>
 1764        /// <returns>BaseItem.</returns>
 1765        protected BaseItem GetLinkedChild(LinkedChild info)
 1766        {
 1767            // First get using the cached Id
 01768            if (info.ItemId.HasValue)
 1769            {
 01770                if (info.ItemId.Value.IsEmpty())
 1771                {
 01772                    return null;
 1773                }
 1774
 01775                var itemById = LibraryManager.GetItemById(info.ItemId.Value);
 1776
 01777                if (itemById is not null)
 1778                {
 01779                    return itemById;
 1780                }
 1781            }
 1782
 01783            var item = FindLinkedChild(info);
 1784
 1785            // If still null, log
 01786            if (item is null)
 1787            {
 1788                // Don't keep searching over and over
 01789                info.ItemId = Guid.Empty;
 1790            }
 1791            else
 1792            {
 1793                // Cache the id for next time
 01794                info.ItemId = item.Id;
 1795            }
 1796
 01797            return item;
 1798        }
 1799
 1800        private BaseItem FindLinkedChild(LinkedChild info)
 1801        {
 01802            var path = info.Path;
 1803
 01804            if (!string.IsNullOrEmpty(path))
 1805            {
 01806                path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
 1807
 01808                var itemByPath = LibraryManager.FindByPath(path, null);
 1809
 01810                if (itemByPath is null)
 1811                {
 01812                    Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
 1813                }
 1814
 01815                return itemByPath;
 1816            }
 1817
 01818            if (!string.IsNullOrEmpty(info.LibraryItemId))
 1819            {
 01820                var item = LibraryManager.GetItemById(info.LibraryItemId);
 1821
 01822                if (item is null)
 1823                {
 01824                    Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
 1825                }
 1826
 01827                return item;
 1828            }
 1829
 01830            return null;
 1831        }
 1832
 1833        /// <summary>
 1834        /// Adds a studio to the item.
 1835        /// </summary>
 1836        /// <param name="name">The name.</param>
 1837        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 1838        public void AddStudio(string name)
 1839        {
 41840            ArgumentException.ThrowIfNullOrEmpty(name);
 41841            var current = Studios;
 1842
 41843            if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
 1844            {
 41845                int curLen = current.Length;
 41846                if (curLen == 0)
 1847                {
 41848                    Studios = [name];
 1849                }
 1850                else
 1851                {
 01852                    Studios = [.. current, name];
 1853                }
 1854            }
 01855        }
 1856
 1857        public void SetStudios(IEnumerable<string> names)
 1858        {
 01859            Studios = names.Trimmed().Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
 01860        }
 1861
 1862        /// <summary>
 1863        /// Adds a genre to the item.
 1864        /// </summary>
 1865        /// <param name="name">The name.</param>
 1866        /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
 1867        public void AddGenre(string name)
 1868        {
 131869            ArgumentException.ThrowIfNullOrEmpty(name);
 1870
 131871            var genres = Genres;
 131872            if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
 1873            {
 131874                Genres = [.. genres, name];
 1875            }
 131876        }
 1877
 1878        /// <summary>
 1879        /// Marks the played.
 1880        /// </summary>
 1881        /// <param name="user">The user.</param>
 1882        /// <param name="datePlayed">The date played.</param>
 1883        /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
 1884        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 1885        public virtual void MarkPlayed(
 1886            User user,
 1887            DateTime? datePlayed,
 1888            bool resetPosition)
 1889        {
 01890            ArgumentNullException.ThrowIfNull(user);
 1891
 01892            var data = UserDataManager.GetUserData(user, this) ?? new UserItemData()
 01893            {
 01894                Key = GetUserDataKeys().First(),
 01895            };
 1896
 01897            if (datePlayed.HasValue)
 1898            {
 1899                // Increment
 01900                data.PlayCount++;
 1901            }
 1902
 1903            // Ensure it's at least one
 01904            data.PlayCount = Math.Max(data.PlayCount, 1);
 1905
 01906            if (resetPosition)
 1907            {
 01908                data.PlaybackPositionTicks = 0;
 1909            }
 1910
 01911            data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
 01912            data.Played = true;
 1913
 01914            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 01915        }
 1916
 1917        /// <summary>
 1918        /// Marks the unplayed.
 1919        /// </summary>
 1920        /// <param name="user">The user.</param>
 1921        /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
 1922        public virtual void MarkUnplayed(User user)
 1923        {
 01924            ArgumentNullException.ThrowIfNull(user);
 1925
 01926            var data = UserDataManager.GetUserData(user, this);
 1927
 1928            // I think it is okay to do this here.
 1929            // if this is only called when a user is manually forcing something to un-played
 1930            // then it probably is what we want to do...
 01931            data.PlayCount = 0;
 01932            data.PlaybackPositionTicks = 0;
 01933            data.LastPlayedDate = null;
 01934            data.Played = false;
 1935
 01936            UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
 01937        }
 1938
 1939        /// <summary>
 1940        /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
 1941        /// </summary>
 1942        public virtual void ChangedExternally()
 1943        {
 01944            ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriori
 01945        }
 1946
 1947        /// <summary>
 1948        /// Gets an image.
 1949        /// </summary>
 1950        /// <param name="type">The type.</param>
 1951        /// <param name="imageIndex">Index of the image.</param>
 1952        /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
 1953        /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
 1954        public bool HasImage(ImageType type, int imageIndex)
 1955        {
 1431956            return GetImageInfo(type, imageIndex) is not null;
 1957        }
 1958
 1959        public void SetImage(ItemImageInfo image, int index)
 1960        {
 131961            if (image.Type == ImageType.Chapter)
 1962            {
 01963                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 1964            }
 1965
 131966            var existingImage = GetImageInfo(image.Type, index);
 1967
 131968            if (existingImage is null)
 1969            {
 111970                AddImage(image);
 1971            }
 1972            else
 1973            {
 21974                existingImage.Path = image.Path;
 21975                existingImage.DateModified = image.DateModified;
 21976                existingImage.Width = image.Width;
 21977                existingImage.Height = image.Height;
 21978                existingImage.BlurHash = image.BlurHash;
 1979            }
 21980        }
 1981
 1982        public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
 1983        {
 461984            if (type == ImageType.Chapter)
 1985            {
 01986                throw new ArgumentException("Cannot set chapter images using SetImagePath");
 1987            }
 1988
 461989            var image = GetImageInfo(type, index);
 1990
 461991            if (image is null)
 1992            {
 451993                AddImage(GetImageInfo(file, type));
 1994            }
 1995            else
 1996            {
 11997                var imageInfo = GetImageInfo(file, type);
 1998
 11999                image.Path = file.FullName;
 12000                image.DateModified = imageInfo.DateModified;
 2001
 2002                // reset these values
 12003                image.Width = 0;
 12004                image.Height = 0;
 2005            }
 12006        }
 2007
 2008        /// <summary>
 2009        /// Deletes the image.
 2010        /// </summary>
 2011        /// <param name="type">The type.</param>
 2012        /// <param name="index">The index.</param>
 2013        /// <returns>A task.</returns>
 2014        public async Task DeleteImageAsync(ImageType type, int index)
 2015        {
 2016            var info = GetImageInfo(type, index);
 2017
 2018            if (info is null)
 2019            {
 2020                // Nothing to do
 2021                return;
 2022            }
 2023
 2024            // Remove from file system
 2025            var path = info.Path;
 2026            if (info.IsLocalFile && !string.IsNullOrWhiteSpace(path))
 2027            {
 2028                FileSystem.DeleteFile(path);
 2029            }
 2030
 2031            // Remove from item
 2032            RemoveImage(info);
 2033
 2034            await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
 2035        }
 2036
 2037        public void RemoveImage(ItemImageInfo image)
 2038        {
 02039            RemoveImages([image]);
 02040        }
 2041
 2042        public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
 2043        {
 92044            ImageInfos = ImageInfos.Except(deletedImages).ToArray();
 92045        }
 2046
 2047        public void AddImage(ItemImageInfo image)
 2048        {
 562049            ImageInfos = [.. ImageInfos, image];
 562050        }
 2051
 2052        public virtual async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationTok
 2053         => await LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken).ConfigureAwait(fals
 2054
 2055        public async Task ReattachUserDataAsync(CancellationToken cancellationToken) =>
 2056            await LibraryManager.ReattachUserDataAsync(this, cancellationToken).ConfigureAwait(false);
 2057
 2058        /// <summary>
 2059        /// Validates that images within the item are still on the filesystem.
 2060        /// </summary>
 2061        /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
 2062        public bool ValidateImages()
 2063        {
 712064            List<ItemImageInfo> deletedImages = null;
 1722065            foreach (var imageInfo in ImageInfos)
 2066            {
 152067                if (!imageInfo.IsLocalFile)
 2068                {
 2069                    continue;
 2070                }
 2071
 152072                if (File.Exists(imageInfo.Path))
 2073                {
 2074                    continue;
 2075                }
 2076
 32077                (deletedImages ??= []).Add(imageInfo);
 2078            }
 2079
 712080            var anyImagesRemoved = deletedImages?.Count > 0;
 712081            if (anyImagesRemoved)
 2082            {
 22083                RemoveImages(deletedImages);
 2084            }
 2085
 712086            return anyImagesRemoved;
 2087        }
 2088
 2089        /// <summary>
 2090        /// Gets the image path.
 2091        /// </summary>
 2092        /// <param name="imageType">Type of the image.</param>
 2093        /// <param name="imageIndex">Index of the image.</param>
 2094        /// <returns>System.String.</returns>
 2095        /// <exception cref="ArgumentNullException">Item is null.</exception>
 2096        public string GetImagePath(ImageType imageType, int imageIndex)
 22097            => GetImageInfo(imageType, imageIndex)?.Path;
 2098
 2099        /// <summary>
 2100        /// Gets the image information.
 2101        /// </summary>
 2102        /// <param name="imageType">Type of the image.</param>
 2103        /// <param name="imageIndex">Index of the image.</param>
 2104        /// <returns>ItemImageInfo.</returns>
 2105        public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
 2106        {
 2982107            if (imageType == ImageType.Chapter)
 2108            {
 02109                var chapter = ChapterManager.GetChapter(Id, imageIndex);
 2110
 02111                if (chapter is null)
 2112                {
 02113                    return null;
 2114                }
 2115
 02116                var path = chapter.ImagePath;
 2117
 02118                if (string.IsNullOrEmpty(path))
 2119                {
 02120                    return null;
 2121                }
 2122
 02123                return new ItemImageInfo
 02124                {
 02125                    Path = path,
 02126                    DateModified = chapter.ImageDateModified,
 02127                    Type = imageType
 02128                };
 2129            }
 2130
 2982131            return GetImages(imageType)
 2982132                .ElementAtOrDefault(imageIndex);
 2133        }
 2134
 2135        /// <summary>
 2136        /// Computes image index for given image or raises if no matching image found.
 2137        /// </summary>
 2138        /// <param name="image">Image to compute index for.</param>
 2139        /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
 2140        /// </exception>
 2141        /// <returns>Image index.</returns>
 2142        public int GetImageIndex(ItemImageInfo image)
 2143        {
 02144            ArgumentNullException.ThrowIfNull(image);
 2145
 02146            if (image.Type == ImageType.Chapter)
 2147            {
 02148                var chapters = ChapterManager.GetChapters(Id);
 02149                for (var i = 0; i < chapters.Count; i++)
 2150                {
 02151                    if (chapters[i].ImagePath == image.Path)
 2152                    {
 02153                        return i;
 2154                    }
 2155                }
 2156
 02157                throw new ArgumentException("No chapter index found for image path", image.Path);
 2158            }
 2159
 02160            var images = GetImages(image.Type).ToArray();
 02161            for (var i = 0; i < images.Length; i++)
 2162            {
 02163                if (images[i].Path == image.Path)
 2164                {
 02165                    return i;
 2166                }
 2167            }
 2168
 02169            throw new ArgumentException("No image index found for image path", image.Path);
 2170        }
 2171
 2172        public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
 2173        {
 2174            if (imageType == ImageType.Chapter)
 2175            {
 2176                throw new ArgumentException("No image info for chapter images");
 2177            }
 2178
 2179            // Yield return is more performant than LINQ Where on an Array
 2180            for (var i = 0; i < ImageInfos.Length; i++)
 2181            {
 2182                var imageInfo = ImageInfos[i];
 2183                if (imageInfo.Type == imageType)
 2184                {
 2185                    yield return imageInfo;
 2186                }
 2187            }
 2188        }
 2189
 2190        /// <summary>
 2191        /// Adds the images, updating metadata if they already are part of this item.
 2192        /// </summary>
 2193        /// <param name="imageType">Type of the image.</param>
 2194        /// <param name="images">The images.</param>
 2195        /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
 2196        /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
 2197        public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
 2198        {
 42199            if (imageType == ImageType.Chapter)
 2200            {
 02201                throw new ArgumentException("Cannot call AddImages with chapter images");
 2202            }
 2203
 42204            var existingImages = GetImages(imageType)
 42205                .ToList();
 2206
 42207            var newImageList = new List<FileSystemMetadata>();
 42208            var imageUpdated = false;
 2209
 242210            foreach (var newImage in images)
 2211            {
 82212                if (newImage is null)
 2213                {
 02214                    throw new ArgumentException("null image found in list");
 2215                }
 2216
 82217                var existing = existingImages
 82218                    .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
 2219
 82220                if (existing is null)
 2221                {
 42222                    newImageList.Add(newImage);
 2223                }
 2224                else
 2225                {
 42226                    if (existing.IsLocalFile)
 2227                    {
 42228                        var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
 2229
 2230                        // If date changed then we need to reset saved image dimensions
 42231                        if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
 2232                        {
 22233                            existing.Width = 0;
 22234                            existing.Height = 0;
 22235                            imageUpdated = true;
 2236                        }
 2237
 42238                        existing.DateModified = newDateModified;
 2239                    }
 2240                }
 2241            }
 2242
 42243            if (newImageList.Count > 0)
 2244            {
 22245                ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
 2246            }
 2247
 42248            return imageUpdated || newImageList.Count > 0;
 2249        }
 2250
 2251        private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
 2252        {
 502253            return new ItemImageInfo
 502254            {
 502255                Path = file.FullName,
 502256                Type = type,
 502257                DateModified = FileSystem.GetLastWriteTimeUtc(file)
 502258            };
 2259        }
 2260
 2261        /// <summary>
 2262        /// Gets the file system path to delete when the item is to be deleted.
 2263        /// </summary>
 2264        /// <returns>The metadata for the deleted paths.</returns>
 2265        public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
 2266        {
 02267            return new[]
 02268            {
 02269                FileSystem.GetFileSystemInfo(Path)
 02270            }.Concat(GetLocalMetadataFilesToDelete());
 2271        }
 2272
 2273        protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
 2274        {
 02275            if (IsFolder || !IsInMixedFolder)
 2276            {
 02277                return [];
 2278            }
 2279
 02280            var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
 2281
 02282            return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
 02283                .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison
 02284                .ToList();
 2285        }
 2286
 2287        public bool AllowsMultipleImages(ImageType type)
 2288        {
 182289            return type == ImageType.Backdrop || type == ImageType.Chapter;
 2290        }
 2291
 2292        public Task SwapImagesAsync(ImageType type, int index1, int index2)
 2293        {
 02294            if (!AllowsMultipleImages(type))
 2295            {
 02296                throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots
 2297            }
 2298
 02299            var info1 = GetImageInfo(type, index1);
 02300            var info2 = GetImageInfo(type, index2);
 2301
 02302            if (info1 is null || info2 is null)
 2303            {
 2304                // Nothing to do
 02305                return Task.CompletedTask;
 2306            }
 2307
 02308            if (!info1.IsLocalFile || !info2.IsLocalFile)
 2309            {
 2310                // TODO: Not supported  yet
 02311                return Task.CompletedTask;
 2312            }
 2313
 02314            var path1 = info1.Path;
 02315            var path2 = info2.Path;
 2316
 02317            FileSystem.SwapFiles(path1, path2);
 2318
 2319            // Refresh these values
 02320            info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
 02321            info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
 2322
 02323            info1.Width = 0;
 02324            info1.Height = 0;
 02325            info2.Width = 0;
 02326            info2.Height = 0;
 2327
 02328            return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
 2329        }
 2330
 2331        public virtual bool IsPlayed(User user, UserItemData userItemData)
 2332        {
 02333            userItemData ??= UserDataManager.GetUserData(user, this);
 2334
 02335            return userItemData is not null && userItemData.Played;
 2336        }
 2337
 2338        public bool IsFavoriteOrLiked(User user, UserItemData userItemData)
 2339        {
 02340            userItemData ??= UserDataManager.GetUserData(user, this);
 2341
 02342            return userItemData is not null && (userItemData.IsFavorite || (userItemData.Likes ?? false));
 2343        }
 2344
 2345        public virtual bool IsUnplayed(User user, UserItemData userItemData)
 2346        {
 02347            ArgumentNullException.ThrowIfNull(user);
 2348
 02349            userItemData ??= UserDataManager.GetUserData(user, this);
 2350
 02351            return userItemData is null || !userItemData.Played;
 2352        }
 2353
 2354        ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
 2355        {
 342356            return GetItemLookupInfo<ItemLookupInfo>();
 2357        }
 2358
 2359        protected T GetItemLookupInfo<T>()
 2360            where T : ItemLookupInfo, new()
 2361        {
 342362            return new T
 342363            {
 342364                Path = Path,
 342365                MetadataCountryCode = GetPreferredMetadataCountryCode(),
 342366                MetadataLanguage = GetPreferredMetadataLanguage(),
 342367                Name = GetNameForMetadataLookup(),
 342368                OriginalTitle = OriginalTitle,
 342369                ProviderIds = ProviderIds,
 342370                IndexNumber = IndexNumber,
 342371                ParentIndexNumber = ParentIndexNumber,
 342372                Year = ProductionYear,
 342373                PremiereDate = PremiereDate
 342374            };
 2375        }
 2376
 2377        protected virtual string GetNameForMetadataLookup()
 2378        {
 342379            return Name;
 2380        }
 2381
 2382        /// <summary>
 2383        /// This is called before any metadata refresh and returns true if changes were made.
 2384        /// </summary>
 2385        /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
 2386        /// <returns>true if the item has change, else false.</returns>
 2387        public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
 2388        {
 342389            _sortName = null;
 2390
 342391            var hasChanges = false;
 2392
 342393            if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
 2394            {
 02395                Name = System.IO.Path.GetFileNameWithoutExtension(Path);
 02396                hasChanges = true;
 2397            }
 2398
 342399            return hasChanges;
 2400        }
 2401
 2402        protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
 2403        {
 02404            if (protocol == MediaProtocol.File)
 2405            {
 02406                return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
 2407            }
 2408
 02409            return path;
 2410        }
 2411
 2412        public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User 
 2413        {
 02414            if (RunTimeTicks.HasValue)
 2415            {
 02416                double pct = RunTimeTicks.Value;
 2417
 02418                if (pct > 0)
 2419                {
 02420                    pct = userData.PlaybackPositionTicks / pct;
 2421
 02422                    if (pct > 0)
 2423                    {
 02424                        dto.PlayedPercentage = 100 * pct;
 2425                    }
 2426                }
 2427            }
 02428        }
 2429
 2430        protected async Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOpti
 2431        {
 2432            var newOptions = new MetadataRefreshOptions(options)
 2433            {
 2434                SearchResult = null
 2435            };
 2436
 2437            var item = this;
 2438
 2439            if (copyTitleMetadata)
 2440            {
 2441                // Take some data from the main item, for querying purposes
 2442                if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
 2443                {
 2444                    newOptions.ForceSave = true;
 2445                    ownedItem.Genres = item.Genres;
 2446                }
 2447
 2448                if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
 2449                {
 2450                    newOptions.ForceSave = true;
 2451                    ownedItem.Studios = item.Studios;
 2452                }
 2453
 2454                if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
 2455                {
 2456                    newOptions.ForceSave = true;
 2457                    ownedItem.ProductionLocations = item.ProductionLocations;
 2458                }
 2459
 2460                if (item.CommunityRating != ownedItem.CommunityRating)
 2461                {
 2462                    ownedItem.CommunityRating = item.CommunityRating;
 2463                    newOptions.ForceSave = true;
 2464                }
 2465
 2466                if (item.CriticRating != ownedItem.CriticRating)
 2467                {
 2468                    ownedItem.CriticRating = item.CriticRating;
 2469                    newOptions.ForceSave = true;
 2470                }
 2471
 2472                if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
 2473                {
 2474                    ownedItem.Overview = item.Overview;
 2475                    newOptions.ForceSave = true;
 2476                }
 2477
 2478                if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
 2479                {
 2480                    ownedItem.OfficialRating = item.OfficialRating;
 2481                    newOptions.ForceSave = true;
 2482                }
 2483
 2484                if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
 2485                {
 2486                    ownedItem.CustomRating = item.CustomRating;
 2487                    newOptions.ForceSave = true;
 2488                }
 2489            }
 2490
 2491            await ownedItem.RefreshMetadata(newOptions, cancellationToken).ConfigureAwait(false);
 2492        }
 2493
 2494        protected async Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string
 2495        {
 2496            var newOptions = new MetadataRefreshOptions(options)
 2497            {
 2498                SearchResult = null
 2499            };
 2500
 2501            var id = LibraryManager.GetNewItemId(path, typeof(Video));
 2502
 2503            // Try to retrieve it from the db. If we don't find it, use the resolved version
 2504            if (LibraryManager.GetItemById(id) is not Video video)
 2505            {
 2506                video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
 2507
 2508                newOptions.ForceSave = true;
 2509            }
 2510
 2511            if (video is null)
 2512            {
 2513                return;
 2514            }
 2515
 2516            if (video.OwnerId.IsEmpty())
 2517            {
 2518                video.OwnerId = Id;
 2519            }
 2520
 2521            await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(fa
 2522        }
 2523
 2524        public string GetEtag(User user)
 2525        {
 62526            var list = GetEtagValues(user);
 2527
 62528            return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
 2529        }
 2530
 2531        protected virtual List<string> GetEtagValues(User user)
 2532        {
 62533            return
 62534            [
 62535                DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
 62536            ];
 2537        }
 2538
 2539        public virtual IEnumerable<Guid> GetAncestorIds()
 2540        {
 1102541            return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
 2542        }
 2543
 2544        public BaseItem GetTopParent()
 2545        {
 1102546            if (IsTopParent)
 2547            {
 212548                return this;
 2549            }
 2550
 892551            return GetParents().FirstOrDefault(parent => parent.IsTopParent);
 2552        }
 2553
 2554        public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
 2555        {
 442556            return [Id];
 2557        }
 2558
 2559        public virtual double? GetRefreshProgress()
 2560        {
 02561            return null;
 2562        }
 2563
 2564        public virtual ItemUpdateType OnMetadataChanged()
 2565        {
 1142566            var updateType = ItemUpdateType.None;
 2567
 1142568            var item = this;
 2569
 1142570            var rating = item.GetParentalRatingScore();
 1142571            if (rating is not null)
 2572            {
 02573                if (rating.Score != item.InheritedParentalRatingValue)
 2574                {
 02575                    item.InheritedParentalRatingValue = rating.Score;
 02576                    updateType |= ItemUpdateType.MetadataImport;
 2577                }
 2578
 02579                if (rating.SubScore != item.InheritedParentalRatingSubValue)
 2580                {
 02581                    item.InheritedParentalRatingSubValue = rating.SubScore;
 02582                    updateType |= ItemUpdateType.MetadataImport;
 2583                }
 2584            }
 2585            else
 2586            {
 1142587                if (item.InheritedParentalRatingValue is not null)
 2588                {
 02589                    item.InheritedParentalRatingValue = null;
 02590                    item.InheritedParentalRatingSubValue = null;
 02591                    updateType |= ItemUpdateType.MetadataImport;
 2592                }
 2593            }
 2594
 1142595            return updateType;
 2596        }
 2597
 2598        /// <summary>
 2599        /// Updates the official rating based on content and returns true or false indicating if it changed.
 2600        /// </summary>
 2601        /// <param name="children">Media children.</param>
 2602        /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
 2603        public bool UpdateRatingToItems(IReadOnlyList<BaseItem> children)
 2604        {
 02605            var currentOfficialRating = OfficialRating;
 2606
 2607            // Gather all possible ratings
 02608            var ratings = children
 02609                .Select(i => i.OfficialRating)
 02610                .Where(i => !string.IsNullOrEmpty(i))
 02611                .Distinct(StringComparer.OrdinalIgnoreCase)
 02612                .Select(rating => (rating, LocalizationManager.GetRatingScore(rating, GetPreferredMetadataCountryCode())
 02613                .OrderBy(i => i.Item2 is null ? 1001 : i.Item2.Score)
 02614                .ThenBy(i => i.Item2 is null ? 1001 : i.Item2.SubScore)
 02615                .Select(i => i.rating);
 2616
 02617            OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
 2618
 02619            return !string.Equals(
 02620                currentOfficialRating ?? string.Empty,
 02621                OfficialRating ?? string.Empty,
 02622                StringComparison.OrdinalIgnoreCase);
 2623        }
 2624
 2625        public IReadOnlyList<BaseItem> GetThemeSongs(User user = null)
 2626        {
 02627            return GetThemeSongs(user, Array.Empty<(ItemSortBy, SortOrder)>());
 2628        }
 2629
 2630        public IReadOnlyList<BaseItem> GetThemeSongs(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> or
 2631        {
 02632            return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong), user, 
 2633        }
 2634
 2635        public IReadOnlyList<BaseItem> GetThemeVideos(User user = null)
 2636        {
 02637            return GetThemeVideos(user, Array.Empty<(ItemSortBy, SortOrder)>());
 2638        }
 2639
 2640        public IReadOnlyList<BaseItem> GetThemeVideos(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> o
 2641        {
 02642            return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo), user,
 2643        }
 2644
 2645        /// <summary>
 2646        /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
 2647        /// </summary>
 2648        /// <returns>An enumerable containing the items.</returns>
 2649        public IEnumerable<BaseItem> GetExtras()
 2650        {
 62651            return ExtraIds
 62652                .Select(LibraryManager.GetItemById)
 62653                .Where(i => i is not null)
 62654                .OrderBy(i => i.SortName);
 2655        }
 2656
 2657        /// <summary>
 2658        /// Get all extras with specific types that are associated with this item.
 2659        /// </summary>
 2660        /// <param name="extraTypes">The types of extras to retrieve.</param>
 2661        /// <returns>An enumerable containing the extras.</returns>
 2662        public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
 2663        {
 02664            return ExtraIds
 02665                .Select(LibraryManager.GetItemById)
 02666                .Where(i => i is not null)
 02667                .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value))
 02668                .OrderBy(i => i.SortName);
 2669        }
 2670
 2671        public virtual long GetRunTimeTicksForPlayState()
 2672        {
 02673            return RunTimeTicks ?? 0;
 2674        }
 2675
 2676        /// <inheritdoc />
 2677        public override bool Equals(object obj)
 2678        {
 02679            return obj is BaseItem baseItem && this.Equals(baseItem);
 2680        }
 2681
 2682        /// <inheritdoc />
 62683        public bool Equals(BaseItem other) => other is not null && other.Id.Equals(Id);
 2684
 2685        /// <inheritdoc />
 622686        public override int GetHashCode() => HashCode.Combine(Id);
 2687    }
 2688}

Methods/Properties

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