| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Text.Json; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using Jellyfin.Data.Enums; |
| | | 10 | | using Jellyfin.Database.Implementations.Entities; |
| | | 11 | | using Jellyfin.Database.Implementations.Enums; |
| | | 12 | | using Jellyfin.Extensions.Json; |
| | | 13 | | using MediaBrowser.Common.Extensions; |
| | | 14 | | using MediaBrowser.Controller; |
| | | 15 | | using MediaBrowser.Controller.Configuration; |
| | | 16 | | using MediaBrowser.Controller.Dto; |
| | | 17 | | using MediaBrowser.Controller.Entities; |
| | | 18 | | using MediaBrowser.Controller.Library; |
| | | 19 | | using MediaBrowser.Model.Configuration; |
| | | 20 | | using MediaBrowser.Model.Dto; |
| | | 21 | | using MediaBrowser.Model.Entities; |
| | | 22 | | using MediaBrowser.Model.IO; |
| | | 23 | | using MediaBrowser.Model.Querying; |
| | | 24 | | using Microsoft.Extensions.Logging; |
| | | 25 | | |
| | | 26 | | namespace Emby.Server.Implementations.Library.SimilarItems; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Manages similar items providers and orchestrates similar items operations. |
| | | 30 | | /// </summary> |
| | | 31 | | public class SimilarItemsManager : ISimilarItemsManager |
| | | 32 | | { |
| | | 33 | | private readonly ILogger<SimilarItemsManager> _logger; |
| | | 34 | | private readonly IServerApplicationPaths _appPaths; |
| | | 35 | | private readonly ILibraryManager _libraryManager; |
| | | 36 | | private readonly IFileSystem _fileSystem; |
| | | 37 | | private readonly IServerConfigurationManager _serverConfigurationManager; |
| | 21 | 38 | | private ISimilarItemsProvider[] _similarItemsProviders = []; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Initializes a new instance of the <see cref="SimilarItemsManager"/> class. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="logger">The logger.</param> |
| | | 44 | | /// <param name="appPaths">The server application paths.</param> |
| | | 45 | | /// <param name="libraryManager">The library manager.</param> |
| | | 46 | | /// <param name="fileSystem">The file system.</param> |
| | | 47 | | /// <param name="serverConfigurationManager">The server configuration manager.</param> |
| | | 48 | | public SimilarItemsManager( |
| | | 49 | | ILogger<SimilarItemsManager> logger, |
| | | 50 | | IServerApplicationPaths appPaths, |
| | | 51 | | ILibraryManager libraryManager, |
| | | 52 | | IFileSystem fileSystem, |
| | | 53 | | IServerConfigurationManager serverConfigurationManager) |
| | | 54 | | { |
| | 21 | 55 | | _logger = logger; |
| | 21 | 56 | | _appPaths = appPaths; |
| | 21 | 57 | | _libraryManager = libraryManager; |
| | 21 | 58 | | _fileSystem = fileSystem; |
| | 21 | 59 | | _serverConfigurationManager = serverConfigurationManager; |
| | 21 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <inheritdoc/> |
| | | 63 | | public void AddParts(IEnumerable<ISimilarItemsProvider> providers) |
| | | 64 | | { |
| | 21 | 65 | | _similarItemsProviders = providers.ToArray(); |
| | 21 | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <inheritdoc/> |
| | | 69 | | public IReadOnlyList<ISimilarItemsProvider> GetSimilarItemsProviders<T>() |
| | | 70 | | where T : BaseItem |
| | | 71 | | { |
| | 0 | 72 | | var itemType = typeof(T); |
| | 0 | 73 | | return _similarItemsProviders |
| | 0 | 74 | | .Where(p => (p is ILocalSimilarItemsProvider local && local.Supports(itemType)) |
| | 0 | 75 | | || (p is IRemoteSimilarItemsProvider remote && remote.Supports(itemType))) |
| | 0 | 76 | | .ToList(); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <inheritdoc/> |
| | | 80 | | public async Task<IReadOnlyList<BaseItem>> GetSimilarItemsAsync( |
| | | 81 | | BaseItem item, |
| | | 82 | | IReadOnlyList<Guid> excludeArtistIds, |
| | | 83 | | User? user, |
| | | 84 | | DtoOptions dtoOptions, |
| | | 85 | | int? limit, |
| | | 86 | | LibraryOptions? libraryOptions, |
| | | 87 | | CancellationToken cancellationToken) |
| | | 88 | | { |
| | 0 | 89 | | ArgumentNullException.ThrowIfNull(item); |
| | 0 | 90 | | ArgumentNullException.ThrowIfNull(excludeArtistIds); |
| | | 91 | | |
| | 0 | 92 | | var itemType = item.GetType(); |
| | 0 | 93 | | var requestedLimit = limit ?? 50; |
| | 0 | 94 | | var itemKind = item.GetBaseItemKind(); |
| | | 95 | | |
| | | 96 | | // Ensure ProviderIds is included in DtoOptions for matching remote provider responses |
| | 0 | 97 | | if (!dtoOptions.Fields.Contains(ItemFields.ProviderIds)) |
| | | 98 | | { |
| | 0 | 99 | | dtoOptions.Fields = dtoOptions.Fields.Concat([ItemFields.ProviderIds]).ToArray(); |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | // Local providers are always enabled. Remote providers must be explicitly enabled. |
| | 0 | 103 | | var localProviders = _similarItemsProviders |
| | 0 | 104 | | .OfType<ILocalSimilarItemsProvider>() |
| | 0 | 105 | | .Where(p => p.Supports(itemType)) |
| | 0 | 106 | | .ToList(); |
| | 0 | 107 | | var remoteProviders = _similarItemsProviders |
| | 0 | 108 | | .OfType<IRemoteSimilarItemsProvider>() |
| | 0 | 109 | | .Where(p => p.Supports(itemType)); |
| | 0 | 110 | | var matchingProviders = new List<ISimilarItemsProvider>(localProviders); |
| | | 111 | | |
| | 0 | 112 | | var typeOptions = libraryOptions?.GetTypeOptions(itemType.Name); |
| | 0 | 113 | | if (typeOptions?.SimilarItemProviders?.Length > 0) |
| | | 114 | | { |
| | 0 | 115 | | matchingProviders.AddRange(remoteProviders |
| | 0 | 116 | | .Where(p => typeOptions.SimilarItemProviders.Contains(p.Name, StringComparer.OrdinalIgnoreCase))); |
| | | 117 | | } |
| | | 118 | | |
| | 0 | 119 | | var orderConfig = typeOptions?.SimilarItemProviderOrder is { Length: > 0 } order |
| | 0 | 120 | | ? order |
| | 0 | 121 | | : typeOptions?.SimilarItemProviders; |
| | 0 | 122 | | var orderedProviders = matchingProviders |
| | 0 | 123 | | .OrderBy(p => GetConfiguredSimilarProviderOrder(orderConfig, p.Name)) |
| | 0 | 124 | | .ToList(); |
| | | 125 | | |
| | 0 | 126 | | var allResults = new List<(BaseItem Item, float Score)>(); |
| | 0 | 127 | | var excludeIds = new HashSet<Guid> { item.Id }; |
| | 0 | 128 | | var excludeKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { item.GetPresentationUniqueKey() }; |
| | 0 | 129 | | foreach (var (providerOrder, provider) in orderedProviders.Index()) |
| | | 130 | | { |
| | 0 | 131 | | if (allResults.Count >= requestedLimit || cancellationToken.IsCancellationRequested) |
| | | 132 | | { |
| | | 133 | | break; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | try |
| | | 137 | | { |
| | 0 | 138 | | if (provider is ILocalSimilarItemsProvider localProvider) |
| | | 139 | | { |
| | 0 | 140 | | var query = new SimilarItemsQuery |
| | 0 | 141 | | { |
| | 0 | 142 | | User = user, |
| | 0 | 143 | | Limit = requestedLimit - allResults.Count, |
| | 0 | 144 | | DtoOptions = dtoOptions, |
| | 0 | 145 | | ExcludeItemIds = [.. excludeIds], |
| | 0 | 146 | | ExcludeArtistIds = excludeArtistIds |
| | 0 | 147 | | }; |
| | | 148 | | |
| | 0 | 149 | | var items = await localProvider.GetSimilarItemsAsync(item, query, cancellationToken).ConfigureAwait( |
| | | 150 | | |
| | 0 | 151 | | foreach (var (position, resultItem) in items.Index()) |
| | | 152 | | { |
| | 0 | 153 | | var isNewId = excludeIds.Add(resultItem.Id); |
| | 0 | 154 | | var isNewKey = excludeKeys.Add(resultItem.GetPresentationUniqueKey()); |
| | 0 | 155 | | if (isNewId && isNewKey) |
| | | 156 | | { |
| | 0 | 157 | | var score = CalculateScore(null, providerOrder, position); |
| | 0 | 158 | | allResults.Add((resultItem, score)); |
| | | 159 | | } |
| | | 160 | | } |
| | | 161 | | } |
| | 0 | 162 | | else if (provider is IRemoteSimilarItemsProvider remoteProvider) |
| | | 163 | | { |
| | 0 | 164 | | var cachePath = GetSimilarItemsCachePath(provider.Name, itemType.Name, item.Id); |
| | | 165 | | |
| | 0 | 166 | | var cachedReferences = await TryReadSimilarItemsCacheAsync(cachePath, cancellationToken).ConfigureAw |
| | 0 | 167 | | if (cachedReferences is not null) |
| | | 168 | | { |
| | 0 | 169 | | var resolvedItems = ResolveRemoteReferences(cachedReferences, providerOrder, user, dtoOptions, i |
| | 0 | 170 | | allResults.AddRange(resolvedItems); |
| | 0 | 171 | | continue; |
| | | 172 | | } |
| | | 173 | | |
| | 0 | 174 | | var query = new SimilarItemsQuery |
| | 0 | 175 | | { |
| | 0 | 176 | | User = user, |
| | 0 | 177 | | Limit = requestedLimit - allResults.Count, |
| | 0 | 178 | | DtoOptions = dtoOptions, |
| | 0 | 179 | | ExcludeItemIds = [.. excludeIds], |
| | 0 | 180 | | ExcludeArtistIds = excludeArtistIds |
| | 0 | 181 | | }; |
| | | 182 | | |
| | | 183 | | // Collect references in batches and resolve against local library. |
| | | 184 | | // Stop fetching once we have enough resolved local items. |
| | | 185 | | const int BatchSize = 20; |
| | 0 | 186 | | var remaining = requestedLimit - allResults.Count; |
| | 0 | 187 | | var collectedReferences = new List<SimilarItemReference>(); |
| | 0 | 188 | | var pendingBatch = new List<SimilarItemReference>(); |
| | | 189 | | |
| | 0 | 190 | | await foreach (var reference in remoteProvider.GetSimilarItemsAsync(item, query, cancellationToken). |
| | | 191 | | { |
| | 0 | 192 | | collectedReferences.Add(reference); |
| | 0 | 193 | | pendingBatch.Add(reference); |
| | | 194 | | |
| | 0 | 195 | | if (pendingBatch.Count >= BatchSize) |
| | | 196 | | { |
| | 0 | 197 | | var resolvedItems = ResolveRemoteReferences(pendingBatch, providerOrder, user, dtoOptions, i |
| | 0 | 198 | | allResults.AddRange(resolvedItems); |
| | 0 | 199 | | remaining -= resolvedItems.Count; |
| | 0 | 200 | | pendingBatch.Clear(); |
| | | 201 | | |
| | 0 | 202 | | if (remaining <= 0) |
| | | 203 | | { |
| | | 204 | | break; |
| | | 205 | | } |
| | | 206 | | } |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | // Resolve any remaining references in the last partial batch |
| | 0 | 210 | | if (pendingBatch.Count > 0) |
| | | 211 | | { |
| | 0 | 212 | | var resolvedItems = ResolveRemoteReferences(pendingBatch, providerOrder, user, dtoOptions, itemK |
| | 0 | 213 | | allResults.AddRange(resolvedItems); |
| | | 214 | | } |
| | | 215 | | |
| | 0 | 216 | | if (collectedReferences.Count > 0 && provider.CacheDuration is not null) |
| | | 217 | | { |
| | 0 | 218 | | await SaveSimilarItemsCacheAsync(cachePath, collectedReferences, provider.CacheDuration.Value, c |
| | | 219 | | } |
| | 0 | 220 | | } |
| | 0 | 221 | | } |
| | 0 | 222 | | catch (OperationCanceledException) |
| | | 223 | | { |
| | 0 | 224 | | break; |
| | | 225 | | } |
| | 0 | 226 | | catch (Exception ex) |
| | | 227 | | { |
| | 0 | 228 | | _logger.LogWarning(ex, "Similar items provider {ProviderName} failed for item {ItemId}", provider.Name, |
| | 0 | 229 | | } |
| | 0 | 230 | | } |
| | | 231 | | |
| | 0 | 232 | | return allResults |
| | 0 | 233 | | .OrderByDescending(x => x.Score) |
| | 0 | 234 | | .Select(x => x.Item) |
| | 0 | 235 | | .Take(requestedLimit) |
| | 0 | 236 | | .ToList(); |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <inheritdoc/> |
| | | 240 | | public async Task<IReadOnlyList<SimilarItemsRecommendation>> GetMovieRecommendationsAsync( |
| | | 241 | | User? user, |
| | | 242 | | Guid parentId, |
| | | 243 | | int categoryLimit, |
| | | 244 | | int itemLimit, |
| | | 245 | | DtoOptions dtoOptions, |
| | | 246 | | CancellationToken cancellationToken) |
| | | 247 | | { |
| | 0 | 248 | | ArgumentNullException.ThrowIfNull(dtoOptions); |
| | | 249 | | |
| | 0 | 250 | | var recentlyPlayedMovies = _libraryManager.GetItemList(new InternalItemsQuery(user) |
| | 0 | 251 | | { |
| | 0 | 252 | | IncludeItemTypes = [BaseItemKind.Movie], |
| | 0 | 253 | | OrderBy = [(ItemSortBy.DatePlayed, SortOrder.Descending), (ItemSortBy.Random, SortOrder.Descending)], |
| | 0 | 254 | | Limit = 7, |
| | 0 | 255 | | ParentId = parentId, |
| | 0 | 256 | | Recursive = true, |
| | 0 | 257 | | IsPlayed = true, |
| | 0 | 258 | | EnableGroupByMetadataKey = true, |
| | 0 | 259 | | DtoOptions = dtoOptions |
| | 0 | 260 | | }); |
| | | 261 | | |
| | 0 | 262 | | var itemTypes = new List<BaseItemKind> { BaseItemKind.Movie }; |
| | 0 | 263 | | if (_serverConfigurationManager.Configuration.EnableExternalContentInSuggestions) |
| | | 264 | | { |
| | 0 | 265 | | itemTypes.Add(BaseItemKind.Trailer); |
| | 0 | 266 | | itemTypes.Add(BaseItemKind.LiveTvProgram); |
| | | 267 | | } |
| | | 268 | | |
| | 0 | 269 | | var likedMovies = _libraryManager.GetItemList(new InternalItemsQuery(user) |
| | 0 | 270 | | { |
| | 0 | 271 | | IncludeItemTypes = itemTypes.ToArray(), |
| | 0 | 272 | | IsMovie = true, |
| | 0 | 273 | | OrderBy = [(ItemSortBy.Random, SortOrder.Descending)], |
| | 0 | 274 | | Limit = 10, |
| | 0 | 275 | | IsFavoriteOrLiked = true, |
| | 0 | 276 | | ExcludeItemIds = recentlyPlayedMovies.Select(i => i.Id).ToArray(), |
| | 0 | 277 | | EnableGroupByMetadataKey = true, |
| | 0 | 278 | | ParentId = parentId, |
| | 0 | 279 | | Recursive = true, |
| | 0 | 280 | | DtoOptions = dtoOptions |
| | 0 | 281 | | }); |
| | | 282 | | |
| | 0 | 283 | | var mostRecentMovies = recentlyPlayedMovies.Take(Math.Min(recentlyPlayedMovies.Count, 6)).ToList(); |
| | 0 | 284 | | var recentDirectors = GetPeopleNames(mostRecentMovies, [PersonType.Director]); |
| | 0 | 285 | | var recentActors = GetPeopleNames(mostRecentMovies, [PersonType.Actor, PersonType.GuestStar]); |
| | | 286 | | |
| | | 287 | | // Cap baseline items to categoryLimit - the round-robin can't use more categories than that. |
| | 0 | 288 | | var recentlyPlayedBaseline = recentlyPlayedMovies.Count > categoryLimit |
| | 0 | 289 | | ? recentlyPlayedMovies.Take(categoryLimit).ToList() |
| | 0 | 290 | | : recentlyPlayedMovies; |
| | 0 | 291 | | var likedBaseline = likedMovies.Count > categoryLimit |
| | 0 | 292 | | ? likedMovies.Take(categoryLimit).ToList() |
| | 0 | 293 | | : likedMovies; |
| | | 294 | | |
| | 0 | 295 | | var batchQuery = new SimilarItemsQuery |
| | 0 | 296 | | { |
| | 0 | 297 | | User = user, |
| | 0 | 298 | | Limit = itemLimit, |
| | 0 | 299 | | DtoOptions = dtoOptions |
| | 0 | 300 | | }; |
| | | 301 | | |
| | 0 | 302 | | var similarToRecentlyPlayed = await GetSimilarItemsRecommendationsAsync( |
| | 0 | 303 | | recentlyPlayedBaseline, |
| | 0 | 304 | | RecommendationType.SimilarToRecentlyPlayed, |
| | 0 | 305 | | batchQuery, |
| | 0 | 306 | | cancellationToken).ConfigureAwait(false); |
| | | 307 | | |
| | 0 | 308 | | var similarToLiked = await GetSimilarItemsRecommendationsAsync( |
| | 0 | 309 | | likedBaseline, |
| | 0 | 310 | | RecommendationType.SimilarToLikedItem, |
| | 0 | 311 | | batchQuery, |
| | 0 | 312 | | cancellationToken).ConfigureAwait(false); |
| | | 313 | | |
| | 0 | 314 | | var hasDirectorFromRecentlyPlayed = GetPersonRecommendations(user, recentDirectors, itemLimit, dtoOptions, Recom |
| | 0 | 315 | | var hasActorFromRecentlyPlayed = GetPersonRecommendations(user, recentActors, itemLimit, dtoOptions, Recommendat |
| | | 316 | | |
| | | 317 | | // Use a single enumerator per list, listed twice so MoveNext advances it |
| | | 318 | | // twice per round-robin pass (giving these categories double weight). |
| | | 319 | | // IMPORTANT: Declare as IEnumerator<T> to box the List<T>.Enumerator struct once; |
| | | 320 | | // using var would box separately per list insertion, creating independent copies. |
| | 0 | 321 | | IEnumerator<SimilarItemsRecommendation> similarToRecentlyPlayedEnum = similarToRecentlyPlayed.GetEnumerator(); |
| | 0 | 322 | | IEnumerator<SimilarItemsRecommendation> similarToLikedEnum = similarToLiked.GetEnumerator(); |
| | | 323 | | |
| | 0 | 324 | | var categoryTypes = new List<IEnumerator<SimilarItemsRecommendation>> |
| | 0 | 325 | | { |
| | 0 | 326 | | similarToRecentlyPlayedEnum, |
| | 0 | 327 | | similarToRecentlyPlayedEnum, |
| | 0 | 328 | | similarToLikedEnum, |
| | 0 | 329 | | similarToLikedEnum, |
| | 0 | 330 | | hasDirectorFromRecentlyPlayed.GetEnumerator(), |
| | 0 | 331 | | hasActorFromRecentlyPlayed.GetEnumerator() |
| | 0 | 332 | | }; |
| | | 333 | | |
| | 0 | 334 | | var categories = new List<SimilarItemsRecommendation>(); |
| | 0 | 335 | | while (categories.Count < categoryLimit) |
| | | 336 | | { |
| | 0 | 337 | | var allEmpty = true; |
| | 0 | 338 | | foreach (var category in categoryTypes) |
| | | 339 | | { |
| | 0 | 340 | | if (category.MoveNext()) |
| | | 341 | | { |
| | 0 | 342 | | categories.Add(category.Current); |
| | 0 | 343 | | allEmpty = false; |
| | | 344 | | |
| | 0 | 345 | | if (categories.Count >= categoryLimit) |
| | | 346 | | { |
| | | 347 | | break; |
| | | 348 | | } |
| | | 349 | | } |
| | | 350 | | } |
| | | 351 | | |
| | 0 | 352 | | if (allEmpty) |
| | | 353 | | { |
| | | 354 | | break; |
| | | 355 | | } |
| | | 356 | | } |
| | | 357 | | |
| | 0 | 358 | | return [.. categories.OrderBy(i => i.RecommendationType)]; |
| | 0 | 359 | | } |
| | | 360 | | |
| | | 361 | | private async Task<IReadOnlyList<SimilarItemsRecommendation>> GetSimilarItemsRecommendationsAsync( |
| | | 362 | | IReadOnlyList<BaseItem> baselineItems, |
| | | 363 | | RecommendationType recommendationType, |
| | | 364 | | SimilarItemsQuery query, |
| | | 365 | | CancellationToken cancellationToken) |
| | | 366 | | { |
| | 0 | 367 | | var batchProvider = _similarItemsProviders |
| | 0 | 368 | | .OfType<IBatchLocalSimilarItemsProvider>() |
| | 0 | 369 | | .FirstOrDefault(); |
| | | 370 | | |
| | 0 | 371 | | if (batchProvider is null || baselineItems.Count == 0) |
| | | 372 | | { |
| | 0 | 373 | | return []; |
| | | 374 | | } |
| | | 375 | | |
| | 0 | 376 | | var batchResults = await batchProvider.GetBatchSimilarItemsAsync(baselineItems, query, cancellationToken).Config |
| | | 377 | | |
| | 0 | 378 | | var recommendations = new List<SimilarItemsRecommendation>(baselineItems.Count); |
| | 0 | 379 | | foreach (var baseline in baselineItems) |
| | | 380 | | { |
| | 0 | 381 | | if (batchResults.TryGetValue(baseline.Id, out var similar) && similar.Count > 0) |
| | | 382 | | { |
| | 0 | 383 | | recommendations.Add(new SimilarItemsRecommendation |
| | 0 | 384 | | { |
| | 0 | 385 | | BaselineItemName = baseline.Name, |
| | 0 | 386 | | CategoryId = baseline.Id, |
| | 0 | 387 | | RecommendationType = recommendationType, |
| | 0 | 388 | | Items = similar |
| | 0 | 389 | | }); |
| | | 390 | | } |
| | | 391 | | } |
| | | 392 | | |
| | 0 | 393 | | return recommendations; |
| | 0 | 394 | | } |
| | | 395 | | |
| | | 396 | | private IEnumerable<SimilarItemsRecommendation> GetPersonRecommendations( |
| | | 397 | | User? user, |
| | | 398 | | IReadOnlyList<string> names, |
| | | 399 | | int itemLimit, |
| | | 400 | | DtoOptions dtoOptions, |
| | | 401 | | RecommendationType type, |
| | | 402 | | IReadOnlyList<BaseItemKind> itemTypes) |
| | | 403 | | { |
| | 0 | 404 | | var personTypes = type == RecommendationType.HasDirectorFromRecentlyPlayed |
| | 0 | 405 | | ? [PersonType.Director] |
| | 0 | 406 | | : Array.Empty<string>(); |
| | | 407 | | |
| | 0 | 408 | | foreach (var name in names) |
| | | 409 | | { |
| | 0 | 410 | | var items = _libraryManager.GetItemList(new InternalItemsQuery(user) |
| | 0 | 411 | | { |
| | 0 | 412 | | Person = name, |
| | 0 | 413 | | Limit = itemLimit + 2, |
| | 0 | 414 | | PersonTypes = personTypes, |
| | 0 | 415 | | IncludeItemTypes = itemTypes.ToArray(), |
| | 0 | 416 | | IsMovie = true, |
| | 0 | 417 | | IsPlayed = false, |
| | 0 | 418 | | EnableGroupByMetadataKey = true, |
| | 0 | 419 | | DtoOptions = dtoOptions |
| | 0 | 420 | | }) |
| | 0 | 421 | | .DistinctBy(i => i.GetProviderId(MetadataProvider.Imdb) ?? Guid.NewGuid().ToString("N", CultureInfo.Inva |
| | 0 | 422 | | .Take(itemLimit) |
| | 0 | 423 | | .ToList(); |
| | | 424 | | |
| | 0 | 425 | | if (items.Count > 0) |
| | | 426 | | { |
| | 0 | 427 | | yield return new SimilarItemsRecommendation |
| | 0 | 428 | | { |
| | 0 | 429 | | BaselineItemName = name, |
| | 0 | 430 | | CategoryId = name.GetMD5(), |
| | 0 | 431 | | RecommendationType = type, |
| | 0 | 432 | | Items = items |
| | 0 | 433 | | }; |
| | | 434 | | } |
| | | 435 | | } |
| | 0 | 436 | | } |
| | | 437 | | |
| | | 438 | | private IReadOnlyList<string> GetPeopleNames(IReadOnlyList<BaseItem> items, IReadOnlyList<string> personTypes) |
| | | 439 | | { |
| | 0 | 440 | | var itemIds = items.Select(i => i.Id).ToArray(); |
| | 0 | 441 | | return _libraryManager.GetPeopleNamesByItems(itemIds, personTypes) |
| | 0 | 442 | | .Values |
| | 0 | 443 | | .SelectMany(names => names) |
| | 0 | 444 | | .Distinct() |
| | 0 | 445 | | .ToArray(); |
| | | 446 | | } |
| | | 447 | | |
| | | 448 | | private List<(BaseItem Item, float Score)> ResolveRemoteReferences( |
| | | 449 | | IReadOnlyList<SimilarItemReference> references, |
| | | 450 | | int providerOrder, |
| | | 451 | | User? user, |
| | | 452 | | DtoOptions dtoOptions, |
| | | 453 | | BaseItemKind itemKind, |
| | | 454 | | HashSet<Guid> excludeIds, |
| | | 455 | | HashSet<string> excludeKeys) |
| | | 456 | | { |
| | 0 | 457 | | if (references.Count == 0) |
| | | 458 | | { |
| | 0 | 459 | | return []; |
| | | 460 | | } |
| | | 461 | | |
| | 0 | 462 | | var resolvedByKey = new Dictionary<string, (BaseItem Item, float Score)>(StringComparer.OrdinalIgnoreCase); |
| | 0 | 463 | | var providerLookup = new Dictionary<(string ProviderName, string ProviderId), (float? Score, int Position)>(Stri |
| | | 464 | | |
| | 0 | 465 | | foreach (var (position, match) in references.Index()) |
| | | 466 | | { |
| | 0 | 467 | | var lookupKey = (match.ProviderName, match.ProviderId); |
| | 0 | 468 | | if (!providerLookup.TryGetValue(lookupKey, out var existing)) |
| | | 469 | | { |
| | 0 | 470 | | providerLookup[lookupKey] = (match.Score, position); |
| | | 471 | | } |
| | 0 | 472 | | else if (match.Score > existing.Score || (match.Score == existing.Score && position < existing.Position)) |
| | | 473 | | { |
| | 0 | 474 | | providerLookup[lookupKey] = (match.Score, position); |
| | | 475 | | } |
| | | 476 | | } |
| | | 477 | | |
| | 0 | 478 | | var allProviderIds = providerLookup |
| | 0 | 479 | | .GroupBy(kvp => kvp.Key.ProviderName) |
| | 0 | 480 | | .ToDictionary(g => g.Key, g => g.Select(x => x.Key.ProviderId).ToArray()); |
| | | 481 | | |
| | 0 | 482 | | var query = new InternalItemsQuery(user) |
| | 0 | 483 | | { |
| | 0 | 484 | | HasAnyProviderIds = allProviderIds, |
| | 0 | 485 | | IncludeItemTypes = [itemKind], |
| | 0 | 486 | | DtoOptions = dtoOptions |
| | 0 | 487 | | }; |
| | | 488 | | |
| | 0 | 489 | | var items = _libraryManager.GetItemList(query); |
| | | 490 | | |
| | 0 | 491 | | foreach (var item in items) |
| | | 492 | | { |
| | 0 | 493 | | if (excludeIds.Contains(item.Id)) |
| | | 494 | | { |
| | | 495 | | continue; |
| | | 496 | | } |
| | | 497 | | |
| | 0 | 498 | | var presentationKey = item.GetPresentationUniqueKey(); |
| | 0 | 499 | | if (excludeKeys.Contains(presentationKey)) |
| | | 500 | | { |
| | | 501 | | continue; |
| | | 502 | | } |
| | | 503 | | |
| | 0 | 504 | | foreach (var providerName in allProviderIds.Keys) |
| | | 505 | | { |
| | 0 | 506 | | if (item.TryGetProviderId(providerName, out var itemProviderId) && providerLookup.TryGetValue((providerN |
| | | 507 | | { |
| | 0 | 508 | | var score = CalculateScore(matchInfo.Score, providerOrder, matchInfo.Position); |
| | 0 | 509 | | if (!resolvedByKey.TryGetValue(presentationKey, out var existing) || existing.Score < score) |
| | | 510 | | { |
| | 0 | 511 | | resolvedByKey[presentationKey] = (item, score); |
| | | 512 | | } |
| | | 513 | | |
| | 0 | 514 | | break; |
| | | 515 | | } |
| | | 516 | | } |
| | | 517 | | } |
| | | 518 | | |
| | 0 | 519 | | foreach (var (key, entry) in resolvedByKey) |
| | | 520 | | { |
| | 0 | 521 | | excludeIds.Add(entry.Item.Id); |
| | 0 | 522 | | excludeKeys.Add(key); |
| | | 523 | | } |
| | | 524 | | |
| | 0 | 525 | | return [.. resolvedByKey.Values]; |
| | | 526 | | } |
| | | 527 | | |
| | | 528 | | private static float CalculateScore(float? matchScore, int providerOrder, int position) |
| | | 529 | | { |
| | | 530 | | // Use provider-supplied score if available, otherwise derive from position |
| | 0 | 531 | | var baseScore = matchScore ?? (1.0f - (position * 0.02f)); |
| | | 532 | | |
| | | 533 | | // Apply small boost based on provider order (higher priority providers get small bonus) |
| | 0 | 534 | | var priorityBoost = Math.Max(0, 10 - providerOrder) * 0.005f; |
| | | 535 | | |
| | 0 | 536 | | return Math.Clamp(baseScore + priorityBoost, 0f, 1f); |
| | | 537 | | } |
| | | 538 | | |
| | | 539 | | private static int GetConfiguredSimilarProviderOrder(string[]? orderConfig, string providerName) |
| | | 540 | | { |
| | 0 | 541 | | if (orderConfig is null || orderConfig.Length == 0) |
| | | 542 | | { |
| | 0 | 543 | | return int.MaxValue; |
| | | 544 | | } |
| | | 545 | | |
| | 0 | 546 | | var index = Array.FindIndex(orderConfig, name => string.Equals(name, providerName, StringComparison.OrdinalIgnor |
| | 0 | 547 | | return index >= 0 ? index : int.MaxValue; |
| | | 548 | | } |
| | | 549 | | |
| | | 550 | | private string GetSimilarItemsCachePath(string providerName, string baseItemType, Guid itemId) |
| | | 551 | | { |
| | 0 | 552 | | var dataPath = Path.Combine( |
| | 0 | 553 | | _appPaths.CachePath, |
| | 0 | 554 | | $"{providerName.ToLowerInvariant()}-similar-{baseItemType.ToLowerInvariant()}"); |
| | 0 | 555 | | return Path.Combine(dataPath, $"{itemId.ToString("N", CultureInfo.InvariantCulture)}.json"); |
| | | 556 | | } |
| | | 557 | | |
| | | 558 | | private async Task<List<SimilarItemReference>?> TryReadSimilarItemsCacheAsync(string cachePath, CancellationToken ca |
| | | 559 | | { |
| | 0 | 560 | | var fileInfo = _fileSystem.GetFileSystemInfo(cachePath); |
| | 0 | 561 | | if (!fileInfo.Exists || fileInfo.Length == 0) |
| | | 562 | | { |
| | 0 | 563 | | return null; |
| | | 564 | | } |
| | | 565 | | |
| | | 566 | | try |
| | | 567 | | { |
| | 0 | 568 | | var stream = File.OpenRead(cachePath); |
| | 0 | 569 | | await using (stream.ConfigureAwait(false)) |
| | | 570 | | { |
| | 0 | 571 | | var cache = await JsonSerializer.DeserializeAsync<SimilarItemsCache>(stream, JsonDefaults.Options, cance |
| | 0 | 572 | | if (cache?.References is not null && DateTime.UtcNow < cache.ExpiresAt) |
| | | 573 | | { |
| | 0 | 574 | | return cache.References; |
| | | 575 | | } |
| | | 576 | | } |
| | 0 | 577 | | } |
| | 0 | 578 | | catch (IOException ex) |
| | | 579 | | { |
| | 0 | 580 | | _logger.LogWarning(ex, "Failed to read similar items cache from {CachePath}", cachePath); |
| | 0 | 581 | | } |
| | 0 | 582 | | catch (JsonException ex) |
| | | 583 | | { |
| | 0 | 584 | | _logger.LogWarning(ex, "Failed to parse similar items cache from {CachePath}", cachePath); |
| | 0 | 585 | | } |
| | | 586 | | |
| | 0 | 587 | | return null; |
| | 0 | 588 | | } |
| | | 589 | | |
| | | 590 | | private async Task SaveSimilarItemsCacheAsync(string cachePath, List<SimilarItemReference> references, TimeSpan cach |
| | | 591 | | { |
| | | 592 | | try |
| | | 593 | | { |
| | 0 | 594 | | var directory = Path.GetDirectoryName(cachePath); |
| | 0 | 595 | | if (!string.IsNullOrEmpty(directory)) |
| | | 596 | | { |
| | 0 | 597 | | Directory.CreateDirectory(directory); |
| | | 598 | | } |
| | | 599 | | |
| | 0 | 600 | | var cache = new SimilarItemsCache |
| | 0 | 601 | | { |
| | 0 | 602 | | References = references, |
| | 0 | 603 | | ExpiresAt = DateTime.UtcNow.Add(cacheDuration) |
| | 0 | 604 | | }; |
| | | 605 | | |
| | 0 | 606 | | var stream = File.Create(cachePath); |
| | 0 | 607 | | await using (stream.ConfigureAwait(false)) |
| | | 608 | | { |
| | 0 | 609 | | await JsonSerializer.SerializeAsync(stream, cache, JsonDefaults.Options, cancellationToken).ConfigureAwa |
| | | 610 | | } |
| | 0 | 611 | | } |
| | 0 | 612 | | catch (IOException ex) |
| | | 613 | | { |
| | 0 | 614 | | _logger.LogWarning(ex, "Failed to save similar items cache to {CachePath}", cachePath); |
| | 0 | 615 | | } |
| | 0 | 616 | | } |
| | | 617 | | |
| | | 618 | | private sealed class SimilarItemsCache |
| | | 619 | | { |
| | | 620 | | public List<SimilarItemReference>? References { get; set; } |
| | | 621 | | |
| | | 622 | | public DateTime ExpiresAt { get; set; } |
| | | 623 | | } |
| | | 624 | | |
| | | 625 | | private sealed class StringTupleComparer : IEqualityComparer<(string Key, string Value)> |
| | | 626 | | { |
| | 0 | 627 | | public static readonly StringTupleComparer Instance = new(); |
| | | 628 | | |
| | | 629 | | public bool Equals((string Key, string Value) x, (string Key, string Value) y) |
| | 0 | 630 | | => string.Equals(x.Key, y.Key, StringComparison.OrdinalIgnoreCase) && |
| | 0 | 631 | | string.Equals(x.Value, y.Value, StringComparison.OrdinalIgnoreCase); |
| | | 632 | | |
| | | 633 | | public int GetHashCode((string Key, string Value) obj) |
| | 0 | 634 | | => HashCode.Combine( |
| | 0 | 635 | | StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Key), |
| | 0 | 636 | | StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Value)); |
| | | 637 | | } |
| | | 638 | | } |