< Summary - Jellyfin

Information
Class: Jellyfin.Server.Implementations.Item.ItemCountService
Assembly: Jellyfin.Server.Implementations
File(s): /srv/git/jellyfin/Jellyfin.Server.Implementations/Item/ItemCountService.cs
Line coverage
87%
Covered lines: 361
Uncovered lines: 53
Coverable lines: 414
Total lines: 762
Line coverage: 87.1%
Branch coverage
69%
Covered branches: 100
Total branches: 144
Branch coverage: 69.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 1.7% (4/235) Branch coverage: 0% (0/75) Total lines: 4278/2/2026 - 12:17:28 AM Line coverage: 1.6% (4/236) Branch coverage: 0% (0/75) Total lines: 4308/3/2026 - 12:16:46 AM Line coverage: 1.6% (4/237) Branch coverage: 0% (0/75) Total lines: 4318/18/2026 - 12:17:16 AM Line coverage: 10.9% (26/238) Branch coverage: 6.6% (5/75) Total lines: 43210/29/2026 - 12:17:11 AM Line coverage: 87.6% (361/412) Branch coverage: 70.4% (100/142) Total lines: 75811/7/2026 - 12:19:31 AM Line coverage: 87.1% (361/414) Branch coverage: 69.4% (100/144) Total lines: 762 5/31/2026 - 12:15:44 AM Line coverage: 1.7% (4/235) Branch coverage: 0% (0/75) Total lines: 4278/2/2026 - 12:17:28 AM Line coverage: 1.6% (4/236) Branch coverage: 0% (0/75) Total lines: 4308/3/2026 - 12:16:46 AM Line coverage: 1.6% (4/237) Branch coverage: 0% (0/75) Total lines: 4318/18/2026 - 12:17:16 AM Line coverage: 10.9% (26/238) Branch coverage: 6.6% (5/75) Total lines: 43210/29/2026 - 12:17:11 AM Line coverage: 87.6% (361/412) Branch coverage: 70.4% (100/142) Total lines: 75811/7/2026 - 12:19:31 AM Line coverage: 87.1% (361/414) Branch coverage: 69.4% (100/144) Total lines: 762

Coverage delta

Coverage delta 77 -77

Metrics

File(s)

/srv/git/jellyfin/Jellyfin.Server.Implementations/Item/ItemCountService.cs

#LineLine coverage
 1#pragma warning disable RS0030 // Do not use banned APIs
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Globalization;
 6using System.Linq;
 7using Jellyfin.Data.Enums;
 8using Jellyfin.Database.Implementations;
 9using Jellyfin.Database.Implementations.Entities;
 10using Jellyfin.Extensions;
 11using MediaBrowser.Controller.Entities;
 12using MediaBrowser.Controller.Persistence;
 13using MediaBrowser.Model.Dto;
 14using Microsoft.EntityFrameworkCore;
 15
 16namespace Jellyfin.Server.Implementations.Item;
 17
 18/// <summary>
 19/// Provides item counting and played-status query operations.
 20/// </summary>
 21public class ItemCountService : IItemCountService
 22{
 23    private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
 24    private readonly IItemTypeLookup _itemTypeLookup;
 25    private readonly IItemQueryHelpers _queryHelpers;
 26
 27    /// <summary>
 28    /// Initializes a new instance of the <see cref="ItemCountService"/> class.
 29    /// </summary>
 30    /// <param name="dbProvider">The database context factory.</param>
 31    /// <param name="itemTypeLookup">The item type lookup.</param>
 32    /// <param name="queryHelpers">The shared query helpers.</param>
 33    public ItemCountService(
 34        IDbContextFactory<JellyfinDbContext> dbProvider,
 35        IItemTypeLookup itemTypeLookup,
 36        IItemQueryHelpers queryHelpers)
 37    {
 5038        _dbProvider = dbProvider;
 5039        _itemTypeLookup = itemTypeLookup;
 5040        _queryHelpers = queryHelpers;
 5041    }
 42
 43    /// <inheritdoc/>
 44    public int GetCount(InternalItemsQuery filter)
 45    {
 046        ArgumentNullException.ThrowIfNull(filter);
 047        _queryHelpers.PrepareFilterQuery(filter);
 48
 049        using var context = _dbProvider.CreateDbContext();
 050        var dbQuery = _queryHelpers.TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
 51
 052        return dbQuery.Count();
 053    }
 54
 55    /// <inheritdoc />
 56    public ItemCounts GetItemCounts(InternalItemsQuery filter)
 57    {
 058        ArgumentNullException.ThrowIfNull(filter);
 059        _queryHelpers.PrepareFilterQuery(filter);
 60
 061        using var context = _dbProvider.CreateDbContext();
 062        var dbQuery = _queryHelpers.TranslateQuery(context.BaseItems.AsNoTracking(), context, filter);
 63
 064        var counts = dbQuery
 065            .GroupBy(x => x.Type)
 066            .Select(x => new { x.Key, Count = x.Count() })
 067            .ToArray();
 68
 069        var lookup = _itemTypeLookup.BaseItemKindNames;
 070        var result = new ItemCounts
 071        {
 072            ItemCount = counts.Sum(c => c.Count)
 073        };
 74
 075        foreach (var count in counts)
 76        {
 077            if (string.Equals(count.Key, lookup[BaseItemKind.MusicAlbum], StringComparison.Ordinal))
 78            {
 079                result.AlbumCount = count.Count;
 80            }
 081            else if (string.Equals(count.Key, lookup[BaseItemKind.MusicArtist], StringComparison.Ordinal))
 82            {
 083                result.ArtistCount = count.Count;
 84            }
 085            else if (string.Equals(count.Key, lookup[BaseItemKind.Episode], StringComparison.Ordinal))
 86            {
 087                result.EpisodeCount = count.Count;
 88            }
 089            else if (string.Equals(count.Key, lookup[BaseItemKind.Movie], StringComparison.Ordinal))
 90            {
 091                result.MovieCount = count.Count;
 92            }
 093            else if (string.Equals(count.Key, lookup[BaseItemKind.MusicVideo], StringComparison.Ordinal))
 94            {
 095                result.MusicVideoCount = count.Count;
 96            }
 097            else if (string.Equals(count.Key, lookup[BaseItemKind.LiveTvProgram], StringComparison.Ordinal))
 98            {
 099                result.ProgramCount = count.Count;
 100            }
 0101            else if (string.Equals(count.Key, lookup[BaseItemKind.Series], StringComparison.Ordinal))
 102            {
 0103                result.SeriesCount = count.Count;
 104            }
 0105            else if (string.Equals(count.Key, lookup[BaseItemKind.Audio], StringComparison.Ordinal))
 106            {
 0107                result.SongCount = count.Count;
 108            }
 0109            else if (string.Equals(count.Key, lookup[BaseItemKind.Trailer], StringComparison.Ordinal))
 110            {
 0111                result.TrailerCount = count.Count;
 112            }
 0113            else if (string.Equals(count.Key, lookup[BaseItemKind.BoxSet], StringComparison.Ordinal))
 114            {
 0115                result.BoxSetCount = count.Count;
 116            }
 0117            else if (string.Equals(count.Key, lookup[BaseItemKind.Book], StringComparison.Ordinal))
 118            {
 0119                result.BookCount = count.Count;
 120            }
 0121            else if (string.Equals(count.Key, lookup[BaseItemKind.AudioBook], StringComparison.Ordinal))
 122            {
 0123                result.AudioBookCount = count.Count;
 124            }
 125        }
 126
 0127        return result;
 0128    }
 129
 130    /// <inheritdoc />
 131    public ItemCounts GetItemCountsForNameItem(BaseItemKind kind, Guid id, BaseItemKind[] relatedItemKinds, InternalItem
 132    {
 20133        return GetItemCountsForNameItems(kind, [id], relatedItemKinds, accessFilter)[id];
 134    }
 135
 136    private static ItemValueType[] GetItemValueTypes(BaseItemKind kind)
 33137        => kind switch
 33138        {
 5139            BaseItemKind.MusicArtist => [ItemValueType.Artist, ItemValueType.AlbumArtist],
 20140            BaseItemKind.Genre or BaseItemKind.MusicGenre => [ItemValueType.Genre],
 0141            BaseItemKind.Studio => [ItemValueType.Studios],
 8142            _ => []
 33143        };
 144
 145    /// <inheritdoc />
 146    public Dictionary<Guid, ItemCounts> GetItemCountsForNameItems(BaseItemKind kind, IReadOnlyList<Guid> ids, BaseItemKi
 147    {
 34148        ArgumentNullException.ThrowIfNull(ids);
 34149        ArgumentNullException.ThrowIfNull(relatedItemKinds);
 34150        ArgumentNullException.ThrowIfNull(accessFilter);
 151
 34152        var result = new Dictionary<Guid, ItemCounts>();
 34153        if (ids.Count == 0)
 154        {
 0155            return result;
 156        }
 157
 34158        using var context = _dbProvider.CreateDbContext();
 159
 34160        var idsArray = ids as Guid[] ?? ids.ToArray();
 34161        var nameItems = context.BaseItems.AsNoTracking()
 34162            .WhereOneOrMany(idsArray, e => e.Id)
 34163            .Select(e => new NameItem(e.Id, e.Name, e.CleanName))
 34164            .ToArray();
 165
 80272166        foreach (var id in ids)
 167        {
 40102168            result[id] = new ItemCounts();
 169        }
 170
 34171        if (nameItems.Length == 0)
 172        {
 1173            return result;
 174        }
 175
 33176        var typeNames = relatedItemKinds.Select(k => _itemTypeLookup.BaseItemKindNames[k]).ToArray();
 33177        var related = _queryHelpers.ApplyAccessFiltering(
 33178            context,
 33179            context.BaseItems.AsNoTracking().Where(e => typeNames.Contains(e.Type)),
 33180            accessFilter);
 181
 33182        var valueTypes = GetItemValueTypes(kind);
 33183        if (valueTypes.Length > 0)
 184        {
 25185            CountByItemValue(context, related, kind, relatedItemKinds, valueTypes, nameItems, result);
 186        }
 8187        else if (kind == BaseItemKind.Person)
 188        {
 3189            CountByPersonName(context, related, nameItems, result);
 190        }
 5191        else if (kind == BaseItemKind.Year)
 192        {
 5193            CountByProductionYear(related, nameItems, result);
 194        }
 195
 33196        return result;
 34197    }
 198
 199    private void CountByItemValue(
 200        JellyfinDbContext context,
 201        IQueryable<BaseItemEntity> related,
 202        BaseItemKind kind,
 203        BaseItemKind[] relatedItemKinds,
 204        ItemValueType[] valueTypes,
 205        NameItem[] nameItems,
 206        Dictionary<Guid, ItemCounts> result)
 207    {
 25208        var cleanNames = nameItems
 25209            .Select(n => n.CleanName)
 25210            .OfType<string>()
 25211            .Distinct(StringComparer.Ordinal)
 25212            .ToArray();
 213
 25214        if (cleanNames.Length == 0)
 215        {
 0216            return;
 217        }
 218
 25219        var grouped = context.ItemValuesMap.AsNoTracking()
 25220            .Where(ivm => valueTypes.Contains(ivm.ItemValue.Type))
 25221            .WhereOneOrMany(cleanNames, ivm => ivm.ItemValue.CleanValue)
 25222            .Join(related, ivm => ivm.ItemId, e => e.Id, (ivm, e) => new { ivm.ItemValue.CleanValue, e.Type, e.Id })
 25223            .GroupBy(x => new { x.CleanValue, x.Type })
 25224            .Select(g => new { g.Key.CleanValue, g.Key.Type, Count = g.Select(x => x.Id).Distinct().Count() })
 25225            .ToArray();
 226
 25227        var byCleanName = grouped
 25228            .GroupBy(g => g.CleanValue, StringComparer.Ordinal)
 25229            .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray(), StringComparer.Ordinal);
 230
 25231        var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series];
 25232        var episodeRollUp = RollsUpEpisodes(kind, relatedItemKinds)
 25233                && Array.Exists(grouped, g => string.Equals(g.Type, seriesTypeName, StringComparison.Ordinal))
 25234            ? CountEpisodesOfTaggedSeriesByCleanName(context, related, valueTypes, cleanNames)
 25235            : null;
 236
 232237        foreach (var nameItem in nameItems)
 238        {
 91239            if (nameItem.CleanName is null || !byCleanName.TryGetValue(nameItem.CleanName, out var counts))
 240            {
 241                continue;
 242            }
 243
 27244            var itemCounts = ItemCountBuilder.Build(_itemTypeLookup, counts);
 245
 27246            if (episodeRollUp is not null)
 247            {
 8248                var rollUp = episodeRollUp.GetValueOrDefault(nameItem.CleanName);
 249
 250                // Episodes of a tagged series count towards it even when untagged themselves, and
 251                // a tagged episode of a tagged series must not be counted a second time.
 8252                var directEpisodeCount = itemCounts.EpisodeCount - rollUp.TaggedEpisodesOfTaggedSeries;
 8253                ItemCountBuilder.SetEpisodeCount(itemCounts, rollUp.EpisodesOfTaggedSeries + directEpisodeCount);
 254            }
 255
 27256            result[nameItem.Id] = itemCounts;
 257        }
 25258    }
 259
 260    private void CountByPersonName(
 261        JellyfinDbContext context,
 262        IQueryable<BaseItemEntity> related,
 263        NameItem[] nameItems,
 264        Dictionary<Guid, ItemCounts> result)
 265    {
 3266        var names = nameItems
 3267            .Select(n => n.Name)
 3268            .OfType<string>()
 3269            .Distinct(StringComparer.Ordinal)
 3270            .ToArray();
 271
 3272        if (names.Length == 0)
 273        {
 0274            return;
 275        }
 276
 3277        var grouped = context.PeopleBaseItemMap.AsNoTracking()
 3278            .WhereOneOrMany(names, m => m.People.Name)
 3279            .Join(related, m => m.ItemId, e => e.Id, (m, e) => new { m.People.Name, e.Type, e.Id })
 3280            .GroupBy(x => new { x.Name, x.Type })
 3281            // A person can be credited on one item more than once, in different roles.
 3282            .Select(g => new { g.Key.Name, g.Key.Type, Count = g.Select(x => x.Id).Distinct().Count() })
 3283            .ToArray();
 284
 3285        ApplyGroupedCounts(nameItems, n => n.Name, grouped.Select(g => (g.Name, g.Type, g.Count)), result);
 3286    }
 287
 288    private void CountByProductionYear(
 289        IQueryable<BaseItemEntity> related,
 290        NameItem[] nameItems,
 291        Dictionary<Guid, ItemCounts> result)
 292    {
 5293        var years = new List<int>();
 22294        foreach (var nameItem in nameItems)
 295        {
 6296            if (int.TryParse(nameItem.Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)
 6297                && !years.Contains(year))
 298            {
 6299                years.Add(year);
 300            }
 301        }
 302
 5303        if (years.Count == 0)
 304        {
 0305            return;
 306        }
 307
 308        // No join, so no row can be reached twice and a plain count is the distinct count.
 5309        var grouped = related
 5310            .Where(e => e.ProductionYear != null)
 5311            .WhereOneOrMany(years, e => e.ProductionYear!.Value)
 5312            .GroupBy(e => new { Year = e.ProductionYear!.Value, e.Type })
 5313            .Select(g => new { g.Key.Year, g.Key.Type, Count = g.Count() })
 5314            .ToArray();
 315
 5316        var byYear = grouped
 5317            .GroupBy(g => g.Year)
 5318            .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray());
 319
 22320        foreach (var nameItem in nameItems)
 321        {
 6322            if (int.TryParse(nameItem.Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year)
 6323                && byYear.TryGetValue(year, out var counts))
 324            {
 6325                result[nameItem.Id] = ItemCountBuilder.Build(_itemTypeLookup, counts);
 326            }
 327        }
 5328    }
 329
 330    private void ApplyGroupedCounts(
 331        NameItem[] nameItems,
 332        Func<NameItem, string?> keySelector,
 333        IEnumerable<(string Key, string Type, int Count)> grouped,
 334        Dictionary<Guid, ItemCounts> result)
 335    {
 3336        var byKey = grouped
 3337            .GroupBy(g => g.Key, StringComparer.Ordinal)
 3338            .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray(), StringComparer.Ordinal);
 339
 14340        foreach (var nameItem in nameItems)
 341        {
 4342            var key = keySelector(nameItem);
 4343            if (key is not null && byKey.TryGetValue(key, out var counts))
 344            {
 4345                result[nameItem.Id] = ItemCountBuilder.Build(_itemTypeLookup, counts);
 346            }
 347        }
 3348    }
 349
 350    private static bool RollsUpEpisodes(BaseItemKind kind, BaseItemKind[] relatedItemKinds)
 25351        => kind is BaseItemKind.Studio or BaseItemKind.Genre or BaseItemKind.MusicGenre
 25352            && relatedItemKinds.Contains(BaseItemKind.Episode)
 25353            && relatedItemKinds.Contains(BaseItemKind.Series);
 354
 355    private Dictionary<string, (int EpisodesOfTaggedSeries, int TaggedEpisodesOfTaggedSeries)> CountEpisodesOfTaggedSeri
 356        JellyfinDbContext context,
 357        IQueryable<BaseItemEntity> related,
 358        ItemValueType[] valueTypes,
 359        string[] cleanNames)
 360    {
 5361        var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series];
 5362        var episodeTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Episode];
 363
 5364        var taggedValues = context.ItemValuesMap.AsNoTracking()
 5365            .Where(ivm => valueTypes.Contains(ivm.ItemValue.Type))
 5366            .WhereOneOrMany(cleanNames, ivm => ivm.ItemValue.CleanValue);
 367
 368        // The series carrying each clean name. Distinct, because one item can be mapped to the
 369        // same clean name once per value type.
 5370        var taggedSeries = taggedValues
 5371            .Join(
 5372                related.Where(e => e.Type == seriesTypeName),
 5373                ivm => ivm.ItemId,
 5374                e => e.Id,
 5375                (ivm, e) => new { ivm.ItemValue.CleanValue, SeriesId = e.Id })
 5376            .Distinct();
 377
 5378        var episodes = related.Where(e => e.Type == episodeTypeName && e.SeriesId != null);
 379
 5380        var episodesOfTaggedSeries = taggedSeries
 5381            .Join(episodes, s => s.SeriesId, e => e.SeriesId!.Value, (s, e) => new { s.CleanValue, e.Id })
 5382            .GroupBy(x => x.CleanValue)
 5383            .Select(g => new { CleanValue = g.Key, Count = g.Select(x => x.Id).Distinct().Count() })
 5384            .ToArray();
 385
 386        // Episodes that carry the clean name themselves *and* belong to a series carrying it. The
 387        // roll-up already counts those, so they have to come off the directly tagged ones.
 5388        var taggedEpisodesOfTaggedSeries = taggedValues
 5389            .Join(episodes, ivm => ivm.ItemId, e => e.Id, (ivm, e) => new { ivm.ItemValue.CleanValue, e.Id, e.SeriesId }
 5390            .Join(
 5391                taggedSeries,
 5392                e => new { e.CleanValue, SeriesId = e.SeriesId!.Value },
 5393                s => new { s.CleanValue, s.SeriesId },
 5394                (e, s) => new { e.CleanValue, e.Id })
 5395            .GroupBy(x => x.CleanValue)
 5396            .Select(g => new { CleanValue = g.Key, Count = g.Select(x => x.Id).Distinct().Count() })
 5397            .ToArray();
 398
 5399        var taggedLookup = taggedEpisodesOfTaggedSeries
 5400            .ToDictionary(x => x.CleanValue, x => x.Count, StringComparer.Ordinal);
 401
 402        // Every clean name in taggedLookup came from an episode of a tagged series, so it always
 403        // has a row in episodesOfTaggedSeries too - no second merge pass is needed.
 5404        var result = new Dictionary<string, (int EpisodesOfTaggedSeries, int TaggedEpisodesOfTaggedSeries)>(StringCompar
 20405        foreach (var entry in episodesOfTaggedSeries)
 406        {
 5407            result[entry.CleanValue] = (entry.Count, taggedLookup.GetValueOrDefault(entry.CleanValue));
 408        }
 409
 5410        return result;
 411    }
 412
 413    /// <inheritdoc/>
 414    public int GetPlayedCount(InternalItemsQuery filter, Guid ancestorId)
 415    {
 5416        ArgumentNullException.ThrowIfNull(filter);
 5417        ArgumentNullException.ThrowIfNull(filter.User);
 5418        using var dbContext = _dbProvider.CreateDbContext();
 419
 5420        var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId);
 5421        return baseQuery.Count(DescendantQueryHelper.IsPlayedBy(filter.User.Id));
 5422    }
 423
 424    /// <inheritdoc/>
 425    public int GetTotalCount(InternalItemsQuery filter, Guid ancestorId)
 426    {
 3427        ArgumentNullException.ThrowIfNull(filter);
 3428        using var dbContext = _dbProvider.CreateDbContext();
 429
 3430        var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId);
 3431        return baseQuery.Count();
 3432    }
 433
 434    /// <inheritdoc/>
 435    public (int Played, int Total) GetPlayedAndTotalCount(InternalItemsQuery filter, Guid ancestorId)
 436    {
 5437        ArgumentNullException.ThrowIfNull(filter);
 5438        ArgumentNullException.ThrowIfNull(filter.User);
 5439        using var dbContext = _dbProvider.CreateDbContext();
 440
 5441        var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId);
 5442        return GetPlayedAndTotalCountFromQuery(baseQuery, filter.User.Id);
 5443    }
 444
 445    private IQueryable<BaseItemEntity> BuildGroupedDescendantsQuery(JellyfinDbContext dbContext, InternalItemsQuery filt
 446    {
 13447        var ancestorIds = GetPresentationKeyGroups(dbContext, [ancestorId])[ancestorId];
 13448        var descendantIds = DescendantQueryHelper.GetAllDescendantIdsBatch(dbContext, ancestorIds).ToArray();
 449
 13450        var baseQuery = dbContext.BaseItems
 13451            .AsNoTracking()
 13452            .WhereOneOrMany(descendantIds, b => b.Id)
 13453            .Where(DescendantQueryHelper.IsCountableLeaf);
 454
 13455        return _queryHelpers.ApplyAccessFiltering(dbContext, baseQuery, filter);
 456    }
 457
 458    /// <inheritdoc/>
 459    public (int Played, int Total) GetPlayedAndTotalCountFromLinkedChildren(InternalItemsQuery filter, Guid parentId)
 460    {
 1461        ArgumentNullException.ThrowIfNull(filter);
 1462        ArgumentNullException.ThrowIfNull(filter.User);
 1463        using var dbContext = _dbProvider.CreateDbContext();
 464
 1465        var allDescendantIds = DescendantQueryHelper.GetAllDescendantIdsBatch(dbContext, [parentId]).ToArray();
 1466        var baseQuery = dbContext.BaseItems
 1467            .WhereOneOrMany(allDescendantIds, b => b.Id)
 1468            .Where(DescendantQueryHelper.IsCountableLeaf);
 1469        baseQuery = _queryHelpers.ApplyAccessFiltering(dbContext, baseQuery, filter);
 470
 1471        return GetPlayedAndTotalCountFromQuery(baseQuery, filter.User.Id);
 1472    }
 473
 474    /// <inheritdoc/>
 475    public Dictionary<Guid, int> GetChildCountBatch(IReadOnlyList<Guid> parentIds, User? user)
 476    {
 14477        ArgumentNullException.ThrowIfNull(parentIds);
 478
 14479        if (parentIds.Count == 0)
 480        {
 0481            return new Dictionary<Guid, int>();
 482        }
 483
 14484        using var dbContext = _dbProvider.CreateDbContext();
 485
 14486        var parentIdsArray = parentIds.ToArray();
 487
 14488        var includeVirtual = user is null || user.DisplayMissingEpisodes;
 489
 14490        var accessibleItems = dbContext.BaseItems.AsNoTracking();
 14491        if (user is null)
 492        {
 493            // Access filtering is what would otherwise drop an alternate version, and a child count
 494            // must not report a title twice just because no user was passed in.
 6495            accessibleItems = accessibleItems.Where(DescendantQueryHelper.IsDistinctLibraryItem);
 496        }
 497        else
 498        {
 8499            accessibleItems = _queryHelpers.ApplyAccessFiltering(dbContext, accessibleItems, new InternalItemsQuery(user
 500        }
 501
 14502        var hierarchicalCounts = accessibleItems
 14503            .Where(b => b.ParentId.HasValue && !b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem))
 14504            .WhereOneOrMany(parentIdsArray, b => b.ParentId!.Value)
 14505            .GroupBy(b => b.ParentId!.Value)
 14506            .Select(g => new { ParentId = g.Key, Count = g.Count() })
 14507            .ToDictionary(x => x.ParentId, x => x.Count);
 508
 509        // An episode is a child of its season even when it is not stored under one: with a flat
 510        // structure ParentId points at the series, so counting by ParentId alone leaves the season
 511        // empty and counts its episodes towards the series instead.
 14512        var seasonCounts = accessibleItems
 14513            .Where(b => b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem))
 14514            .WhereOneOrMany(parentIdsArray, b => b.SeasonId!.Value)
 14515            .GroupBy(b => b.SeasonId!.Value)
 14516            .Select(g => new { SeasonId = g.Key, Count = g.Count() })
 14517            .ToDictionary(x => x.SeasonId, x => x.Count);
 518
 519        // A linked child counts only when the item it points at is one the user may open.
 14520        var linkedCounts = dbContext.LinkedChildren
 14521            .WhereOneOrMany(parentIdsArray, lc => lc.ParentId)
 14522            .Join(accessibleItems, lc => lc.ChildId, b => b.Id, (lc, b) => lc.ParentId)
 14523            .GroupBy(parentId => parentId)
 14524            .Select(g => new { ParentId = g.Key, Count = g.Count() })
 14525            .ToDictionary(x => x.ParentId, x => x.Count);
 526
 14527        var mergedChildCounts = GetMergedChildCounts(dbContext, accessibleItems, parentIdsArray, includeVirtual);
 528
 14529        var result = new Dictionary<Guid, int>();
 80064530        foreach (var parentId in parentIds)
 531        {
 40018532            if (mergedChildCounts.TryGetValue(parentId, out var mergedCount))
 533            {
 2534                result[parentId] = mergedCount;
 2535                continue;
 536            }
 537
 40016538            var hierarchicalCount = hierarchicalCounts.GetValueOrDefault(parentId, 0)
 40016539                + seasonCounts.GetValueOrDefault(parentId, 0);
 40016540            var linkedCount = linkedCounts.GetValueOrDefault(parentId, 0);
 541
 40016542            result[parentId] = linkedCount > 0 ? linkedCount : hierarchicalCount;
 543        }
 544
 14545        return result;
 14546    }
 547
 548    private static Dictionary<Guid, int> GetMergedChildCounts(
 549        JellyfinDbContext dbContext,
 550        IQueryable<BaseItemEntity> accessibleItems,
 551        IReadOnlyList<Guid> parentIds,
 552        bool includeVirtual)
 553    {
 14554        var mergedGroups = GetPresentationKeyGroups(dbContext, parentIds)
 14555            .Where(group => group.Value.Count > 1)
 14556            .ToArray();
 557
 14558        if (mergedGroups.Length == 0)
 559        {
 13560            return [];
 561        }
 562
 563        // Only merged folders.
 1564        var memberIds = mergedGroups.SelectMany(group => group.Value).Distinct().ToArray();
 1565        var children = accessibleItems
 1566            .Where(b => b.ParentId.HasValue && !b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem))
 1567            .WhereOneOrMany(memberIds, b => b.ParentId!.Value)
 1568            .Select(b => new { ParentId = b.ParentId!.Value, b.Id, b.PresentationUniqueKey })
 1569            .ToArray()
 1570            .Concat(accessibleItems
 1571                .Where(b => b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem))
 1572                .WhereOneOrMany(memberIds, b => b.SeasonId!.Value)
 1573                .Select(b => new { ParentId = b.SeasonId!.Value, b.Id, b.PresentationUniqueKey })
 1574                .ToArray())
 1575            .GroupBy(b => b.ParentId)
 1576            .ToDictionary(
 1577                g => g.Key,
 1578                g => g.Select(b => string.IsNullOrEmpty(b.PresentationUniqueKey)
 1579                    ? b.Id.ToString("N", CultureInfo.InvariantCulture)
 1580                    : b.PresentationUniqueKey).ToArray());
 581
 1582        var result = new Dictionary<Guid, int>();
 6583        foreach (var (parentId, members) in mergedGroups)
 584        {
 2585            var childKeys = new HashSet<string>(StringComparer.Ordinal);
 12586            foreach (var member in members)
 587            {
 4588                if (children.TryGetValue(member, out var keys))
 589                {
 4590                    childKeys.UnionWith(keys);
 591                }
 592            }
 593
 2594            result[parentId] = childKeys.Count;
 595        }
 596
 1597        return result;
 598    }
 599
 600    /// <inheritdoc/>
 601    public Dictionary<Guid, (int Played, int Total)> GetPlayedAndTotalCountBatch(IReadOnlyList<Guid> folderIds, User use
 602    {
 3603        ArgumentNullException.ThrowIfNull(folderIds);
 3604        ArgumentNullException.ThrowIfNull(user);
 605
 3606        if (folderIds.Count == 0)
 607        {
 0608            return new Dictionary<Guid, (int Played, int Total)>();
 609        }
 610
 3611        using var dbContext = _dbProvider.CreateDbContext();
 3612        var filter = new InternalItemsQuery(user);
 3613        var userId = user.Id;
 614
 615        // Merged series and seasons are stored as one row per folder-item sharing a presentation key.
 3616        var groups = GetPresentationKeyGroups(dbContext, folderIds);
 3617        var folderIdsArray = groups.Values.SelectMany(members => members).Distinct().ToArray();
 618
 3619        var leafItems = dbContext.BaseItems
 3620            .Where(DescendantQueryHelper.IsCountableLeaf);
 3621        leafItems = _queryHelpers.ApplyAccessFiltering(dbContext, leafItems, filter);
 622
 3623        var playedLeafItems = leafItems
 3624            .Select(DescendantQueryHelper.PlayedStateBy(userId));
 625
 3626        var ancestorLeaves = dbContext.AncestorIds
 3627            .WhereOneOrMany(folderIdsArray, a => a.ParentItemId)
 3628            .Join(
 3629                playedLeafItems,
 3630                a => a.ItemId,
 3631                b => b.Id,
 3632                (a, b) => new { FolderId = a.ParentItemId, b.Id, b.Played });
 633
 3634        var linkedLeaves = dbContext.LinkedChildren
 3635            .WhereOneOrMany(folderIdsArray, lc => lc.ParentId)
 3636            .Join(
 3637                playedLeafItems,
 3638                lc => lc.ChildId,
 3639                b => b.Id,
 3640                (lc, b) => new { FolderId = lc.ParentId, b.Id, b.Played });
 641
 3642        var linkedFolderLeaves = dbContext.LinkedChildren
 3643            .WhereOneOrMany(folderIdsArray, lc => lc.ParentId)
 3644            .Join(
 3645                dbContext.BaseItems.Where(b => b.IsFolder),
 3646                lc => lc.ChildId,
 3647                b => b.Id,
 3648                (lc, b) => new { lc.ParentId, FolderChildId = b.Id })
 3649            .Join(
 3650                dbContext.AncestorIds,
 3651                x => x.FolderChildId,
 3652                a => a.ParentItemId,
 3653                (x, a) => new { x.ParentId, DescendantId = a.ItemId })
 3654            .Join(
 3655                playedLeafItems,
 3656                x => x.DescendantId,
 3657                b => b.Id,
 3658                (x, b) => new { FolderId = x.ParentId, b.Id, b.Played });
 659
 3660        var countsByFolder = ancestorLeaves
 3661            .Union(linkedLeaves)
 3662            .Union(linkedFolderLeaves)
 3663            .GroupBy(x => x.FolderId)
 3664            .Select(g => new
 3665            {
 3666                FolderId = g.Key,
 3667                Total = g.Select(x => x.Id).Distinct().Count(),
 3668                Played = g.Where(x => x.Played).Select(x => x.Id).Distinct().Count()
 3669            })
 3670            .ToDictionary(x => x.FolderId, x => (x.Played, x.Total));
 671
 3672        var results = new Dictionary<Guid, (int Played, int Total)>();
 12673        foreach (var (folderId, members) in groups)
 674        {
 3675            var played = 0;
 3676            var total = 0;
 677
 678            // Members of a group are distinct folders, so their leaves cannot overlap.
 14679            foreach (var member in members)
 680            {
 4681                if (countsByFolder.TryGetValue(member, out var counts))
 682                {
 4683                    played += counts.Played;
 4684                    total += counts.Total;
 685                }
 686            }
 687
 3688            if (total > 0 || played > 0)
 689            {
 3690                results[folderId] = (played, total);
 691            }
 692        }
 693
 3694        return results;
 3695    }
 696
 697    private static Dictionary<Guid, List<Guid>> GetPresentationKeyGroups(JellyfinDbContext dbContext, IReadOnlyList<Guid
 698    {
 30699        var requested = dbContext.BaseItems
 30700            .AsNoTracking()
 30701            .WhereOneOrMany(folderIds, e => e.Id)
 30702            .Select(e => new { e.Id, e.PresentationUniqueKey })
 30703            .ToArray();
 704
 30705        var keys = requested
 30706            .Select(e => e.PresentationUniqueKey)
 30707            .Where(key => !string.IsNullOrEmpty(key))
 30708            .Distinct(StringComparer.Ordinal)
 30709            .ToArray();
 710
 711        // Every item that is not merged carries a key derived from its own id, so in the common case
 712        // each group resolves back to the single folder that was asked for.
 30713        var membersByKey = keys.Length == 0
 30714            ? []
 30715            : dbContext.BaseItems
 30716                .AsNoTracking()
 30717                .Where(e => e.IsFolder)
 30718                .WhereOneOrMany(keys, e => e.PresentationUniqueKey!)
 30719                .Select(e => new { e.Id, Key = e.PresentationUniqueKey! })
 30720                .ToArray()
 30721                .GroupBy(e => e.Key, StringComparer.Ordinal)
 30722                .ToDictionary(g => g.Key, g => g.Select(e => e.Id).ToList(), StringComparer.Ordinal);
 723
 30724        var keyById = requested.ToDictionary(e => e.Id, e => e.PresentationUniqueKey);
 30725        var groups = new Dictionary<Guid, List<Guid>>();
 80128726        foreach (var folderId in folderIds)
 727        {
 40034728            groups[folderId] = keyById.TryGetValue(folderId, out var key)
 40034729                && !string.IsNullOrEmpty(key)
 40034730                && membersByKey.TryGetValue(key, out var members)
 40034731                && members.Count > 0
 40034732                    ? members
 40034733                    : [folderId];
 734        }
 735
 30736        return groups;
 737    }
 738
 739    private static (int Played, int Total) GetPlayedAndTotalCountFromQuery(IQueryable<BaseItemEntity> query, Guid userId
 740    {
 6741        var result = query
 6742            .Select(DescendantQueryHelper.IsPlayedBy(userId))
 6743            .GroupBy(_ => 1)
 6744            .OrderBy(g => g.Key)
 6745            .Select(g => new
 6746            {
 6747                Total = g.Count(),
 6748                Played = g.Count(isPlayed => isPlayed)
 6749            })
 6750            .FirstOrDefault();
 751
 6752        return result is null ? (0, 0) : (result.Played, result.Total);
 753    }
 754
 755    /// <summary>
 756    /// A by-name item, reduced to the three columns the counting keys off.
 757    /// </summary>
 758    /// <param name="Id">The id of the by-name item.</param>
 759    /// <param name="Name">The name of the by-name item.</param>
 760    /// <param name="CleanName">The cleaned name of the by-name item.</param>
 761    private sealed record NameItem(Guid Id, string? Name, string? CleanName);
 762}

Methods/Properties

.ctor(Microsoft.EntityFrameworkCore.IDbContextFactory`1<Jellyfin.Database.Implementations.JellyfinDbContext>,MediaBrowser.Controller.Persistence.IItemTypeLookup,MediaBrowser.Controller.Persistence.IItemQueryHelpers)
GetCount(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemCounts(MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemCountsForNameItem(Jellyfin.Data.Enums.BaseItemKind,System.Guid,Jellyfin.Data.Enums.BaseItemKind[],MediaBrowser.Controller.Entities.InternalItemsQuery)
GetItemValueTypes(Jellyfin.Data.Enums.BaseItemKind)
GetItemCountsForNameItems(Jellyfin.Data.Enums.BaseItemKind,System.Collections.Generic.IReadOnlyList`1<System.Guid>,Jellyfin.Data.Enums.BaseItemKind[],MediaBrowser.Controller.Entities.InternalItemsQuery)
CountByItemValue(Jellyfin.Database.Implementations.JellyfinDbContext,System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,Jellyfin.Data.Enums.BaseItemKind,Jellyfin.Data.Enums.BaseItemKind[],Jellyfin.Database.Implementations.Entities.ItemValueType[],Jellyfin.Server.Implementations.Item.ItemCountService/NameItem[],System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Model.Dto.ItemCounts>)
CountByPersonName(Jellyfin.Database.Implementations.JellyfinDbContext,System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,Jellyfin.Server.Implementations.Item.ItemCountService/NameItem[],System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Model.Dto.ItemCounts>)
CountByProductionYear(System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,Jellyfin.Server.Implementations.Item.ItemCountService/NameItem[],System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Model.Dto.ItemCounts>)
ApplyGroupedCounts(Jellyfin.Server.Implementations.Item.ItemCountService/NameItem[],System.Func`2<Jellyfin.Server.Implementations.Item.ItemCountService/NameItem,System.String>,System.Collections.Generic.IEnumerable`1<System.ValueTuple`3<System.String,System.String,System.Int32>>,System.Collections.Generic.Dictionary`2<System.Guid,MediaBrowser.Model.Dto.ItemCounts>)
RollsUpEpisodes(Jellyfin.Data.Enums.BaseItemKind,Jellyfin.Data.Enums.BaseItemKind[])
CountEpisodesOfTaggedSeriesByCleanName(Jellyfin.Database.Implementations.JellyfinDbContext,System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,Jellyfin.Database.Implementations.Entities.ItemValueType[],System.String[])
GetPlayedCount(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Guid)
GetTotalCount(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Guid)
GetPlayedAndTotalCount(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Guid)
BuildGroupedDescendantsQuery(Jellyfin.Database.Implementations.JellyfinDbContext,MediaBrowser.Controller.Entities.InternalItemsQuery,System.Guid)
GetPlayedAndTotalCountFromLinkedChildren(MediaBrowser.Controller.Entities.InternalItemsQuery,System.Guid)
GetChildCountBatch(System.Collections.Generic.IReadOnlyList`1<System.Guid>,Jellyfin.Database.Implementations.Entities.User)
GetMergedChildCounts(Jellyfin.Database.Implementations.JellyfinDbContext,System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,System.Collections.Generic.IReadOnlyList`1<System.Guid>,System.Boolean)
GetPlayedAndTotalCountBatch(System.Collections.Generic.IReadOnlyList`1<System.Guid>,Jellyfin.Database.Implementations.Entities.User)
GetPresentationKeyGroups(Jellyfin.Database.Implementations.JellyfinDbContext,System.Collections.Generic.IReadOnlyList`1<System.Guid>)
GetPlayedAndTotalCountFromQuery(System.Linq.IQueryable`1<Jellyfin.Database.Implementations.Entities.BaseItemEntity>,System.Guid)