| | | 1 | | #pragma warning disable RS0030 // Do not use banned APIs |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Linq; |
| | | 7 | | using Jellyfin.Data.Enums; |
| | | 8 | | using Jellyfin.Database.Implementations; |
| | | 9 | | using Jellyfin.Database.Implementations.Entities; |
| | | 10 | | using Jellyfin.Extensions; |
| | | 11 | | using MediaBrowser.Controller.Entities; |
| | | 12 | | using MediaBrowser.Controller.Persistence; |
| | | 13 | | using MediaBrowser.Model.Dto; |
| | | 14 | | using Microsoft.EntityFrameworkCore; |
| | | 15 | | |
| | | 16 | | namespace Jellyfin.Server.Implementations.Item; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Provides item counting and played-status query operations. |
| | | 20 | | /// </summary> |
| | | 21 | | public 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 | | { |
| | 50 | 38 | | _dbProvider = dbProvider; |
| | 50 | 39 | | _itemTypeLookup = itemTypeLookup; |
| | 50 | 40 | | _queryHelpers = queryHelpers; |
| | 50 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <inheritdoc/> |
| | | 44 | | public int GetCount(InternalItemsQuery filter) |
| | | 45 | | { |
| | 0 | 46 | | ArgumentNullException.ThrowIfNull(filter); |
| | 0 | 47 | | _queryHelpers.PrepareFilterQuery(filter); |
| | | 48 | | |
| | 0 | 49 | | using var context = _dbProvider.CreateDbContext(); |
| | 0 | 50 | | var dbQuery = _queryHelpers.TranslateQuery(context.BaseItems.AsNoTracking(), context, filter); |
| | | 51 | | |
| | 0 | 52 | | return dbQuery.Count(); |
| | 0 | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <inheritdoc /> |
| | | 56 | | public ItemCounts GetItemCounts(InternalItemsQuery filter) |
| | | 57 | | { |
| | 0 | 58 | | ArgumentNullException.ThrowIfNull(filter); |
| | 0 | 59 | | _queryHelpers.PrepareFilterQuery(filter); |
| | | 60 | | |
| | 0 | 61 | | using var context = _dbProvider.CreateDbContext(); |
| | 0 | 62 | | var dbQuery = _queryHelpers.TranslateQuery(context.BaseItems.AsNoTracking(), context, filter); |
| | | 63 | | |
| | 0 | 64 | | var counts = dbQuery |
| | 0 | 65 | | .GroupBy(x => x.Type) |
| | 0 | 66 | | .Select(x => new { x.Key, Count = x.Count() }) |
| | 0 | 67 | | .ToArray(); |
| | | 68 | | |
| | 0 | 69 | | var lookup = _itemTypeLookup.BaseItemKindNames; |
| | 0 | 70 | | var result = new ItemCounts |
| | 0 | 71 | | { |
| | 0 | 72 | | ItemCount = counts.Sum(c => c.Count) |
| | 0 | 73 | | }; |
| | | 74 | | |
| | 0 | 75 | | foreach (var count in counts) |
| | | 76 | | { |
| | 0 | 77 | | if (string.Equals(count.Key, lookup[BaseItemKind.MusicAlbum], StringComparison.Ordinal)) |
| | | 78 | | { |
| | 0 | 79 | | result.AlbumCount = count.Count; |
| | | 80 | | } |
| | 0 | 81 | | else if (string.Equals(count.Key, lookup[BaseItemKind.MusicArtist], StringComparison.Ordinal)) |
| | | 82 | | { |
| | 0 | 83 | | result.ArtistCount = count.Count; |
| | | 84 | | } |
| | 0 | 85 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Episode], StringComparison.Ordinal)) |
| | | 86 | | { |
| | 0 | 87 | | result.EpisodeCount = count.Count; |
| | | 88 | | } |
| | 0 | 89 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Movie], StringComparison.Ordinal)) |
| | | 90 | | { |
| | 0 | 91 | | result.MovieCount = count.Count; |
| | | 92 | | } |
| | 0 | 93 | | else if (string.Equals(count.Key, lookup[BaseItemKind.MusicVideo], StringComparison.Ordinal)) |
| | | 94 | | { |
| | 0 | 95 | | result.MusicVideoCount = count.Count; |
| | | 96 | | } |
| | 0 | 97 | | else if (string.Equals(count.Key, lookup[BaseItemKind.LiveTvProgram], StringComparison.Ordinal)) |
| | | 98 | | { |
| | 0 | 99 | | result.ProgramCount = count.Count; |
| | | 100 | | } |
| | 0 | 101 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Series], StringComparison.Ordinal)) |
| | | 102 | | { |
| | 0 | 103 | | result.SeriesCount = count.Count; |
| | | 104 | | } |
| | 0 | 105 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Audio], StringComparison.Ordinal)) |
| | | 106 | | { |
| | 0 | 107 | | result.SongCount = count.Count; |
| | | 108 | | } |
| | 0 | 109 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Trailer], StringComparison.Ordinal)) |
| | | 110 | | { |
| | 0 | 111 | | result.TrailerCount = count.Count; |
| | | 112 | | } |
| | 0 | 113 | | else if (string.Equals(count.Key, lookup[BaseItemKind.BoxSet], StringComparison.Ordinal)) |
| | | 114 | | { |
| | 0 | 115 | | result.BoxSetCount = count.Count; |
| | | 116 | | } |
| | 0 | 117 | | else if (string.Equals(count.Key, lookup[BaseItemKind.Book], StringComparison.Ordinal)) |
| | | 118 | | { |
| | 0 | 119 | | result.BookCount = count.Count; |
| | | 120 | | } |
| | 0 | 121 | | else if (string.Equals(count.Key, lookup[BaseItemKind.AudioBook], StringComparison.Ordinal)) |
| | | 122 | | { |
| | 0 | 123 | | result.AudioBookCount = count.Count; |
| | | 124 | | } |
| | | 125 | | } |
| | | 126 | | |
| | 0 | 127 | | return result; |
| | 0 | 128 | | } |
| | | 129 | | |
| | | 130 | | /// <inheritdoc /> |
| | | 131 | | public ItemCounts GetItemCountsForNameItem(BaseItemKind kind, Guid id, BaseItemKind[] relatedItemKinds, InternalItem |
| | | 132 | | { |
| | 20 | 133 | | return GetItemCountsForNameItems(kind, [id], relatedItemKinds, accessFilter)[id]; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | private static ItemValueType[] GetItemValueTypes(BaseItemKind kind) |
| | 33 | 137 | | => kind switch |
| | 33 | 138 | | { |
| | 5 | 139 | | BaseItemKind.MusicArtist => [ItemValueType.Artist, ItemValueType.AlbumArtist], |
| | 20 | 140 | | BaseItemKind.Genre or BaseItemKind.MusicGenre => [ItemValueType.Genre], |
| | 0 | 141 | | BaseItemKind.Studio => [ItemValueType.Studios], |
| | 8 | 142 | | _ => [] |
| | 33 | 143 | | }; |
| | | 144 | | |
| | | 145 | | /// <inheritdoc /> |
| | | 146 | | public Dictionary<Guid, ItemCounts> GetItemCountsForNameItems(BaseItemKind kind, IReadOnlyList<Guid> ids, BaseItemKi |
| | | 147 | | { |
| | 34 | 148 | | ArgumentNullException.ThrowIfNull(ids); |
| | 34 | 149 | | ArgumentNullException.ThrowIfNull(relatedItemKinds); |
| | 34 | 150 | | ArgumentNullException.ThrowIfNull(accessFilter); |
| | | 151 | | |
| | 34 | 152 | | var result = new Dictionary<Guid, ItemCounts>(); |
| | 34 | 153 | | if (ids.Count == 0) |
| | | 154 | | { |
| | 0 | 155 | | return result; |
| | | 156 | | } |
| | | 157 | | |
| | 34 | 158 | | using var context = _dbProvider.CreateDbContext(); |
| | | 159 | | |
| | 34 | 160 | | var idsArray = ids as Guid[] ?? ids.ToArray(); |
| | 34 | 161 | | var nameItems = context.BaseItems.AsNoTracking() |
| | 34 | 162 | | .WhereOneOrMany(idsArray, e => e.Id) |
| | 34 | 163 | | .Select(e => new NameItem(e.Id, e.Name, e.CleanName)) |
| | 34 | 164 | | .ToArray(); |
| | | 165 | | |
| | 80272 | 166 | | foreach (var id in ids) |
| | | 167 | | { |
| | 40102 | 168 | | result[id] = new ItemCounts(); |
| | | 169 | | } |
| | | 170 | | |
| | 34 | 171 | | if (nameItems.Length == 0) |
| | | 172 | | { |
| | 1 | 173 | | return result; |
| | | 174 | | } |
| | | 175 | | |
| | 33 | 176 | | var typeNames = relatedItemKinds.Select(k => _itemTypeLookup.BaseItemKindNames[k]).ToArray(); |
| | 33 | 177 | | var related = _queryHelpers.ApplyAccessFiltering( |
| | 33 | 178 | | context, |
| | 33 | 179 | | context.BaseItems.AsNoTracking().Where(e => typeNames.Contains(e.Type)), |
| | 33 | 180 | | accessFilter); |
| | | 181 | | |
| | 33 | 182 | | var valueTypes = GetItemValueTypes(kind); |
| | 33 | 183 | | if (valueTypes.Length > 0) |
| | | 184 | | { |
| | 25 | 185 | | CountByItemValue(context, related, kind, relatedItemKinds, valueTypes, nameItems, result); |
| | | 186 | | } |
| | 8 | 187 | | else if (kind == BaseItemKind.Person) |
| | | 188 | | { |
| | 3 | 189 | | CountByPersonName(context, related, nameItems, result); |
| | | 190 | | } |
| | 5 | 191 | | else if (kind == BaseItemKind.Year) |
| | | 192 | | { |
| | 5 | 193 | | CountByProductionYear(related, nameItems, result); |
| | | 194 | | } |
| | | 195 | | |
| | 33 | 196 | | return result; |
| | 34 | 197 | | } |
| | | 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 | | { |
| | 25 | 208 | | var cleanNames = nameItems |
| | 25 | 209 | | .Select(n => n.CleanName) |
| | 25 | 210 | | .OfType<string>() |
| | 25 | 211 | | .Distinct(StringComparer.Ordinal) |
| | 25 | 212 | | .ToArray(); |
| | | 213 | | |
| | 25 | 214 | | if (cleanNames.Length == 0) |
| | | 215 | | { |
| | 0 | 216 | | return; |
| | | 217 | | } |
| | | 218 | | |
| | 25 | 219 | | var grouped = context.ItemValuesMap.AsNoTracking() |
| | 25 | 220 | | .Where(ivm => valueTypes.Contains(ivm.ItemValue.Type)) |
| | 25 | 221 | | .WhereOneOrMany(cleanNames, ivm => ivm.ItemValue.CleanValue) |
| | 25 | 222 | | .Join(related, ivm => ivm.ItemId, e => e.Id, (ivm, e) => new { ivm.ItemValue.CleanValue, e.Type, e.Id }) |
| | 25 | 223 | | .GroupBy(x => new { x.CleanValue, x.Type }) |
| | 25 | 224 | | .Select(g => new { g.Key.CleanValue, g.Key.Type, Count = g.Select(x => x.Id).Distinct().Count() }) |
| | 25 | 225 | | .ToArray(); |
| | | 226 | | |
| | 25 | 227 | | var byCleanName = grouped |
| | 25 | 228 | | .GroupBy(g => g.CleanValue, StringComparer.Ordinal) |
| | 25 | 229 | | .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray(), StringComparer.Ordinal); |
| | | 230 | | |
| | 25 | 231 | | var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series]; |
| | 25 | 232 | | var episodeRollUp = RollsUpEpisodes(kind, relatedItemKinds) |
| | 25 | 233 | | && Array.Exists(grouped, g => string.Equals(g.Type, seriesTypeName, StringComparison.Ordinal)) |
| | 25 | 234 | | ? CountEpisodesOfTaggedSeriesByCleanName(context, related, valueTypes, cleanNames) |
| | 25 | 235 | | : null; |
| | | 236 | | |
| | 232 | 237 | | foreach (var nameItem in nameItems) |
| | | 238 | | { |
| | 91 | 239 | | if (nameItem.CleanName is null || !byCleanName.TryGetValue(nameItem.CleanName, out var counts)) |
| | | 240 | | { |
| | | 241 | | continue; |
| | | 242 | | } |
| | | 243 | | |
| | 27 | 244 | | var itemCounts = ItemCountBuilder.Build(_itemTypeLookup, counts); |
| | | 245 | | |
| | 27 | 246 | | if (episodeRollUp is not null) |
| | | 247 | | { |
| | 8 | 248 | | 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. |
| | 8 | 252 | | var directEpisodeCount = itemCounts.EpisodeCount - rollUp.TaggedEpisodesOfTaggedSeries; |
| | 8 | 253 | | ItemCountBuilder.SetEpisodeCount(itemCounts, rollUp.EpisodesOfTaggedSeries + directEpisodeCount); |
| | | 254 | | } |
| | | 255 | | |
| | 27 | 256 | | result[nameItem.Id] = itemCounts; |
| | | 257 | | } |
| | 25 | 258 | | } |
| | | 259 | | |
| | | 260 | | private void CountByPersonName( |
| | | 261 | | JellyfinDbContext context, |
| | | 262 | | IQueryable<BaseItemEntity> related, |
| | | 263 | | NameItem[] nameItems, |
| | | 264 | | Dictionary<Guid, ItemCounts> result) |
| | | 265 | | { |
| | 3 | 266 | | var names = nameItems |
| | 3 | 267 | | .Select(n => n.Name) |
| | 3 | 268 | | .OfType<string>() |
| | 3 | 269 | | .Distinct(StringComparer.Ordinal) |
| | 3 | 270 | | .ToArray(); |
| | | 271 | | |
| | 3 | 272 | | if (names.Length == 0) |
| | | 273 | | { |
| | 0 | 274 | | return; |
| | | 275 | | } |
| | | 276 | | |
| | 3 | 277 | | var grouped = context.PeopleBaseItemMap.AsNoTracking() |
| | 3 | 278 | | .WhereOneOrMany(names, m => m.People.Name) |
| | 3 | 279 | | .Join(related, m => m.ItemId, e => e.Id, (m, e) => new { m.People.Name, e.Type, e.Id }) |
| | 3 | 280 | | .GroupBy(x => new { x.Name, x.Type }) |
| | 3 | 281 | | // A person can be credited on one item more than once, in different roles. |
| | 3 | 282 | | .Select(g => new { g.Key.Name, g.Key.Type, Count = g.Select(x => x.Id).Distinct().Count() }) |
| | 3 | 283 | | .ToArray(); |
| | | 284 | | |
| | 3 | 285 | | ApplyGroupedCounts(nameItems, n => n.Name, grouped.Select(g => (g.Name, g.Type, g.Count)), result); |
| | 3 | 286 | | } |
| | | 287 | | |
| | | 288 | | private void CountByProductionYear( |
| | | 289 | | IQueryable<BaseItemEntity> related, |
| | | 290 | | NameItem[] nameItems, |
| | | 291 | | Dictionary<Guid, ItemCounts> result) |
| | | 292 | | { |
| | 5 | 293 | | var years = new List<int>(); |
| | 22 | 294 | | foreach (var nameItem in nameItems) |
| | | 295 | | { |
| | 6 | 296 | | if (int.TryParse(nameItem.Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year) |
| | 6 | 297 | | && !years.Contains(year)) |
| | | 298 | | { |
| | 6 | 299 | | years.Add(year); |
| | | 300 | | } |
| | | 301 | | } |
| | | 302 | | |
| | 5 | 303 | | if (years.Count == 0) |
| | | 304 | | { |
| | 0 | 305 | | return; |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | // No join, so no row can be reached twice and a plain count is the distinct count. |
| | 5 | 309 | | var grouped = related |
| | 5 | 310 | | .Where(e => e.ProductionYear != null) |
| | 5 | 311 | | .WhereOneOrMany(years, e => e.ProductionYear!.Value) |
| | 5 | 312 | | .GroupBy(e => new { Year = e.ProductionYear!.Value, e.Type }) |
| | 5 | 313 | | .Select(g => new { g.Key.Year, g.Key.Type, Count = g.Count() }) |
| | 5 | 314 | | .ToArray(); |
| | | 315 | | |
| | 5 | 316 | | var byYear = grouped |
| | 5 | 317 | | .GroupBy(g => g.Year) |
| | 5 | 318 | | .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray()); |
| | | 319 | | |
| | 22 | 320 | | foreach (var nameItem in nameItems) |
| | | 321 | | { |
| | 6 | 322 | | if (int.TryParse(nameItem.Name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year) |
| | 6 | 323 | | && byYear.TryGetValue(year, out var counts)) |
| | | 324 | | { |
| | 6 | 325 | | result[nameItem.Id] = ItemCountBuilder.Build(_itemTypeLookup, counts); |
| | | 326 | | } |
| | | 327 | | } |
| | 5 | 328 | | } |
| | | 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 | | { |
| | 3 | 336 | | var byKey = grouped |
| | 3 | 337 | | .GroupBy(g => g.Key, StringComparer.Ordinal) |
| | 3 | 338 | | .ToDictionary(g => g.Key, g => g.Select(x => (x.Type, x.Count)).ToArray(), StringComparer.Ordinal); |
| | | 339 | | |
| | 14 | 340 | | foreach (var nameItem in nameItems) |
| | | 341 | | { |
| | 4 | 342 | | var key = keySelector(nameItem); |
| | 4 | 343 | | if (key is not null && byKey.TryGetValue(key, out var counts)) |
| | | 344 | | { |
| | 4 | 345 | | result[nameItem.Id] = ItemCountBuilder.Build(_itemTypeLookup, counts); |
| | | 346 | | } |
| | | 347 | | } |
| | 3 | 348 | | } |
| | | 349 | | |
| | | 350 | | private static bool RollsUpEpisodes(BaseItemKind kind, BaseItemKind[] relatedItemKinds) |
| | 25 | 351 | | => kind is BaseItemKind.Studio or BaseItemKind.Genre or BaseItemKind.MusicGenre |
| | 25 | 352 | | && relatedItemKinds.Contains(BaseItemKind.Episode) |
| | 25 | 353 | | && 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 | | { |
| | 5 | 361 | | var seriesTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Series]; |
| | 5 | 362 | | var episodeTypeName = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Episode]; |
| | | 363 | | |
| | 5 | 364 | | var taggedValues = context.ItemValuesMap.AsNoTracking() |
| | 5 | 365 | | .Where(ivm => valueTypes.Contains(ivm.ItemValue.Type)) |
| | 5 | 366 | | .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. |
| | 5 | 370 | | var taggedSeries = taggedValues |
| | 5 | 371 | | .Join( |
| | 5 | 372 | | related.Where(e => e.Type == seriesTypeName), |
| | 5 | 373 | | ivm => ivm.ItemId, |
| | 5 | 374 | | e => e.Id, |
| | 5 | 375 | | (ivm, e) => new { ivm.ItemValue.CleanValue, SeriesId = e.Id }) |
| | 5 | 376 | | .Distinct(); |
| | | 377 | | |
| | 5 | 378 | | var episodes = related.Where(e => e.Type == episodeTypeName && e.SeriesId != null); |
| | | 379 | | |
| | 5 | 380 | | var episodesOfTaggedSeries = taggedSeries |
| | 5 | 381 | | .Join(episodes, s => s.SeriesId, e => e.SeriesId!.Value, (s, e) => new { s.CleanValue, e.Id }) |
| | 5 | 382 | | .GroupBy(x => x.CleanValue) |
| | 5 | 383 | | .Select(g => new { CleanValue = g.Key, Count = g.Select(x => x.Id).Distinct().Count() }) |
| | 5 | 384 | | .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. |
| | 5 | 388 | | var taggedEpisodesOfTaggedSeries = taggedValues |
| | 5 | 389 | | .Join(episodes, ivm => ivm.ItemId, e => e.Id, (ivm, e) => new { ivm.ItemValue.CleanValue, e.Id, e.SeriesId } |
| | 5 | 390 | | .Join( |
| | 5 | 391 | | taggedSeries, |
| | 5 | 392 | | e => new { e.CleanValue, SeriesId = e.SeriesId!.Value }, |
| | 5 | 393 | | s => new { s.CleanValue, s.SeriesId }, |
| | 5 | 394 | | (e, s) => new { e.CleanValue, e.Id }) |
| | 5 | 395 | | .GroupBy(x => x.CleanValue) |
| | 5 | 396 | | .Select(g => new { CleanValue = g.Key, Count = g.Select(x => x.Id).Distinct().Count() }) |
| | 5 | 397 | | .ToArray(); |
| | | 398 | | |
| | 5 | 399 | | var taggedLookup = taggedEpisodesOfTaggedSeries |
| | 5 | 400 | | .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. |
| | 5 | 404 | | var result = new Dictionary<string, (int EpisodesOfTaggedSeries, int TaggedEpisodesOfTaggedSeries)>(StringCompar |
| | 20 | 405 | | foreach (var entry in episodesOfTaggedSeries) |
| | | 406 | | { |
| | 5 | 407 | | result[entry.CleanValue] = (entry.Count, taggedLookup.GetValueOrDefault(entry.CleanValue)); |
| | | 408 | | } |
| | | 409 | | |
| | 5 | 410 | | return result; |
| | | 411 | | } |
| | | 412 | | |
| | | 413 | | /// <inheritdoc/> |
| | | 414 | | public int GetPlayedCount(InternalItemsQuery filter, Guid ancestorId) |
| | | 415 | | { |
| | 5 | 416 | | ArgumentNullException.ThrowIfNull(filter); |
| | 5 | 417 | | ArgumentNullException.ThrowIfNull(filter.User); |
| | 5 | 418 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | | 419 | | |
| | 5 | 420 | | var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId); |
| | 5 | 421 | | return baseQuery.Count(DescendantQueryHelper.IsPlayedBy(filter.User.Id)); |
| | 5 | 422 | | } |
| | | 423 | | |
| | | 424 | | /// <inheritdoc/> |
| | | 425 | | public int GetTotalCount(InternalItemsQuery filter, Guid ancestorId) |
| | | 426 | | { |
| | 3 | 427 | | ArgumentNullException.ThrowIfNull(filter); |
| | 3 | 428 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | | 429 | | |
| | 3 | 430 | | var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId); |
| | 3 | 431 | | return baseQuery.Count(); |
| | 3 | 432 | | } |
| | | 433 | | |
| | | 434 | | /// <inheritdoc/> |
| | | 435 | | public (int Played, int Total) GetPlayedAndTotalCount(InternalItemsQuery filter, Guid ancestorId) |
| | | 436 | | { |
| | 5 | 437 | | ArgumentNullException.ThrowIfNull(filter); |
| | 5 | 438 | | ArgumentNullException.ThrowIfNull(filter.User); |
| | 5 | 439 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | | 440 | | |
| | 5 | 441 | | var baseQuery = BuildGroupedDescendantsQuery(dbContext, filter, ancestorId); |
| | 5 | 442 | | return GetPlayedAndTotalCountFromQuery(baseQuery, filter.User.Id); |
| | 5 | 443 | | } |
| | | 444 | | |
| | | 445 | | private IQueryable<BaseItemEntity> BuildGroupedDescendantsQuery(JellyfinDbContext dbContext, InternalItemsQuery filt |
| | | 446 | | { |
| | 13 | 447 | | var ancestorIds = GetPresentationKeyGroups(dbContext, [ancestorId])[ancestorId]; |
| | 13 | 448 | | var descendantIds = DescendantQueryHelper.GetAllDescendantIdsBatch(dbContext, ancestorIds).ToArray(); |
| | | 449 | | |
| | 13 | 450 | | var baseQuery = dbContext.BaseItems |
| | 13 | 451 | | .AsNoTracking() |
| | 13 | 452 | | .WhereOneOrMany(descendantIds, b => b.Id) |
| | 13 | 453 | | .Where(DescendantQueryHelper.IsCountableLeaf); |
| | | 454 | | |
| | 13 | 455 | | return _queryHelpers.ApplyAccessFiltering(dbContext, baseQuery, filter); |
| | | 456 | | } |
| | | 457 | | |
| | | 458 | | /// <inheritdoc/> |
| | | 459 | | public (int Played, int Total) GetPlayedAndTotalCountFromLinkedChildren(InternalItemsQuery filter, Guid parentId) |
| | | 460 | | { |
| | 1 | 461 | | ArgumentNullException.ThrowIfNull(filter); |
| | 1 | 462 | | ArgumentNullException.ThrowIfNull(filter.User); |
| | 1 | 463 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | | 464 | | |
| | 1 | 465 | | var allDescendantIds = DescendantQueryHelper.GetAllDescendantIdsBatch(dbContext, [parentId]).ToArray(); |
| | 1 | 466 | | var baseQuery = dbContext.BaseItems |
| | 1 | 467 | | .WhereOneOrMany(allDescendantIds, b => b.Id) |
| | 1 | 468 | | .Where(DescendantQueryHelper.IsCountableLeaf); |
| | 1 | 469 | | baseQuery = _queryHelpers.ApplyAccessFiltering(dbContext, baseQuery, filter); |
| | | 470 | | |
| | 1 | 471 | | return GetPlayedAndTotalCountFromQuery(baseQuery, filter.User.Id); |
| | 1 | 472 | | } |
| | | 473 | | |
| | | 474 | | /// <inheritdoc/> |
| | | 475 | | public Dictionary<Guid, int> GetChildCountBatch(IReadOnlyList<Guid> parentIds, User? user) |
| | | 476 | | { |
| | 14 | 477 | | ArgumentNullException.ThrowIfNull(parentIds); |
| | | 478 | | |
| | 14 | 479 | | if (parentIds.Count == 0) |
| | | 480 | | { |
| | 0 | 481 | | return new Dictionary<Guid, int>(); |
| | | 482 | | } |
| | | 483 | | |
| | 14 | 484 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | | 485 | | |
| | 14 | 486 | | var parentIdsArray = parentIds.ToArray(); |
| | | 487 | | |
| | 14 | 488 | | var includeVirtual = user is null || user.DisplayMissingEpisodes; |
| | | 489 | | |
| | 14 | 490 | | var accessibleItems = dbContext.BaseItems.AsNoTracking(); |
| | 14 | 491 | | 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. |
| | 6 | 495 | | accessibleItems = accessibleItems.Where(DescendantQueryHelper.IsDistinctLibraryItem); |
| | | 496 | | } |
| | | 497 | | else |
| | | 498 | | { |
| | 8 | 499 | | accessibleItems = _queryHelpers.ApplyAccessFiltering(dbContext, accessibleItems, new InternalItemsQuery(user |
| | | 500 | | } |
| | | 501 | | |
| | 14 | 502 | | var hierarchicalCounts = accessibleItems |
| | 14 | 503 | | .Where(b => b.ParentId.HasValue && !b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem)) |
| | 14 | 504 | | .WhereOneOrMany(parentIdsArray, b => b.ParentId!.Value) |
| | 14 | 505 | | .GroupBy(b => b.ParentId!.Value) |
| | 14 | 506 | | .Select(g => new { ParentId = g.Key, Count = g.Count() }) |
| | 14 | 507 | | .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. |
| | 14 | 512 | | var seasonCounts = accessibleItems |
| | 14 | 513 | | .Where(b => b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem)) |
| | 14 | 514 | | .WhereOneOrMany(parentIdsArray, b => b.SeasonId!.Value) |
| | 14 | 515 | | .GroupBy(b => b.SeasonId!.Value) |
| | 14 | 516 | | .Select(g => new { SeasonId = g.Key, Count = g.Count() }) |
| | 14 | 517 | | .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. |
| | 14 | 520 | | var linkedCounts = dbContext.LinkedChildren |
| | 14 | 521 | | .WhereOneOrMany(parentIdsArray, lc => lc.ParentId) |
| | 14 | 522 | | .Join(accessibleItems, lc => lc.ChildId, b => b.Id, (lc, b) => lc.ParentId) |
| | 14 | 523 | | .GroupBy(parentId => parentId) |
| | 14 | 524 | | .Select(g => new { ParentId = g.Key, Count = g.Count() }) |
| | 14 | 525 | | .ToDictionary(x => x.ParentId, x => x.Count); |
| | | 526 | | |
| | 14 | 527 | | var mergedChildCounts = GetMergedChildCounts(dbContext, accessibleItems, parentIdsArray, includeVirtual); |
| | | 528 | | |
| | 14 | 529 | | var result = new Dictionary<Guid, int>(); |
| | 80064 | 530 | | foreach (var parentId in parentIds) |
| | | 531 | | { |
| | 40018 | 532 | | if (mergedChildCounts.TryGetValue(parentId, out var mergedCount)) |
| | | 533 | | { |
| | 2 | 534 | | result[parentId] = mergedCount; |
| | 2 | 535 | | continue; |
| | | 536 | | } |
| | | 537 | | |
| | 40016 | 538 | | var hierarchicalCount = hierarchicalCounts.GetValueOrDefault(parentId, 0) |
| | 40016 | 539 | | + seasonCounts.GetValueOrDefault(parentId, 0); |
| | 40016 | 540 | | var linkedCount = linkedCounts.GetValueOrDefault(parentId, 0); |
| | | 541 | | |
| | 40016 | 542 | | result[parentId] = linkedCount > 0 ? linkedCount : hierarchicalCount; |
| | | 543 | | } |
| | | 544 | | |
| | 14 | 545 | | return result; |
| | 14 | 546 | | } |
| | | 547 | | |
| | | 548 | | private static Dictionary<Guid, int> GetMergedChildCounts( |
| | | 549 | | JellyfinDbContext dbContext, |
| | | 550 | | IQueryable<BaseItemEntity> accessibleItems, |
| | | 551 | | IReadOnlyList<Guid> parentIds, |
| | | 552 | | bool includeVirtual) |
| | | 553 | | { |
| | 14 | 554 | | var mergedGroups = GetPresentationKeyGroups(dbContext, parentIds) |
| | 14 | 555 | | .Where(group => group.Value.Count > 1) |
| | 14 | 556 | | .ToArray(); |
| | | 557 | | |
| | 14 | 558 | | if (mergedGroups.Length == 0) |
| | | 559 | | { |
| | 13 | 560 | | return []; |
| | | 561 | | } |
| | | 562 | | |
| | | 563 | | // Only merged folders. |
| | 1 | 564 | | var memberIds = mergedGroups.SelectMany(group => group.Value).Distinct().ToArray(); |
| | 1 | 565 | | var children = accessibleItems |
| | 1 | 566 | | .Where(b => b.ParentId.HasValue && !b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem)) |
| | 1 | 567 | | .WhereOneOrMany(memberIds, b => b.ParentId!.Value) |
| | 1 | 568 | | .Select(b => new { ParentId = b.ParentId!.Value, b.Id, b.PresentationUniqueKey }) |
| | 1 | 569 | | .ToArray() |
| | 1 | 570 | | .Concat(accessibleItems |
| | 1 | 571 | | .Where(b => b.SeasonId.HasValue && (includeVirtual || !b.IsVirtualItem)) |
| | 1 | 572 | | .WhereOneOrMany(memberIds, b => b.SeasonId!.Value) |
| | 1 | 573 | | .Select(b => new { ParentId = b.SeasonId!.Value, b.Id, b.PresentationUniqueKey }) |
| | 1 | 574 | | .ToArray()) |
| | 1 | 575 | | .GroupBy(b => b.ParentId) |
| | 1 | 576 | | .ToDictionary( |
| | 1 | 577 | | g => g.Key, |
| | 1 | 578 | | g => g.Select(b => string.IsNullOrEmpty(b.PresentationUniqueKey) |
| | 1 | 579 | | ? b.Id.ToString("N", CultureInfo.InvariantCulture) |
| | 1 | 580 | | : b.PresentationUniqueKey).ToArray()); |
| | | 581 | | |
| | 1 | 582 | | var result = new Dictionary<Guid, int>(); |
| | 6 | 583 | | foreach (var (parentId, members) in mergedGroups) |
| | | 584 | | { |
| | 2 | 585 | | var childKeys = new HashSet<string>(StringComparer.Ordinal); |
| | 12 | 586 | | foreach (var member in members) |
| | | 587 | | { |
| | 4 | 588 | | if (children.TryGetValue(member, out var keys)) |
| | | 589 | | { |
| | 4 | 590 | | childKeys.UnionWith(keys); |
| | | 591 | | } |
| | | 592 | | } |
| | | 593 | | |
| | 2 | 594 | | result[parentId] = childKeys.Count; |
| | | 595 | | } |
| | | 596 | | |
| | 1 | 597 | | return result; |
| | | 598 | | } |
| | | 599 | | |
| | | 600 | | /// <inheritdoc/> |
| | | 601 | | public Dictionary<Guid, (int Played, int Total)> GetPlayedAndTotalCountBatch(IReadOnlyList<Guid> folderIds, User use |
| | | 602 | | { |
| | 3 | 603 | | ArgumentNullException.ThrowIfNull(folderIds); |
| | 3 | 604 | | ArgumentNullException.ThrowIfNull(user); |
| | | 605 | | |
| | 3 | 606 | | if (folderIds.Count == 0) |
| | | 607 | | { |
| | 0 | 608 | | return new Dictionary<Guid, (int Played, int Total)>(); |
| | | 609 | | } |
| | | 610 | | |
| | 3 | 611 | | using var dbContext = _dbProvider.CreateDbContext(); |
| | 3 | 612 | | var filter = new InternalItemsQuery(user); |
| | 3 | 613 | | var userId = user.Id; |
| | | 614 | | |
| | | 615 | | // Merged series and seasons are stored as one row per folder-item sharing a presentation key. |
| | 3 | 616 | | var groups = GetPresentationKeyGroups(dbContext, folderIds); |
| | 3 | 617 | | var folderIdsArray = groups.Values.SelectMany(members => members).Distinct().ToArray(); |
| | | 618 | | |
| | 3 | 619 | | var leafItems = dbContext.BaseItems |
| | 3 | 620 | | .Where(DescendantQueryHelper.IsCountableLeaf); |
| | 3 | 621 | | leafItems = _queryHelpers.ApplyAccessFiltering(dbContext, leafItems, filter); |
| | | 622 | | |
| | 3 | 623 | | var playedLeafItems = leafItems |
| | 3 | 624 | | .Select(DescendantQueryHelper.PlayedStateBy(userId)); |
| | | 625 | | |
| | 3 | 626 | | var ancestorLeaves = dbContext.AncestorIds |
| | 3 | 627 | | .WhereOneOrMany(folderIdsArray, a => a.ParentItemId) |
| | 3 | 628 | | .Join( |
| | 3 | 629 | | playedLeafItems, |
| | 3 | 630 | | a => a.ItemId, |
| | 3 | 631 | | b => b.Id, |
| | 3 | 632 | | (a, b) => new { FolderId = a.ParentItemId, b.Id, b.Played }); |
| | | 633 | | |
| | 3 | 634 | | var linkedLeaves = dbContext.LinkedChildren |
| | 3 | 635 | | .WhereOneOrMany(folderIdsArray, lc => lc.ParentId) |
| | 3 | 636 | | .Join( |
| | 3 | 637 | | playedLeafItems, |
| | 3 | 638 | | lc => lc.ChildId, |
| | 3 | 639 | | b => b.Id, |
| | 3 | 640 | | (lc, b) => new { FolderId = lc.ParentId, b.Id, b.Played }); |
| | | 641 | | |
| | 3 | 642 | | var linkedFolderLeaves = dbContext.LinkedChildren |
| | 3 | 643 | | .WhereOneOrMany(folderIdsArray, lc => lc.ParentId) |
| | 3 | 644 | | .Join( |
| | 3 | 645 | | dbContext.BaseItems.Where(b => b.IsFolder), |
| | 3 | 646 | | lc => lc.ChildId, |
| | 3 | 647 | | b => b.Id, |
| | 3 | 648 | | (lc, b) => new { lc.ParentId, FolderChildId = b.Id }) |
| | 3 | 649 | | .Join( |
| | 3 | 650 | | dbContext.AncestorIds, |
| | 3 | 651 | | x => x.FolderChildId, |
| | 3 | 652 | | a => a.ParentItemId, |
| | 3 | 653 | | (x, a) => new { x.ParentId, DescendantId = a.ItemId }) |
| | 3 | 654 | | .Join( |
| | 3 | 655 | | playedLeafItems, |
| | 3 | 656 | | x => x.DescendantId, |
| | 3 | 657 | | b => b.Id, |
| | 3 | 658 | | (x, b) => new { FolderId = x.ParentId, b.Id, b.Played }); |
| | | 659 | | |
| | 3 | 660 | | var countsByFolder = ancestorLeaves |
| | 3 | 661 | | .Union(linkedLeaves) |
| | 3 | 662 | | .Union(linkedFolderLeaves) |
| | 3 | 663 | | .GroupBy(x => x.FolderId) |
| | 3 | 664 | | .Select(g => new |
| | 3 | 665 | | { |
| | 3 | 666 | | FolderId = g.Key, |
| | 3 | 667 | | Total = g.Select(x => x.Id).Distinct().Count(), |
| | 3 | 668 | | Played = g.Where(x => x.Played).Select(x => x.Id).Distinct().Count() |
| | 3 | 669 | | }) |
| | 3 | 670 | | .ToDictionary(x => x.FolderId, x => (x.Played, x.Total)); |
| | | 671 | | |
| | 3 | 672 | | var results = new Dictionary<Guid, (int Played, int Total)>(); |
| | 12 | 673 | | foreach (var (folderId, members) in groups) |
| | | 674 | | { |
| | 3 | 675 | | var played = 0; |
| | 3 | 676 | | var total = 0; |
| | | 677 | | |
| | | 678 | | // Members of a group are distinct folders, so their leaves cannot overlap. |
| | 14 | 679 | | foreach (var member in members) |
| | | 680 | | { |
| | 4 | 681 | | if (countsByFolder.TryGetValue(member, out var counts)) |
| | | 682 | | { |
| | 4 | 683 | | played += counts.Played; |
| | 4 | 684 | | total += counts.Total; |
| | | 685 | | } |
| | | 686 | | } |
| | | 687 | | |
| | 3 | 688 | | if (total > 0 || played > 0) |
| | | 689 | | { |
| | 3 | 690 | | results[folderId] = (played, total); |
| | | 691 | | } |
| | | 692 | | } |
| | | 693 | | |
| | 3 | 694 | | return results; |
| | 3 | 695 | | } |
| | | 696 | | |
| | | 697 | | private static Dictionary<Guid, List<Guid>> GetPresentationKeyGroups(JellyfinDbContext dbContext, IReadOnlyList<Guid |
| | | 698 | | { |
| | 30 | 699 | | var requested = dbContext.BaseItems |
| | 30 | 700 | | .AsNoTracking() |
| | 30 | 701 | | .WhereOneOrMany(folderIds, e => e.Id) |
| | 30 | 702 | | .Select(e => new { e.Id, e.PresentationUniqueKey }) |
| | 30 | 703 | | .ToArray(); |
| | | 704 | | |
| | 30 | 705 | | var keys = requested |
| | 30 | 706 | | .Select(e => e.PresentationUniqueKey) |
| | 30 | 707 | | .Where(key => !string.IsNullOrEmpty(key)) |
| | 30 | 708 | | .Distinct(StringComparer.Ordinal) |
| | 30 | 709 | | .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. |
| | 30 | 713 | | var membersByKey = keys.Length == 0 |
| | 30 | 714 | | ? [] |
| | 30 | 715 | | : dbContext.BaseItems |
| | 30 | 716 | | .AsNoTracking() |
| | 30 | 717 | | .Where(e => e.IsFolder) |
| | 30 | 718 | | .WhereOneOrMany(keys, e => e.PresentationUniqueKey!) |
| | 30 | 719 | | .Select(e => new { e.Id, Key = e.PresentationUniqueKey! }) |
| | 30 | 720 | | .ToArray() |
| | 30 | 721 | | .GroupBy(e => e.Key, StringComparer.Ordinal) |
| | 30 | 722 | | .ToDictionary(g => g.Key, g => g.Select(e => e.Id).ToList(), StringComparer.Ordinal); |
| | | 723 | | |
| | 30 | 724 | | var keyById = requested.ToDictionary(e => e.Id, e => e.PresentationUniqueKey); |
| | 30 | 725 | | var groups = new Dictionary<Guid, List<Guid>>(); |
| | 80128 | 726 | | foreach (var folderId in folderIds) |
| | | 727 | | { |
| | 40034 | 728 | | groups[folderId] = keyById.TryGetValue(folderId, out var key) |
| | 40034 | 729 | | && !string.IsNullOrEmpty(key) |
| | 40034 | 730 | | && membersByKey.TryGetValue(key, out var members) |
| | 40034 | 731 | | && members.Count > 0 |
| | 40034 | 732 | | ? members |
| | 40034 | 733 | | : [folderId]; |
| | | 734 | | } |
| | | 735 | | |
| | 30 | 736 | | return groups; |
| | | 737 | | } |
| | | 738 | | |
| | | 739 | | private static (int Played, int Total) GetPlayedAndTotalCountFromQuery(IQueryable<BaseItemEntity> query, Guid userId |
| | | 740 | | { |
| | 6 | 741 | | var result = query |
| | 6 | 742 | | .Select(DescendantQueryHelper.IsPlayedBy(userId)) |
| | 6 | 743 | | .GroupBy(_ => 1) |
| | 6 | 744 | | .OrderBy(g => g.Key) |
| | 6 | 745 | | .Select(g => new |
| | 6 | 746 | | { |
| | 6 | 747 | | Total = g.Count(), |
| | 6 | 748 | | Played = g.Count(isPlayed => isPlayed) |
| | 6 | 749 | | }) |
| | 6 | 750 | | .FirstOrDefault(); |
| | | 751 | | |
| | 6 | 752 | | 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 | | } |