Skip to content

The Free Software Media System - Server Backend & API

Merge remote-tracking branch 'upstream/master' into perf-rebased

Shadowghostbcd5c33ecdc0
diff --cc Jellyfin.Server.Implementations/Item/BaseItemMapper.cs
index a879b07161,0000000000..831e7c3354
mode 100644,000000..100644
--- a/Jellyfin.Server.Implementations/Item/BaseItemMapper.cs
+++ b/Jellyfin.Server.Implementations/Item/BaseItemMapper.cs
@@@ -1,494 -1,0 +1,494 @@@
+#pragma warning disable RS0030 // Do not use banned APIs
+
+using System;
+using System.Collections.Concurrent;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Text.Json;
+using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Extensions;
+using Jellyfin.Extensions.Json;
+using MediaBrowser.Common;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Entities.TV;
+using MediaBrowser.Controller.LiveTv;
+using MediaBrowser.Model.Entities;
+using MediaBrowser.Model.LiveTv;
+using Microsoft.Extensions.Logging;
+using BaseItemDto = MediaBrowser.Controller.Entities.BaseItem;
+using BaseItemEntity = Jellyfin.Database.Implementations.Entities.BaseItemEntity;
+
+namespace Jellyfin.Server.Implementations.Item;
+
+/// <summary>
+/// Handles mapping between BaseItemEntity (database) and BaseItemDto (domain) objects.
+/// </summary>
+internal static class BaseItemMapper
+{
+ /// <summary>
+ /// This holds all the types in the running assemblies
+ /// so that we can de-serialize properly when we don't have strong types.
+ /// </summary>
+ private static readonly ConcurrentDictionary<string, Type?> _typeMap = new ConcurrentDictionary<string, Type?>();
+
+ /// <summary>
+ /// Maps a Entity to the DTO.
+ /// </summary>
+ /// <param name="entity">The entity.</param>
+ /// <param name="dto">The dto base instance.</param>
+ /// <param name="appHost">The Application server Host.</param>
+ /// <returns>The dto to map.</returns>
+ public static BaseItemDto Map(BaseItemEntity entity, BaseItemDto dto, IServerApplicationHost? appHost)
+ {
+ dto.Id = entity.Id;
+ dto.ParentId = entity.ParentId.GetValueOrDefault();
+ dto.Path = appHost?.ExpandVirtualPath(entity.Path) ?? entity.Path;
+ dto.EndDate = entity.EndDate;
+ dto.CommunityRating = entity.CommunityRating;
+ dto.CustomRating = entity.CustomRating;
+ dto.IndexNumber = entity.IndexNumber;
+ dto.IsLocked = entity.IsLocked;
+ dto.Name = entity.Name;
+ dto.OfficialRating = entity.OfficialRating;
+ dto.Overview = entity.Overview;
+ dto.ParentIndexNumber = entity.ParentIndexNumber;
+ dto.PremiereDate = entity.PremiereDate;
+ dto.ProductionYear = entity.ProductionYear;
+ dto.SortName = entity.SortName;
+ dto.ForcedSortName = entity.ForcedSortName;
+ dto.RunTimeTicks = entity.RunTimeTicks;
+ dto.PreferredMetadataLanguage = entity.PreferredMetadataLanguage;
+ dto.PreferredMetadataCountryCode = entity.PreferredMetadataCountryCode;
+ dto.IsInMixedFolder = entity.IsInMixedFolder;
+ dto.InheritedParentalRatingValue = entity.InheritedParentalRatingValue;
+ dto.InheritedParentalRatingSubValue = entity.InheritedParentalRatingSubValue;
+ dto.CriticRating = entity.CriticRating;
+ dto.PresentationUniqueKey = entity.PresentationUniqueKey;
+ dto.OriginalTitle = entity.OriginalTitle;
+ dto.Album = entity.Album;
+ dto.LUFS = entity.LUFS;
+ dto.NormalizationGain = entity.NormalizationGain;
+ dto.IsVirtualItem = entity.IsVirtualItem;
+ dto.ExternalSeriesId = entity.ExternalSeriesId;
+ dto.Tagline = entity.Tagline;
+ dto.TotalBitrate = entity.TotalBitrate;
+ dto.ExternalId = entity.ExternalId;
+ dto.Size = entity.Size;
+ dto.Genres = string.IsNullOrWhiteSpace(entity.Genres) ? [] : entity.Genres.Split('|');
+ dto.DateCreated = entity.DateCreated ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ dto.DateModified = entity.DateModified ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ dto.ChannelId = entity.ChannelId ?? Guid.Empty;
+ dto.DateLastRefreshed = entity.DateLastRefreshed ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ dto.DateLastSaved = entity.DateLastSaved ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ dto.OwnerId = entity.OwnerId ?? Guid.Empty;
+ dto.Width = entity.Width.GetValueOrDefault();
+ dto.Height = entity.Height.GetValueOrDefault();
+ dto.UserData = entity.UserData;
+
+ if (entity.Provider is not null)
+ {
+ dto.ProviderIds = entity.Provider.ToDictionary(e => e.ProviderId, e => e.ProviderValue);
+ }
+
+ if (entity.ExtraType is not null)
+ {
+ dto.ExtraType = (ExtraType)entity.ExtraType;
+ }
+
+ if (entity.LockedFields is not null)
+ {
+ dto.LockedFields = entity.LockedFields?.Select(e => (MetadataField)e.Id).ToArray() ?? [];
+ }
+
+ if (entity.Audio is not null)
+ {
+ dto.Audio = (ProgramAudio)entity.Audio;
+ }
+
+ dto.ProductionLocations = entity.ProductionLocations?.Split('|', StringSplitOptions.RemoveEmptyEntries) ?? [];
+ dto.Studios = entity.Studios?.Split('|') ?? [];
+ dto.Tags = string.IsNullOrWhiteSpace(entity.Tags) ? [] : entity.Tags.Split('|');
+
+ if (dto is IHasProgramAttributes hasProgramAttributes)
+ {
+ hasProgramAttributes.IsMovie = entity.IsMovie;
+ hasProgramAttributes.IsSeries = entity.IsSeries;
+ hasProgramAttributes.EpisodeTitle = entity.EpisodeTitle;
+ hasProgramAttributes.IsRepeat = entity.IsRepeat;
+ }
+
+ if (dto is LiveTvChannel liveTvChannel)
+ {
+ liveTvChannel.ServiceName = entity.ExternalServiceId;
+ }
+
+ if (dto is Trailer trailer)
+ {
+ trailer.TrailerTypes = entity.TrailerTypes?.Select(e => (TrailerType)e.Id).ToArray() ?? [];
+ }
+
+ if (dto is Video video)
+ {
+ video.PrimaryVersionId = entity.PrimaryVersionId;
+ }
+
+ if (dto is IHasSeries hasSeriesName)
+ {
+ hasSeriesName.SeriesName = entity.SeriesName;
+ hasSeriesName.SeriesId = entity.SeriesId.GetValueOrDefault();
+ hasSeriesName.SeriesPresentationUniqueKey = entity.SeriesPresentationUniqueKey;
+ }
+
+ if (dto is Episode episode)
+ {
+ episode.SeasonName = entity.SeasonName;
+ episode.SeasonId = entity.SeasonId.GetValueOrDefault();
+ }
+
+ if (dto is IHasArtist hasArtists)
+ {
+ hasArtists.Artists = entity.Artists?.Split('|', StringSplitOptions.RemoveEmptyEntries) ?? [];
+ }
+
+ if (dto is IHasAlbumArtist hasAlbumArtists)
+ {
+ hasAlbumArtists.AlbumArtists = entity.AlbumArtists?.Split('|', StringSplitOptions.RemoveEmptyEntries) ?? [];
+ }
+
+ if (dto is LiveTvProgram program)
+ {
+ program.ShowId = entity.ShowId;
+ }
+
+ if (entity.Images is not null)
+ {
+ dto.ImageInfos = entity.Images.Select(e => MapImageFromEntity(e, appHost)).ToArray();
+ }
+
+ // dto.Type = entity.Type;
+ // dto.Data = entity.Data;
+ // dto.MediaType = Enum.TryParse<MediaType>(entity.MediaType);
+ if (dto is IHasStartDate hasStartDate)
+ {
+ hasStartDate.StartDate = entity.StartDate.GetValueOrDefault();
+ }
+
+ // Fields that are present in the DB but are never actually used
+ // dto.UnratedType = entity.UnratedType;
+ // dto.TopParentId = entity.TopParentId;
+ // dto.CleanName = entity.CleanName;
+ // dto.UserDataKey = entity.UserDataKey;
+
+ if (dto is Folder folder)
+ {
+ folder.DateLastMediaAdded = entity.DateLastMediaAdded ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
+ if (entity.LinkedChildEntities is not null && entity.LinkedChildEntities.Count > 0)
+ {
+ folder.LinkedChildren = entity.LinkedChildEntities
+ .OrderBy(e => e.SortOrder)
+ .Select(e => new LinkedChild
+ {
+ ItemId = e.ChildId,
+ Type = (MediaBrowser.Controller.Entities.LinkedChildType)e.ChildType
+ })
+ .ToArray();
+ }
+ }
+
+ return dto;
+ }
+
+ /// <summary>
+ /// Maps a DTO to a database entity.
+ /// </summary>
+ /// <param name="dto">The DTO.</param>
+ /// <param name="appHost">The application host for path resolution.</param>
+ /// <returns>The database entity.</returns>
+ public static BaseItemEntity Map(BaseItemDto dto, IServerApplicationHost appHost)
+ {
+ var dtoType = dto.GetType();
+ var entity = new BaseItemEntity()
+ {
+ Type = dtoType.ToString(),
+ Id = dto.Id
+ };
+
+ if (TypeRequiresDeserialization(dtoType))
+ {
+ entity.Data = JsonSerializer.Serialize(dto, dtoType, JsonDefaults.Options);
+ }
+
+ entity.ParentId = !dto.ParentId.IsEmpty() ? dto.ParentId : null;
+ entity.Path = GetPathToSave(dto.Path, appHost);
+ entity.EndDate = dto.EndDate;
+ entity.CommunityRating = dto.CommunityRating;
+ entity.CustomRating = dto.CustomRating;
+ entity.IndexNumber = dto.IndexNumber;
+ entity.IsLocked = dto.IsLocked;
+ entity.Name = dto.Name;
+ entity.CleanName = dto.Name.GetCleanValue();
+ entity.OfficialRating = dto.OfficialRating;
+ entity.Overview = dto.Overview;
+ entity.ParentIndexNumber = dto.ParentIndexNumber;
+ entity.PremiereDate = dto.PremiereDate;
+ entity.ProductionYear = dto.ProductionYear;
+ entity.SortName = dto.SortName;
+ entity.ForcedSortName = dto.ForcedSortName;
+ entity.RunTimeTicks = dto.RunTimeTicks;
+ entity.PreferredMetadataLanguage = dto.PreferredMetadataLanguage;
+ entity.PreferredMetadataCountryCode = dto.PreferredMetadataCountryCode;
+ entity.IsInMixedFolder = dto.IsInMixedFolder;
+ entity.InheritedParentalRatingValue = dto.InheritedParentalRatingValue;
+ entity.InheritedParentalRatingSubValue = dto.InheritedParentalRatingSubValue;
+ entity.CriticRating = dto.CriticRating;
+ entity.PresentationUniqueKey = dto.PresentationUniqueKey;
+ entity.OriginalTitle = dto.OriginalTitle;
+ entity.Album = dto.Album;
+ entity.LUFS = dto.LUFS;
+ entity.NormalizationGain = dto.NormalizationGain;
+ entity.IsVirtualItem = dto.IsVirtualItem;
+ entity.ExternalSeriesId = dto.ExternalSeriesId;
+ entity.Tagline = dto.Tagline;
+ entity.TotalBitrate = dto.TotalBitrate;
+ entity.ExternalId = dto.ExternalId;
+ entity.Size = dto.Size;
- entity.Genres = string.Join('|', dto.Genres);
++ entity.Genres = string.Join('|', dto.Genres.Distinct(StringComparer.OrdinalIgnoreCase));
+ entity.DateCreated = dto.DateCreated == DateTime.MinValue ? null : dto.DateCreated;
+ entity.DateModified = dto.DateModified == DateTime.MinValue ? null : dto.DateModified;
+ entity.ChannelId = dto.ChannelId;
+ entity.DateLastRefreshed = dto.DateLastRefreshed == DateTime.MinValue ? null : dto.DateLastRefreshed;
+ entity.DateLastSaved = dto.DateLastSaved == DateTime.MinValue ? null : dto.DateLastSaved;
+ entity.OwnerId = dto.OwnerId == Guid.Empty ? null : dto.OwnerId;
+ entity.Width = dto.Width;
+ entity.Height = dto.Height;
+ entity.Provider = dto.ProviderIds.Select(e => new BaseItemProvider()
+ {
+ Item = entity,
+ ProviderId = e.Key,
+ ProviderValue = e.Value
+ }).ToList();
+
+ if (dto.Audio.HasValue)
+ {
+ entity.Audio = (ProgramAudioEntity)dto.Audio;
+ }
+
+ if (dto.ExtraType.HasValue)
+ {
+ entity.ExtraType = (BaseItemExtraType)dto.ExtraType;
+ }
+
- entity.ProductionLocations = dto.ProductionLocations is not null ? string.Join('|', dto.ProductionLocations.Where(p => !string.IsNullOrWhiteSpace(p))) : null;
- entity.Studios = dto.Studios is not null ? string.Join('|', dto.Studios) : null;
- entity.Tags = dto.Tags is not null ? string.Join('|', dto.Tags) : null;
++ entity.ProductionLocations = dto.ProductionLocations is not null ? string.Join('|', dto.ProductionLocations.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct(StringComparer.OrdinalIgnoreCase)) : null;
++ entity.Studios = dto.Studios is not null ? string.Join('|', dto.Studios.Distinct(StringComparer.OrdinalIgnoreCase)) : null;
++ entity.Tags = dto.Tags is not null ? string.Join('|', dto.Tags.Distinct(StringComparer.OrdinalIgnoreCase)) : null;
+ entity.LockedFields = dto.LockedFields is not null ? dto.LockedFields
+ .Select(e => new BaseItemMetadataField()
+ {
+ Id = (int)e,
+ Item = entity,
+ ItemId = entity.Id
+ })
+ .ToArray() : null;
+
+ if (dto is IHasProgramAttributes hasProgramAttributes)
+ {
+ entity.IsMovie = hasProgramAttributes.IsMovie;
+ entity.IsSeries = hasProgramAttributes.IsSeries;
+ entity.EpisodeTitle = hasProgramAttributes.EpisodeTitle;
+ entity.IsRepeat = hasProgramAttributes.IsRepeat;
+ }
+
+ if (dto is LiveTvChannel liveTvChannel)
+ {
+ entity.ExternalServiceId = liveTvChannel.ServiceName;
+ }
+
+ if (dto is Video video)
+ {
+ entity.PrimaryVersionId = video.PrimaryVersionId;
+ }
+
+ if (dto is IHasSeries hasSeriesName)
+ {
+ entity.SeriesName = hasSeriesName.SeriesName;
+ entity.SeriesId = hasSeriesName.SeriesId;
+ entity.SeriesPresentationUniqueKey = hasSeriesName.SeriesPresentationUniqueKey;
+ }
+
+ if (dto is Episode episode)
+ {
+ entity.SeasonName = episode.SeasonName;
+ entity.SeasonId = episode.SeasonId;
+ }
+
+ if (dto is IHasArtist hasArtists)
+ {
- entity.Artists = hasArtists.Artists is not null ? string.Join('|', hasArtists.Artists) : null;
++ entity.Artists = hasArtists.Artists is not null ? string.Join('|', hasArtists.Artists.Distinct(StringComparer.OrdinalIgnoreCase)) : null;
+ }
+
+ if (dto is IHasAlbumArtist hasAlbumArtists)
+ {
- entity.AlbumArtists = hasAlbumArtists.AlbumArtists is not null ? string.Join('|', hasAlbumArtists.AlbumArtists) : null;
++ entity.AlbumArtists = hasAlbumArtists.AlbumArtists is not null ? string.Join('|', hasAlbumArtists.AlbumArtists.Distinct(StringComparer.OrdinalIgnoreCase)) : null;
+ }
+
+ if (dto is LiveTvProgram program)
+ {
+ entity.ShowId = program.ShowId;
+ }
+
+ if (dto.ImageInfos is not null)
+ {
+ entity.Images = dto.ImageInfos.Select(f => MapImageToEntity(dto.Id, f)).ToArray();
+ }
+
+ if (dto is Trailer trailer)
+ {
+ entity.TrailerTypes = trailer.TrailerTypes?.Select(e => new BaseItemTrailerType()
+ {
+ Id = (int)e,
+ Item = entity,
+ ItemId = entity.Id
+ }).ToArray() ?? [];
+ }
+
+ // dto.Type = entity.Type;
+ // dto.Data = entity.Data;
+ entity.MediaType = dto.MediaType.ToString();
+ if (dto is IHasStartDate hasStartDate)
+ {
+ entity.StartDate = hasStartDate.StartDate;
+ }
+
+ entity.UnratedType = dto.GetBlockUnratedType().ToString();
+
+ // Fields that are present in the DB but are never actually used
+ // dto.UserDataKey = entity.UserDataKey;
+
+ if (dto is Folder folder)
+ {
+ entity.DateLastMediaAdded = folder.DateLastMediaAdded == DateTime.MinValue ? null : folder.DateLastMediaAdded;
+ entity.IsFolder = folder.IsFolder;
+ }
+
+ return entity;
+ }
+
+ /// <summary>
+ /// Maps a database image entity to a domain image info.
+ /// </summary>
+ /// <param name="e">The database image entity.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <returns>The mapped image info.</returns>
+ public static ItemImageInfo MapImageFromEntity(BaseItemImageInfo e, IServerApplicationHost? appHost)
+ {
+ return new ItemImageInfo()
+ {
+ Path = appHost?.ExpandVirtualPath(e.Path) ?? e.Path,
+ BlurHash = e.Blurhash is null ? null : Encoding.UTF8.GetString(e.Blurhash),
+ DateModified = e.DateModified ?? DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc),
+ Height = e.Height,
+ Width = e.Width,
+ Type = (ImageType)e.ImageType
+ };
+ }
+
+ /// <summary>
+ /// Maps a domain image info to a database image entity.
+ /// </summary>
+ /// <param name="baseItemId">The parent item ID.</param>
+ /// <param name="e">The image info to map.</param>
+ /// <returns>The mapped database entity.</returns>
+ public static BaseItemImageInfo MapImageToEntity(Guid baseItemId, ItemImageInfo e)
+ {
+ return new BaseItemImageInfo()
+ {
+ ItemId = baseItemId,
+ Id = Guid.NewGuid(),
+ Path = e.Path,
+ Blurhash = e.BlurHash is null ? null : Encoding.UTF8.GetBytes(e.BlurHash),
+ DateModified = e.DateModified,
+ Height = e.Height,
+ Width = e.Width,
+ ImageType = (ImageInfoImageType)e.Type,
+ Item = null!
+ };
+ }
+
+ /// <summary>
+ /// Gets the type from a type name string.
+ /// </summary>
+ /// <param name="typeName">The type name.</param>
+ /// <returns>The resolved type, or null.</returns>
+ public static Type? GetType(string typeName)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(typeName);
+
+ return _typeMap.GetOrAdd(typeName, k => AppDomain.CurrentDomain.GetAssemblies()
+ .Select(a => a.GetType(k))
+ .FirstOrDefault(t => t is not null));
+ }
+
+ /// <summary>
+ /// Checks whether a type requires JSON deserialization.
+ /// </summary>
+ /// <param name="type">The type to check.</param>
+ /// <returns>True if the type requires deserialization.</returns>
+ public static bool TypeRequiresDeserialization(Type type)
+ {
+ return type.GetCustomAttribute<RequiresSourceSerialisationAttribute>() == null;
+ }
+
+ /// <summary>
+ /// Deserializes a BaseItemEntity and sets all properties.
+ /// </summary>
+ /// <param name="baseItemEntity">The DB entity.</param>
+ /// <param name="logger">Logger.</param>
+ /// <param name="appHost">The application server Host.</param>
+ /// <param name="skipDeserialization">If only mapping should be processed.</param>
+ /// <returns>A mapped BaseItem, or null if the item type is unknown.</returns>
+ public static BaseItemDto? DeserializeBaseItem(BaseItemEntity baseItemEntity, ILogger logger, IServerApplicationHost? appHost, bool skipDeserialization = false)
+ {
+ var type = GetType(baseItemEntity.Type);
+ if (type is null)
+ {
+ logger.LogWarning(
+ "Skipping item {ItemId} with unknown type '{ItemType}'. This may indicate a removed plugin or database corruption.",
+ baseItemEntity.Id,
+ baseItemEntity.Type);
+ return null;
+ }
+
+ BaseItemDto? dto = null;
+ if (TypeRequiresDeserialization(type) && baseItemEntity.Data is not null && !skipDeserialization)
+ {
+ try
+ {
+ dto = JsonSerializer.Deserialize(baseItemEntity.Data, type, JsonDefaults.Options) as BaseItemDto;
+ }
+ catch (JsonException ex)
+ {
+ logger.LogError(ex, "Error deserializing item with JSON: {Data}", baseItemEntity.Data);
+ }
+ }
+
+ if (dto is null)
+ {
+ dto = Activator.CreateInstance(type) as BaseItemDto ?? throw new InvalidOperationException("Cannot deserialize unknown type.");
+ }
+
+ return Map(baseItemEntity, dto, appHost);
+ }
+
+ private static string? GetPathToSave(string path, IServerApplicationHost appHost)
+ {
+ if (path is null)
+ {
+ return null;
+ }
+
+ return appHost.ReverseVirtualPath(path);
+ }
+}
diff --cc Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs
index 305a8d4a45,0000000000..ffa5cff1f2
mode 100644,000000..100644
--- a/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs
+++ b/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs
@@@ -1,663 -1,0 +1,664 @@@
+#pragma warning disable RS0030 // Do not use banned APIs
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Database.Implementations;
+using Jellyfin.Database.Implementations.Entities;
+using Jellyfin.Extensions;
+using MediaBrowser.Controller;
+using MediaBrowser.Controller.Entities;
+using MediaBrowser.Controller.Entities.Audio;
+using MediaBrowser.Controller.Persistence;
+using MediaBrowser.Controller.Playlists;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Logging;
+using BaseItemDto = MediaBrowser.Controller.Entities.BaseItem;
+using DbLinkedChildType = Jellyfin.Database.Implementations.Entities.LinkedChildType;
+using LinkedChildType = MediaBrowser.Controller.Entities.LinkedChildType;
+
+namespace Jellyfin.Server.Implementations.Item;
+
+/// <summary>
+/// Handles item persistence operations (save, delete, update).
+/// </summary>
+public class ItemPersistenceService : IItemPersistenceService
+{
+ private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
+ private readonly IServerApplicationHost _appHost;
+ private readonly ILogger<ItemPersistenceService> _logger;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ItemPersistenceService"/> class.
+ /// </summary>
+ /// <param name="dbProvider">The database context factory.</param>
+ /// <param name="appHost">The application host.</param>
+ /// <param name="logger">The logger.</param>
+ public ItemPersistenceService(
+ IDbContextFactory<JellyfinDbContext> dbProvider,
+ IServerApplicationHost appHost,
+ ILogger<ItemPersistenceService> logger)
+ {
+ _dbProvider = dbProvider;
+ _appHost = appHost;
+ _logger = logger;
+ }
+
+ /// <inheritdoc />
+ public void DeleteItem(params IReadOnlyList<Guid> ids)
+ {
+ if (ids is null || ids.Count == 0 || ids.Any(f => f.Equals(BaseItemRepository.PlaceholderId)))
+ {
+ throw new ArgumentException("Guid can't be empty or the placeholder id.", nameof(ids));
+ }
+
+ using var context = _dbProvider.CreateDbContext();
+ using var transaction = context.Database.BeginTransaction();
+
+ var date = (DateTime?)DateTime.UtcNow;
+
+ var descendantIds = DescendantQueryHelper.GetOwnedDescendantIdsBatch(context, ids);
+ foreach (var id in ids)
+ {
+ descendantIds.Add(id);
+ }
+
+ var extraIds = context.BaseItems
+ .Where(e => e.OwnerId.HasValue && descendantIds.Contains(e.OwnerId.Value))
+ .Select(e => e.Id)
+ .ToArray();
+
+ foreach (var extraId in extraIds)
+ {
+ descendantIds.Add(extraId);
+ }
+
+ var relatedItems = descendantIds.ToArray();
+
+ // When batch-deleting, multiple items may have UserData for the same (UserId, CustomDataKey).
+ // Moving all of them to PlaceholderId would violate the UNIQUE constraint.
+ // Deduplicate by loading keys client-side, keeping the best row per group.
+ var batchUserData = context.UserData.WhereOneOrMany(relatedItems, e => e.ItemId);
+
+ var allRows = batchUserData
+ .Select(ud => new { ud.ItemId, ud.UserId, ud.CustomDataKey, ud.LastPlayedDate, ud.PlayCount })
+ .ToList();
+
+ var duplicateRows = allRows
+ .GroupBy(ud => new { ud.UserId, ud.CustomDataKey })
+ .Where(g => g.Count() > 1)
+ .SelectMany(g => g
+ .OrderByDescending(ud => ud.LastPlayedDate)
+ .ThenByDescending(ud => ud.PlayCount)
+ .Skip(1))
+ .ToList();
+
+ foreach (var dup in duplicateRows)
+ {
+ context.UserData
+ .Where(ud => ud.ItemId == dup.ItemId && ud.UserId == dup.UserId && ud.CustomDataKey == dup.CustomDataKey)
+ .ExecuteDelete();
+ }
+
+ // Delete existing placeholder rows that would conflict with the incoming ones
+ context.UserData
+ .Join(
+ batchUserData,
+ placeholder => new { placeholder.UserId, placeholder.CustomDataKey },
+ userData => new { userData.UserId, userData.CustomDataKey },
+ (placeholder, userData) => placeholder)
+ .Where(e => e.ItemId == BaseItemRepository.PlaceholderId)
+ .ExecuteDelete();
+
+ batchUserData
+ .ExecuteUpdate(e => e
+ .SetProperty(f => f.RetentionDate, date)
+ .SetProperty(f => f.ItemId, BaseItemRepository.PlaceholderId));
+
+ context.AncestorIds.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.AncestorIds.WhereOneOrMany(relatedItems, e => e.ParentItemId).ExecuteDelete();
+ context.AttachmentStreamInfos.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.BaseItemImageInfos.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.BaseItemMetadataFields.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.BaseItemProviders.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.BaseItemTrailerTypes.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.Chapters.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.CustomItemDisplayPreferences.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.ItemDisplayPreferences.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.ItemValues.Where(e => e.BaseItemsMap!.Count == 0).ExecuteDelete();
+ context.ItemValuesMap.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.LinkedChildren.WhereOneOrMany(relatedItems, e => e.ParentId).ExecuteDelete();
+ context.LinkedChildren.WhereOneOrMany(relatedItems, e => e.ChildId).ExecuteDelete();
+ context.BaseItems.WhereOneOrMany(relatedItems, e => e.Id).ExecuteDelete();
+ context.KeyframeData.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.MediaSegments.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.MediaStreamInfos.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ var query = context.PeopleBaseItemMap.WhereOneOrMany(relatedItems, e => e.ItemId).Select(f => f.PeopleId).Distinct().ToArray();
+ context.PeopleBaseItemMap.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.Peoples.WhereOneOrMany(query, e => e.Id).Where(e => e.BaseItems!.Count == 0).ExecuteDelete();
+ context.TrickplayInfos.WhereOneOrMany(relatedItems, e => e.ItemId).ExecuteDelete();
+ context.SaveChanges();
+ transaction.Commit();
+ }
+
+ /// <inheritdoc />
+ public void UpdateInheritedValues()
+ {
+ using var context = _dbProvider.CreateDbContext();
+ using var transaction = context.Database.BeginTransaction();
+
+ context.ItemValuesMap.Where(e => e.ItemValue.Type == ItemValueType.InheritedTags).ExecuteDelete();
+ context.SaveChanges();
+
+ transaction.Commit();
+ }
+
+ /// <inheritdoc />
+ public void SaveItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
+ {
+ UpdateOrInsertItems(items, cancellationToken);
+ }
+
+ /// <inheritdoc />
+ public async Task SaveImagesAsync(BaseItem item, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+
+ var images = item.ImageInfos.Select(e => BaseItemMapper.MapImageToEntity(item.Id, e)).ToArray();
+
+ var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+ await using (context.ConfigureAwait(false))
+ {
+ if (!await context.BaseItems
+ .AnyAsync(bi => bi.Id == item.Id, cancellationToken)
+ .ConfigureAwait(false))
+ {
+ _logger.LogWarning("Unable to save ImageInfo for non existing BaseItem");
+ return;
+ }
+
+ await context.BaseItemImageInfos
+ .Where(e => e.ItemId == item.Id)
+ .ExecuteDeleteAsync(cancellationToken)
+ .ConfigureAwait(false);
+
+ await context.BaseItemImageInfos
+ .AddRangeAsync(images, cancellationToken)
+ .ConfigureAwait(false);
+
+ await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ /// <inheritdoc />
+ public async Task ReattachUserDataAsync(BaseItemDto item, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
+
+ await using (dbContext.ConfigureAwait(false))
+ {
+ var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
+ await using (transaction.ConfigureAwait(false))
+ {
+ var userKeys = item.GetUserDataKeys().ToArray();
+ var retentionDate = (DateTime?)null;
+
+ await dbContext.UserData
+ .Where(e => e.ItemId == BaseItemRepository.PlaceholderId)
+ .Where(e => userKeys.Contains(e.CustomDataKey))
+ .ExecuteUpdateAsync(
+ e => e
+ .SetProperty(f => f.ItemId, item.Id)
+ .SetProperty(f => f.RetentionDate, retentionDate),
+ cancellationToken).ConfigureAwait(false);
+
+ item.UserData = await dbContext.UserData
+ .AsNoTracking()
+ .Where(e => e.ItemId == item.Id)
+ .ToArrayAsync(cancellationToken)
+ .ConfigureAwait(false);
+
+ await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private void UpdateOrInsertItems(IReadOnlyList<BaseItemDto> items, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(items);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tuples = new List<(BaseItemDto Item, List<Guid>? AncestorIds, BaseItemDto TopParent, IEnumerable<string> UserDataKey, List<string> InheritedTags)>();
+ foreach (var item in items.GroupBy(e => e.Id).Select(e => e.Last()).Where(e => e.Id != BaseItemRepository.PlaceholderId))
+ {
+ var ancestorIds = item.SupportsAncestors ?
+ item.GetAncestorIds().Distinct().ToList() :
+ null;
+
+ var topParent = item.GetTopParent();
+
+ var userdataKey = item.GetUserDataKeys();
+ var inheritedTags = item.GetInheritedTags();
+
+ tuples.Add((item, ancestorIds, topParent, userdataKey, inheritedTags));
+ }
+
+ using var context = _dbProvider.CreateDbContext();
+ using var transaction = context.Database.BeginTransaction();
+
+ var ids = tuples.Select(f => f.Item.Id).ToArray();
+ var existingItems = context.BaseItems.Where(e => ids.Contains(e.Id)).Select(f => f.Id).ToArray();
+
+ foreach (var item in tuples)
+ {
+ var entity = BaseItemMapper.Map(item.Item, _appHost);
+ entity.TopParentId = item.TopParent?.Id;
+
+ if (!existingItems.Any(e => e == entity.Id))
+ {
+ context.BaseItems.Add(entity);
+ }
+ else
+ {
+ context.BaseItemProviders.Where(e => e.ItemId == entity.Id).ExecuteDelete();
+ context.BaseItemImageInfos.Where(e => e.ItemId == entity.Id).ExecuteDelete();
+ context.BaseItemMetadataFields.Where(e => e.ItemId == entity.Id).ExecuteDelete();
+
+ if (entity.Images is { Count: > 0 })
+ {
+ context.BaseItemImageInfos.AddRange(entity.Images);
+ }
+
+ if (entity.LockedFields is { Count: > 0 })
+ {
+ context.BaseItemMetadataFields.AddRange(entity.LockedFields);
+ }
+
+ context.BaseItems.Attach(entity).State = EntityState.Modified;
+ }
+ }
+
+ var itemValueMaps = tuples
+ .Select(e => (e.Item, Values: GetItemValuesToSave(e.Item, e.InheritedTags)))
+ .ToArray();
+ var allListedItemValues = itemValueMaps
+ .SelectMany(f => f.Values)
+ .Distinct()
+ .ToArray();
++
++ var types = allListedItemValues.Select(e => e.MagicNumber).Distinct().ToArray();
++ var values = allListedItemValues.Select(e => e.Value).Distinct().ToArray();
++ var allListedItemValuesSet = allListedItemValues.ToHashSet();
++
+ var existingValues = context.ItemValues
- .Select(e => new
- {
- item = e,
- Key = e.Type + "+" + e.Value
- })
- .Where(f => allListedItemValues.Select(e => $"{(int)e.MagicNumber}+{e.Value}").Contains(f.Key))
- .Select(e => e.item)
++ .Where(e => types.Contains(e.Type) && values.Contains(e.Value))
++ .AsEnumerable()
++ .Where(e => allListedItemValuesSet.Contains((e.Type, e.Value)))
+ .ToArray();
+ var missingItemValues = allListedItemValues.Except(existingValues.Select(f => (MagicNumber: f.Type, f.Value))).Select(f => new ItemValue()
+ {
+ CleanValue = f.Value.GetCleanValue(),
+ ItemValueId = Guid.NewGuid(),
+ Type = f.MagicNumber,
+ Value = f.Value
+ }).ToArray();
+ context.ItemValues.AddRange(missingItemValues);
+
+ var itemValuesStore = existingValues.Concat(missingItemValues).ToArray();
+ var valueMap = itemValueMaps
+ .Select(f => (f.Item, Values: f.Values.Select(e => itemValuesStore.First(g => g.Value == e.Value && g.Type == e.MagicNumber)).DistinctBy(e => e.ItemValueId).ToArray()))
+ .ToArray();
+
+ var mappedValues = context.ItemValuesMap.Where(e => ids.Contains(e.ItemId)).ToList();
+
+ foreach (var item in valueMap)
+ {
+ var itemMappedValues = mappedValues.Where(e => e.ItemId == item.Item.Id).ToList();
+ foreach (var itemValue in item.Values)
+ {
+ var existingItem = itemMappedValues.FirstOrDefault(f => f.ItemValueId == itemValue.ItemValueId);
+ if (existingItem is null)
+ {
+ context.ItemValuesMap.Add(new ItemValueMap()
+ {
+ Item = null!,
+ ItemId = item.Item.Id,
+ ItemValue = null!,
+ ItemValueId = itemValue.ItemValueId
+ });
+ }
+ else
+ {
+ itemMappedValues.Remove(existingItem);
+ }
+ }
+
+ context.ItemValuesMap.RemoveRange(itemMappedValues);
+ }
+
+ var itemsWithAncestors = tuples
+ .Where(t => t.Item.SupportsAncestors && t.AncestorIds != null)
+ .Select(t => t.Item.Id)
+ .ToList();
+
+ var allExistingAncestorIds = itemsWithAncestors.Count > 0
+ ? context.AncestorIds
+ .Where(e => itemsWithAncestors.Contains(e.ItemId))
+ .ToList()
+ .GroupBy(e => e.ItemId)
+ .ToDictionary(g => g.Key, g => g.ToList())
+ : new Dictionary<Guid, List<AncestorId>>();
+
+ var allRequestedAncestorIds = tuples
+ .Where(t => t.Item.SupportsAncestors && t.AncestorIds != null)
+ .SelectMany(t => t.AncestorIds!)
+ .Distinct()
+ .ToList();
+
+ var validAncestorIdsSet = allRequestedAncestorIds.Count > 0
+ ? context.BaseItems
+ .Where(e => allRequestedAncestorIds.Contains(e.Id))
+ .Select(f => f.Id)
+ .ToHashSet()
+ : new HashSet<Guid>();
+
+ foreach (var item in tuples)
+ {
+ if (item.Item.SupportsAncestors && item.AncestorIds != null)
+ {
+ var existingAncestorIds = allExistingAncestorIds.GetValueOrDefault(item.Item.Id) ?? new List<AncestorId>();
+ var validAncestorIds = item.AncestorIds.Where(id => validAncestorIdsSet.Contains(id)).ToArray();
+ foreach (var ancestorId in validAncestorIds)
+ {
+ var existingAncestorId = existingAncestorIds.FirstOrDefault(e => e.ParentItemId == ancestorId);
+ if (existingAncestorId is null)
+ {
+ context.AncestorIds.Add(new AncestorId()
+ {
+ ParentItemId = ancestorId,
+ ItemId = item.Item.Id,
+ Item = null!,
+ ParentItem = null!
+ });
+ }
+ else
+ {
+ existingAncestorIds.Remove(existingAncestorId);
+ }
+ }
+
+ context.AncestorIds.RemoveRange(existingAncestorIds);
+ }
+ }
+
+ context.SaveChanges();
+
+ var folderIds = tuples
+ .Where(t => t.Item is Folder)
+ .Select(t => t.Item.Id)
+ .ToList();
+
+ var videoIds = tuples
+ .Where(t => t.Item is Video)
+ .Select(t => t.Item.Id)
+ .ToList();
+
+ var allLinkedChildrenByParent = new Dictionary<Guid, List<LinkedChildEntity>>();
+ if (folderIds.Count > 0 || videoIds.Count > 0)
+ {
+ var allParentIds = folderIds.Concat(videoIds).Distinct().ToList();
+ var allLinkedChildren = context.LinkedChildren
+ .Where(e => allParentIds.Contains(e.ParentId))
+ .ToList();
+
+ allLinkedChildrenByParent = allLinkedChildren
+ .GroupBy(e => e.ParentId)
+ .ToDictionary(g => g.Key, g => g.ToList());
+ }
+
+ foreach (var item in tuples)
+ {
+ if (item.Item is Folder folder)
+ {
+ var existingLinkedChildren = allLinkedChildrenByParent.GetValueOrDefault(item.Item.Id)?.ToList() ?? new List<LinkedChildEntity>();
+ if (folder.LinkedChildren.Length > 0)
+ {
+#pragma warning disable CS0618 // Type or member is obsolete - legacy path resolution for old data
+ var pathsToResolve = folder.LinkedChildren
+ .Where(lc => (!lc.ItemId.HasValue || lc.ItemId.Value.IsEmpty()) && !string.IsNullOrEmpty(lc.Path))
+ .Select(lc => lc.Path)
+ .Distinct()
+ .ToList();
+
+ var pathToIdMap = pathsToResolve.Count > 0
+ ? context.BaseItems
+ .Where(e => e.Path != null && pathsToResolve.Contains(e.Path))
+ .Select(e => new { e.Path, e.Id })
+ .GroupBy(e => e.Path!)
+ .ToDictionary(g => g.Key, g => g.First().Id)
+ : [];
+
+ var resolvedChildren = new List<(LinkedChild Child, Guid ChildId)>();
+ foreach (var linkedChild in folder.LinkedChildren)
+ {
+ var childItemId = linkedChild.ItemId;
+ if (!childItemId.HasValue || childItemId.Value.IsEmpty())
+ {
+ if (!string.IsNullOrEmpty(linkedChild.Path) && pathToIdMap.TryGetValue(linkedChild.Path, out var resolvedId))
+ {
+ childItemId = resolvedId;
+ }
+ }
+#pragma warning restore CS0618
+
+ if (childItemId.HasValue && !childItemId.Value.IsEmpty())
+ {
+ resolvedChildren.Add((linkedChild, childItemId.Value));
+ }
+ }
+
+ resolvedChildren = resolvedChildren
+ .GroupBy(c => c.ChildId)
+ .Select(g => g.Last())
+ .ToList();
+
+ var childIdsToCheck = resolvedChildren.Select(c => c.ChildId).ToList();
+ var existingChildIds = childIdsToCheck.Count > 0
+ ? context.BaseItems
+ .Where(e => childIdsToCheck.Contains(e.Id))
+ .Select(e => e.Id)
+ .ToHashSet()
+ : [];
+
+ var isPlaylist = folder is Playlist;
+ var sortOrder = 0;
+ foreach (var (linkedChild, childId) in resolvedChildren)
+ {
+ if (!existingChildIds.Contains(childId))
+ {
+ _logger.LogWarning(
+ "Skipping LinkedChild for parent {ParentName} ({ParentId}): child item {ChildId} does not exist in database",
+ item.Item.Name,
+ item.Item.Id,
+ childId);
+ continue;
+ }
+
+ var existingLink = existingLinkedChildren.FirstOrDefault(e => e.ChildId == childId);
+ if (existingLink is null)
+ {
+ context.LinkedChildren.Add(new LinkedChildEntity()
+ {
+ ParentId = item.Item.Id,
+ ChildId = childId,
+ ChildType = (DbLinkedChildType)linkedChild.Type,
+ SortOrder = isPlaylist ? sortOrder : null
+ });
+ }
+ else
+ {
+ existingLink.SortOrder = isPlaylist ? sortOrder : null;
+ existingLink.ChildType = (DbLinkedChildType)linkedChild.Type;
+ existingLinkedChildren.Remove(existingLink);
+ }
+
+ sortOrder++;
+ }
+ }
+
+ if (existingLinkedChildren.Count > 0)
+ {
+ context.LinkedChildren.RemoveRange(existingLinkedChildren);
+ }
+ }
+
+ if (item.Item is Video video)
+ {
+ var existingLinkedChildren = (allLinkedChildrenByParent.GetValueOrDefault(video.Id) ?? new List<LinkedChildEntity>())
+ .Where(e => (int)e.ChildType == 2 || (int)e.ChildType == 3)
+ .ToList();
+
+ var newLinkedChildren = new List<(Guid ChildId, LinkedChildType Type)>();
+
+ if (video.LocalAlternateVersions.Length > 0)
+ {
+ var pathsToResolve = video.LocalAlternateVersions.Where(p => !string.IsNullOrEmpty(p)).ToList();
+ if (pathsToResolve.Count > 0)
+ {
+ var pathToIdMap = context.BaseItems
+ .Where(e => e.Path != null && pathsToResolve.Contains(e.Path))
+ .Select(e => new { e.Path, e.Id })
+ .GroupBy(e => e.Path!)
+ .ToDictionary(g => g.Key, g => g.First().Id);
+
+ foreach (var path in pathsToResolve)
+ {
+ if (pathToIdMap.TryGetValue(path, out var childId))
+ {
+ newLinkedChildren.Add((childId, LinkedChildType.LocalAlternateVersion));
+ }
+ }
+ }
+ }
+
+ if (video.LinkedAlternateVersions.Length > 0)
+ {
+ foreach (var linkedChild in video.LinkedAlternateVersions)
+ {
+ if (linkedChild.ItemId.HasValue && !linkedChild.ItemId.Value.IsEmpty())
+ {
+ newLinkedChildren.Add((linkedChild.ItemId.Value, LinkedChildType.LinkedAlternateVersion));
+ }
+ }
+ }
+
+ newLinkedChildren = newLinkedChildren
+ .GroupBy(c => c.ChildId)
+ .Select(g => g.Last())
+ .ToList();
+
+ var childIdsToCheck = newLinkedChildren.Select(c => c.ChildId).ToList();
+ var existingChildIds = childIdsToCheck.Count > 0
+ ? context.BaseItems
+ .Where(e => childIdsToCheck.Contains(e.Id))
+ .Select(e => e.Id)
+ .ToHashSet()
+ : [];
+
+ int sortOrder = 0;
+ foreach (var (childId, childType) in newLinkedChildren)
+ {
+ if (!existingChildIds.Contains(childId))
+ {
+ _logger.LogWarning(
+ "Skipping alternate version for video {VideoName} ({VideoId}): child item {ChildId} does not exist in database",
+ video.Name,
+ video.Id,
+ childId);
+ continue;
+ }
+
+ var existingLink = existingLinkedChildren.FirstOrDefault(e => e.ChildId == childId);
+ if (existingLink is null)
+ {
+ context.LinkedChildren.Add(new LinkedChildEntity
+ {
+ ParentId = video.Id,
+ ChildId = childId,
+ ChildType = (DbLinkedChildType)childType,
+ SortOrder = sortOrder
+ });
+ }
+ else
+ {
+ existingLink.ChildType = (DbLinkedChildType)childType;
+ existingLink.SortOrder = sortOrder;
+ existingLinkedChildren.Remove(existingLink);
+ }
+
+ sortOrder++;
+ }
+
+ if (existingLinkedChildren.Count > 0)
+ {
+ var orphanedLocalVersionIds = existingLinkedChildren
+ .Where(e => e.ChildType == DbLinkedChildType.LocalAlternateVersion)
+ .Select(e => e.ChildId)
+ .ToList();
+
+ context.LinkedChildren.RemoveRange(existingLinkedChildren);
+
+ if (orphanedLocalVersionIds.Count > 0)
+ {
+ var orphanedItems = context.BaseItems
+ .Where(e => orphanedLocalVersionIds.Contains(e.Id) && e.OwnerId == video.Id)
+ .ToList();
+
+ if (orphanedItems.Count > 0)
+ {
+ _logger.LogInformation(
+ "Deleting {Count} orphaned LocalAlternateVersion items for video {VideoName} ({VideoId})",
+ orphanedItems.Count,
+ video.Name,
+ video.Id);
+ context.BaseItems.RemoveRange(orphanedItems);
+ }
+ }
+ }
+ }
+ }
+
+ context.SaveChanges();
+ transaction.Commit();
+ }
+
+ private static List<(ItemValueType MagicNumber, string Value)> GetItemValuesToSave(BaseItemDto item, List<string> inheritedTags)
+ {
+ var list = new List<(ItemValueType, string)>();
+
+ if (item is IHasArtist hasArtist)
+ {
+ list.AddRange(hasArtist.Artists.Select(i => ((ItemValueType)0, i)));
+ }
+
+ if (item is IHasAlbumArtist hasAlbumArtist)
+ {
+ list.AddRange(hasAlbumArtist.AlbumArtists.Select(i => (ItemValueType.AlbumArtist, i)));
+ }
+
+ list.AddRange(item.Genres.Select(i => (ItemValueType.Genre, i)));
+ list.AddRange(item.Studios.Select(i => (ItemValueType.Studios, i)));
+ list.AddRange(item.Tags.Select(i => (ItemValueType.Tags, i)));
+
+ list.AddRange(inheritedTags.Select(i => (ItemValueType.InheritedTags, i)));
+
+ list.RemoveAll(i => string.IsNullOrWhiteSpace(i.Item2));
+
+ return list;
+ }
+}