| | | 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.Extensions.Json; |
| | | 12 | | using MediaBrowser.Controller; |
| | | 13 | | using MediaBrowser.Controller.Dto; |
| | | 14 | | using MediaBrowser.Controller.Entities; |
| | | 15 | | using MediaBrowser.Controller.Library; |
| | | 16 | | using MediaBrowser.Model.Configuration; |
| | | 17 | | using MediaBrowser.Model.Entities; |
| | | 18 | | using MediaBrowser.Model.IO; |
| | | 19 | | using MediaBrowser.Model.Querying; |
| | | 20 | | using Microsoft.Extensions.Logging; |
| | | 21 | | |
| | | 22 | | namespace Emby.Server.Implementations.Library.SimilarItems; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Manages similar items providers and orchestrates similar items operations. |
| | | 26 | | /// </summary> |
| | | 27 | | public class SimilarItemsManager : ISimilarItemsManager |
| | | 28 | | { |
| | | 29 | | private readonly ILogger<SimilarItemsManager> _logger; |
| | | 30 | | private readonly IServerApplicationPaths _appPaths; |
| | | 31 | | private readonly ILibraryManager _libraryManager; |
| | | 32 | | private readonly IFileSystem _fileSystem; |
| | 21 | 33 | | private ISimilarItemsProvider[] _similarItemsProviders = []; |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Initializes a new instance of the <see cref="SimilarItemsManager"/> class. |
| | | 37 | | /// </summary> |
| | | 38 | | /// <param name="logger">The logger.</param> |
| | | 39 | | /// <param name="appPaths">The server application paths.</param> |
| | | 40 | | /// <param name="libraryManager">The library manager.</param> |
| | | 41 | | /// <param name="fileSystem">The file system.</param> |
| | | 42 | | public SimilarItemsManager( |
| | | 43 | | ILogger<SimilarItemsManager> logger, |
| | | 44 | | IServerApplicationPaths appPaths, |
| | | 45 | | ILibraryManager libraryManager, |
| | | 46 | | IFileSystem fileSystem) |
| | | 47 | | { |
| | 21 | 48 | | _logger = logger; |
| | 21 | 49 | | _appPaths = appPaths; |
| | 21 | 50 | | _libraryManager = libraryManager; |
| | 21 | 51 | | _fileSystem = fileSystem; |
| | 21 | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc/> |
| | | 55 | | public void AddParts(IEnumerable<ISimilarItemsProvider> providers) |
| | | 56 | | { |
| | 21 | 57 | | _similarItemsProviders = providers.ToArray(); |
| | 21 | 58 | | } |
| | | 59 | | |
| | | 60 | | /// <inheritdoc/> |
| | | 61 | | public IReadOnlyList<ISimilarItemsProvider> GetSimilarItemsProviders<T>() |
| | | 62 | | where T : BaseItem |
| | | 63 | | { |
| | 0 | 64 | | var itemType = typeof(T); |
| | 0 | 65 | | return _similarItemsProviders |
| | 0 | 66 | | .Where(p => (p is ILocalSimilarItemsProvider local && local.Supports(itemType)) |
| | 0 | 67 | | || (p is IRemoteSimilarItemsProvider remote && remote.Supports(itemType))) |
| | 0 | 68 | | .ToList(); |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <inheritdoc/> |
| | | 72 | | public async Task<IReadOnlyList<BaseItem>> GetSimilarItemsAsync( |
| | | 73 | | BaseItem item, |
| | | 74 | | IReadOnlyList<Guid> excludeArtistIds, |
| | | 75 | | User? user, |
| | | 76 | | DtoOptions dtoOptions, |
| | | 77 | | int? limit, |
| | | 78 | | LibraryOptions? libraryOptions, |
| | | 79 | | CancellationToken cancellationToken) |
| | | 80 | | { |
| | 0 | 81 | | ArgumentNullException.ThrowIfNull(item); |
| | 0 | 82 | | ArgumentNullException.ThrowIfNull(excludeArtistIds); |
| | | 83 | | |
| | 0 | 84 | | var itemType = item.GetType(); |
| | 0 | 85 | | var requestedLimit = limit ?? 50; |
| | 0 | 86 | | var itemKind = item.GetBaseItemKind(); |
| | | 87 | | |
| | | 88 | | // Ensure ProviderIds is included in DtoOptions for matching remote provider responses |
| | 0 | 89 | | if (!dtoOptions.Fields.Contains(ItemFields.ProviderIds)) |
| | | 90 | | { |
| | 0 | 91 | | dtoOptions.Fields = dtoOptions.Fields.Concat([ItemFields.ProviderIds]).ToArray(); |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | // Local providers are always enabled. Remote providers must be explicitly enabled. |
| | 0 | 95 | | var localProviders = _similarItemsProviders |
| | 0 | 96 | | .OfType<ILocalSimilarItemsProvider>() |
| | 0 | 97 | | .Where(p => p.Supports(itemType)) |
| | 0 | 98 | | .ToList(); |
| | 0 | 99 | | var remoteProviders = _similarItemsProviders |
| | 0 | 100 | | .OfType<IRemoteSimilarItemsProvider>() |
| | 0 | 101 | | .Where(p => p.Supports(itemType)); |
| | 0 | 102 | | var matchingProviders = new List<ISimilarItemsProvider>(localProviders); |
| | | 103 | | |
| | 0 | 104 | | var typeOptions = libraryOptions?.GetTypeOptions(itemType.Name); |
| | 0 | 105 | | if (typeOptions?.SimilarItemProviders?.Length > 0) |
| | | 106 | | { |
| | 0 | 107 | | matchingProviders.AddRange(remoteProviders |
| | 0 | 108 | | .Where(p => typeOptions.SimilarItemProviders.Contains(p.Name, StringComparer.OrdinalIgnoreCase))); |
| | | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | var orderConfig = typeOptions?.SimilarItemProviderOrder is { Length: > 0 } order |
| | 0 | 112 | | ? order |
| | 0 | 113 | | : typeOptions?.SimilarItemProviders; |
| | 0 | 114 | | var orderedProviders = matchingProviders |
| | 0 | 115 | | .OrderBy(p => GetConfiguredSimilarProviderOrder(orderConfig, p.Name)) |
| | 0 | 116 | | .ToList(); |
| | | 117 | | |
| | 0 | 118 | | var allResults = new List<(BaseItem Item, float Score)>(); |
| | 0 | 119 | | var excludeIds = new HashSet<Guid> { item.Id }; |
| | 0 | 120 | | foreach (var (providerOrder, provider) in orderedProviders.Index()) |
| | | 121 | | { |
| | 0 | 122 | | if (allResults.Count >= requestedLimit || cancellationToken.IsCancellationRequested) |
| | | 123 | | { |
| | | 124 | | break; |
| | | 125 | | } |
| | | 126 | | |
| | | 127 | | try |
| | | 128 | | { |
| | 0 | 129 | | if (provider is ILocalSimilarItemsProvider localProvider) |
| | | 130 | | { |
| | 0 | 131 | | var query = new SimilarItemsQuery |
| | 0 | 132 | | { |
| | 0 | 133 | | User = user, |
| | 0 | 134 | | Limit = requestedLimit - allResults.Count, |
| | 0 | 135 | | DtoOptions = dtoOptions, |
| | 0 | 136 | | ExcludeItemIds = [.. excludeIds], |
| | 0 | 137 | | ExcludeArtistIds = excludeArtistIds |
| | 0 | 138 | | }; |
| | | 139 | | |
| | 0 | 140 | | var items = await localProvider.GetSimilarItemsAsync(item, query, cancellationToken).ConfigureAwait( |
| | | 141 | | |
| | 0 | 142 | | foreach (var (position, resultItem) in items.Index()) |
| | | 143 | | { |
| | 0 | 144 | | if (excludeIds.Add(resultItem.Id)) |
| | | 145 | | { |
| | 0 | 146 | | var score = CalculateScore(null, providerOrder, position); |
| | 0 | 147 | | allResults.Add((resultItem, score)); |
| | | 148 | | } |
| | | 149 | | } |
| | | 150 | | } |
| | 0 | 151 | | else if (provider is IRemoteSimilarItemsProvider remoteProvider) |
| | | 152 | | { |
| | 0 | 153 | | var cachePath = GetSimilarItemsCachePath(provider.Name, itemType.Name, item.Id); |
| | | 154 | | |
| | 0 | 155 | | var cachedReferences = await TryReadSimilarItemsCacheAsync(cachePath, cancellationToken).ConfigureAw |
| | 0 | 156 | | if (cachedReferences is not null) |
| | | 157 | | { |
| | 0 | 158 | | var resolvedItems = ResolveRemoteReferences(cachedReferences, providerOrder, user, dtoOptions, i |
| | 0 | 159 | | allResults.AddRange(resolvedItems); |
| | 0 | 160 | | continue; |
| | | 161 | | } |
| | | 162 | | |
| | 0 | 163 | | var query = new SimilarItemsQuery |
| | 0 | 164 | | { |
| | 0 | 165 | | User = user, |
| | 0 | 166 | | Limit = requestedLimit - allResults.Count, |
| | 0 | 167 | | DtoOptions = dtoOptions, |
| | 0 | 168 | | ExcludeItemIds = [.. excludeIds], |
| | 0 | 169 | | ExcludeArtistIds = excludeArtistIds |
| | 0 | 170 | | }; |
| | | 171 | | |
| | | 172 | | // Collect references in batches and resolve against local library. |
| | | 173 | | // Stop fetching once we have enough resolved local items. |
| | | 174 | | const int BatchSize = 20; |
| | 0 | 175 | | var remaining = requestedLimit - allResults.Count; |
| | 0 | 176 | | var collectedReferences = new List<SimilarItemReference>(); |
| | 0 | 177 | | var pendingBatch = new List<SimilarItemReference>(); |
| | | 178 | | |
| | 0 | 179 | | await foreach (var reference in remoteProvider.GetSimilarItemsAsync(item, query, cancellationToken). |
| | | 180 | | { |
| | 0 | 181 | | collectedReferences.Add(reference); |
| | 0 | 182 | | pendingBatch.Add(reference); |
| | | 183 | | |
| | 0 | 184 | | if (pendingBatch.Count >= BatchSize) |
| | | 185 | | { |
| | 0 | 186 | | var resolvedItems = ResolveRemoteReferences(pendingBatch, providerOrder, user, dtoOptions, i |
| | 0 | 187 | | allResults.AddRange(resolvedItems); |
| | 0 | 188 | | remaining -= resolvedItems.Count; |
| | 0 | 189 | | pendingBatch.Clear(); |
| | | 190 | | |
| | 0 | 191 | | if (remaining <= 0) |
| | | 192 | | { |
| | | 193 | | break; |
| | | 194 | | } |
| | | 195 | | } |
| | | 196 | | } |
| | | 197 | | |
| | | 198 | | // Resolve any remaining references in the last partial batch |
| | 0 | 199 | | if (pendingBatch.Count > 0) |
| | | 200 | | { |
| | 0 | 201 | | var resolvedItems = ResolveRemoteReferences(pendingBatch, providerOrder, user, dtoOptions, itemK |
| | 0 | 202 | | allResults.AddRange(resolvedItems); |
| | | 203 | | } |
| | | 204 | | |
| | 0 | 205 | | if (collectedReferences.Count > 0 && provider.CacheDuration is not null) |
| | | 206 | | { |
| | 0 | 207 | | await SaveSimilarItemsCacheAsync(cachePath, collectedReferences, provider.CacheDuration.Value, c |
| | | 208 | | } |
| | 0 | 209 | | } |
| | 0 | 210 | | } |
| | 0 | 211 | | catch (OperationCanceledException) |
| | | 212 | | { |
| | 0 | 213 | | break; |
| | | 214 | | } |
| | 0 | 215 | | catch (Exception ex) |
| | | 216 | | { |
| | 0 | 217 | | _logger.LogWarning(ex, "Similar items provider {ProviderName} failed for item {ItemId}", provider.Name, |
| | 0 | 218 | | } |
| | 0 | 219 | | } |
| | | 220 | | |
| | 0 | 221 | | return allResults |
| | 0 | 222 | | .OrderByDescending(x => x.Score) |
| | 0 | 223 | | .Select(x => x.Item) |
| | 0 | 224 | | .Take(requestedLimit) |
| | 0 | 225 | | .ToList(); |
| | 0 | 226 | | } |
| | | 227 | | |
| | | 228 | | private List<(BaseItem Item, float Score)> ResolveRemoteReferences( |
| | | 229 | | IReadOnlyList<SimilarItemReference> references, |
| | | 230 | | int providerOrder, |
| | | 231 | | User? user, |
| | | 232 | | DtoOptions dtoOptions, |
| | | 233 | | BaseItemKind itemKind, |
| | | 234 | | HashSet<Guid> excludeIds) |
| | | 235 | | { |
| | 0 | 236 | | if (references.Count == 0) |
| | | 237 | | { |
| | 0 | 238 | | return []; |
| | | 239 | | } |
| | | 240 | | |
| | 0 | 241 | | var resolvedById = new Dictionary<Guid, (BaseItem Item, float Score)>(); |
| | 0 | 242 | | var providerLookup = new Dictionary<(string ProviderName, string ProviderId), (float? Score, int Position)>(Stri |
| | | 243 | | |
| | 0 | 244 | | foreach (var (position, match) in references.Index()) |
| | | 245 | | { |
| | 0 | 246 | | var lookupKey = (match.ProviderName, match.ProviderId); |
| | 0 | 247 | | if (!providerLookup.TryGetValue(lookupKey, out var existing)) |
| | | 248 | | { |
| | 0 | 249 | | providerLookup[lookupKey] = (match.Score, position); |
| | | 250 | | } |
| | 0 | 251 | | else if (match.Score > existing.Score || (match.Score == existing.Score && position < existing.Position)) |
| | | 252 | | { |
| | 0 | 253 | | providerLookup[lookupKey] = (match.Score, position); |
| | | 254 | | } |
| | | 255 | | } |
| | | 256 | | |
| | 0 | 257 | | var allProviderIds = providerLookup |
| | 0 | 258 | | .GroupBy(kvp => kvp.Key.ProviderName) |
| | 0 | 259 | | .ToDictionary(g => g.Key, g => g.Select(x => x.Key.ProviderId).ToArray()); |
| | | 260 | | |
| | 0 | 261 | | var query = new InternalItemsQuery(user) |
| | 0 | 262 | | { |
| | 0 | 263 | | HasAnyProviderIds = allProviderIds, |
| | 0 | 264 | | IncludeItemTypes = [itemKind], |
| | 0 | 265 | | DtoOptions = dtoOptions |
| | 0 | 266 | | }; |
| | | 267 | | |
| | 0 | 268 | | var items = _libraryManager.GetItemList(query); |
| | | 269 | | |
| | 0 | 270 | | foreach (var item in items) |
| | | 271 | | { |
| | 0 | 272 | | if (excludeIds.Contains(item.Id) || resolvedById.ContainsKey(item.Id)) |
| | | 273 | | { |
| | | 274 | | continue; |
| | | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | foreach (var providerName in allProviderIds.Keys) |
| | | 278 | | { |
| | 0 | 279 | | if (item.TryGetProviderId(providerName, out var itemProviderId) && providerLookup.TryGetValue((providerN |
| | | 280 | | { |
| | 0 | 281 | | var score = CalculateScore(matchInfo.Score, providerOrder, matchInfo.Position); |
| | 0 | 282 | | if (!resolvedById.TryGetValue(item.Id, out var existing) || existing.Score < score) |
| | | 283 | | { |
| | 0 | 284 | | excludeIds.Add(item.Id); |
| | 0 | 285 | | resolvedById[item.Id] = (item, score); |
| | | 286 | | } |
| | | 287 | | |
| | 0 | 288 | | break; |
| | | 289 | | } |
| | | 290 | | } |
| | | 291 | | } |
| | | 292 | | |
| | 0 | 293 | | return [.. resolvedById.Values]; |
| | | 294 | | } |
| | | 295 | | |
| | | 296 | | private static float CalculateScore(float? matchScore, int providerOrder, int position) |
| | | 297 | | { |
| | | 298 | | // Use provider-supplied score if available, otherwise derive from position |
| | 0 | 299 | | var baseScore = matchScore ?? (1.0f - (position * 0.02f)); |
| | | 300 | | |
| | | 301 | | // Apply small boost based on provider order (higher priority providers get small bonus) |
| | 0 | 302 | | var priorityBoost = Math.Max(0, 10 - providerOrder) * 0.005f; |
| | | 303 | | |
| | 0 | 304 | | return Math.Clamp(baseScore + priorityBoost, 0f, 1f); |
| | | 305 | | } |
| | | 306 | | |
| | | 307 | | private static int GetConfiguredSimilarProviderOrder(string[]? orderConfig, string providerName) |
| | | 308 | | { |
| | 0 | 309 | | if (orderConfig is null || orderConfig.Length == 0) |
| | | 310 | | { |
| | 0 | 311 | | return int.MaxValue; |
| | | 312 | | } |
| | | 313 | | |
| | 0 | 314 | | var index = Array.FindIndex(orderConfig, name => string.Equals(name, providerName, StringComparison.OrdinalIgnor |
| | 0 | 315 | | return index >= 0 ? index : int.MaxValue; |
| | | 316 | | } |
| | | 317 | | |
| | | 318 | | private string GetSimilarItemsCachePath(string providerName, string baseItemType, Guid itemId) |
| | | 319 | | { |
| | 0 | 320 | | var dataPath = Path.Combine( |
| | 0 | 321 | | _appPaths.CachePath, |
| | 0 | 322 | | $"{providerName.ToLowerInvariant()}-similar-{baseItemType.ToLowerInvariant()}"); |
| | 0 | 323 | | return Path.Combine(dataPath, $"{itemId.ToString("N", CultureInfo.InvariantCulture)}.json"); |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | private async Task<List<SimilarItemReference>?> TryReadSimilarItemsCacheAsync(string cachePath, CancellationToken ca |
| | | 327 | | { |
| | 0 | 328 | | var fileInfo = _fileSystem.GetFileSystemInfo(cachePath); |
| | 0 | 329 | | if (!fileInfo.Exists || fileInfo.Length == 0) |
| | | 330 | | { |
| | 0 | 331 | | return null; |
| | | 332 | | } |
| | | 333 | | |
| | | 334 | | try |
| | | 335 | | { |
| | 0 | 336 | | var stream = File.OpenRead(cachePath); |
| | 0 | 337 | | await using (stream.ConfigureAwait(false)) |
| | | 338 | | { |
| | 0 | 339 | | var cache = await JsonSerializer.DeserializeAsync<SimilarItemsCache>(stream, JsonDefaults.Options, cance |
| | 0 | 340 | | if (cache?.References is not null && DateTime.UtcNow < cache.ExpiresAt) |
| | | 341 | | { |
| | 0 | 342 | | return cache.References; |
| | | 343 | | } |
| | | 344 | | } |
| | 0 | 345 | | } |
| | 0 | 346 | | catch (IOException ex) |
| | | 347 | | { |
| | 0 | 348 | | _logger.LogWarning(ex, "Failed to read similar items cache from {CachePath}", cachePath); |
| | 0 | 349 | | } |
| | 0 | 350 | | catch (JsonException ex) |
| | | 351 | | { |
| | 0 | 352 | | _logger.LogWarning(ex, "Failed to parse similar items cache from {CachePath}", cachePath); |
| | 0 | 353 | | } |
| | | 354 | | |
| | 0 | 355 | | return null; |
| | 0 | 356 | | } |
| | | 357 | | |
| | | 358 | | private async Task SaveSimilarItemsCacheAsync(string cachePath, List<SimilarItemReference> references, TimeSpan cach |
| | | 359 | | { |
| | | 360 | | try |
| | | 361 | | { |
| | 0 | 362 | | var directory = Path.GetDirectoryName(cachePath); |
| | 0 | 363 | | if (!string.IsNullOrEmpty(directory)) |
| | | 364 | | { |
| | 0 | 365 | | Directory.CreateDirectory(directory); |
| | | 366 | | } |
| | | 367 | | |
| | 0 | 368 | | var cache = new SimilarItemsCache |
| | 0 | 369 | | { |
| | 0 | 370 | | References = references, |
| | 0 | 371 | | ExpiresAt = DateTime.UtcNow.Add(cacheDuration) |
| | 0 | 372 | | }; |
| | | 373 | | |
| | 0 | 374 | | var stream = File.Create(cachePath); |
| | 0 | 375 | | await using (stream.ConfigureAwait(false)) |
| | | 376 | | { |
| | 0 | 377 | | await JsonSerializer.SerializeAsync(stream, cache, JsonDefaults.Options, cancellationToken).ConfigureAwa |
| | | 378 | | } |
| | 0 | 379 | | } |
| | 0 | 380 | | catch (IOException ex) |
| | | 381 | | { |
| | 0 | 382 | | _logger.LogWarning(ex, "Failed to save similar items cache to {CachePath}", cachePath); |
| | 0 | 383 | | } |
| | 0 | 384 | | } |
| | | 385 | | |
| | | 386 | | private sealed class SimilarItemsCache |
| | | 387 | | { |
| | | 388 | | public List<SimilarItemReference>? References { get; set; } |
| | | 389 | | |
| | | 390 | | public DateTime ExpiresAt { get; set; } |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | private sealed class StringTupleComparer : IEqualityComparer<(string Key, string Value)> |
| | | 394 | | { |
| | 0 | 395 | | public static readonly StringTupleComparer Instance = new(); |
| | | 396 | | |
| | | 397 | | public bool Equals((string Key, string Value) x, (string Key, string Value) y) |
| | 0 | 398 | | => string.Equals(x.Key, y.Key, StringComparison.OrdinalIgnoreCase) && |
| | 0 | 399 | | string.Equals(x.Value, y.Value, StringComparison.OrdinalIgnoreCase); |
| | | 400 | | |
| | | 401 | | public int GetHashCode((string Key, string Value) obj) |
| | 0 | 402 | | => HashCode.Combine( |
| | 0 | 403 | | StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Key), |
| | 0 | 404 | | StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Value)); |
| | | 405 | | } |
| | | 406 | | } |