| | | 1 | | #pragma warning disable RS0030 // Do not use banned APIs |
| | | 2 | | #pragma warning disable CA1862 // Use the 'StringComparison' method overloads to perform case-insensitive string compari |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using Jellyfin.Data.Enums; |
| | | 10 | | using Jellyfin.Database.Implementations; |
| | | 11 | | using Jellyfin.Database.Implementations.Entities; |
| | | 12 | | using Jellyfin.Extensions; |
| | | 13 | | using MediaBrowser.Controller.Entities; |
| | | 14 | | using MediaBrowser.Controller.Library; |
| | | 15 | | using MediaBrowser.Controller.Persistence; |
| | | 16 | | using MediaBrowser.Model.Configuration; |
| | | 17 | | using Microsoft.EntityFrameworkCore; |
| | | 18 | | |
| | | 19 | | namespace Emby.Server.Implementations.Library.Search; |
| | | 20 | | |
| | | 21 | | /// <summary> |
| | | 22 | | /// Built-in SQL-based search provider that queries the library database directly. |
| | | 23 | | /// </summary> |
| | | 24 | | public class SqlSearchProvider : IInternalSearchProvider |
| | | 25 | | { |
| | | 26 | | private const int DefaultSearchLimit = 100; |
| | | 27 | | private const float ExactMatchScore = 100f; |
| | | 28 | | private const float PrefixMatchScore = 80f; |
| | | 29 | | private const float WordPrefixMatchScore = 75f; |
| | | 30 | | private const float ContainsMatchScore = 50f; |
| | | 31 | | |
| | 0 | 32 | | private static readonly Guid _placeholderId = Guid.Parse("00000000-0000-0000-0000-000000000001"); |
| | | 33 | | |
| | | 34 | | private readonly IDbContextFactory<JellyfinDbContext> _dbProvider; |
| | | 35 | | private readonly IItemTypeLookup _itemTypeLookup; |
| | | 36 | | private readonly ILibraryManager _libraryManager; |
| | | 37 | | private readonly IUserManager _userManager; |
| | | 38 | | private readonly IItemQueryHelpers _queryHelpers; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Initializes a new instance of the <see cref="SqlSearchProvider"/> class. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="dbProvider">The database context factory.</param> |
| | | 44 | | /// <param name="itemTypeLookup">The item type lookup.</param> |
| | | 45 | | /// <param name="libraryManager">The library manager.</param> |
| | | 46 | | /// <param name="userManager">The user manager.</param> |
| | | 47 | | /// <param name="queryHelpers">The shared item query helpers.</param> |
| | | 48 | | public SqlSearchProvider( |
| | | 49 | | IDbContextFactory<JellyfinDbContext> dbProvider, |
| | | 50 | | IItemTypeLookup itemTypeLookup, |
| | | 51 | | ILibraryManager libraryManager, |
| | | 52 | | IUserManager userManager, |
| | | 53 | | IItemQueryHelpers queryHelpers) |
| | | 54 | | { |
| | 21 | 55 | | _dbProvider = dbProvider; |
| | 21 | 56 | | _itemTypeLookup = itemTypeLookup; |
| | 21 | 57 | | _libraryManager = libraryManager; |
| | 21 | 58 | | _userManager = userManager; |
| | 21 | 59 | | _queryHelpers = queryHelpers; |
| | 21 | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <inheritdoc/> |
| | 21 | 63 | | public string Name => "Database"; |
| | | 64 | | |
| | | 65 | | /// <inheritdoc/> |
| | 0 | 66 | | public MetadataPluginType Type => MetadataPluginType.SearchProvider; |
| | | 67 | | |
| | | 68 | | /// <inheritdoc/> |
| | 21 | 69 | | public int Priority => 100; // Low priority - runs as fallback |
| | | 70 | | |
| | | 71 | | /// <inheritdoc/> |
| | | 72 | | public bool CanSearch(SearchProviderQuery query) |
| | | 73 | | { |
| | | 74 | | // SQL search can always handle any query |
| | 0 | 75 | | return true; |
| | | 76 | | } |
| | | 77 | | |
| | | 78 | | /// <inheritdoc/> |
| | | 79 | | public async Task<IReadOnlyList<SearchResult>> SearchAsync(SearchProviderQuery query, CancellationToken cancellation |
| | | 80 | | { |
| | 0 | 81 | | ArgumentNullException.ThrowIfNull(query); |
| | 0 | 82 | | ArgumentException.ThrowIfNullOrWhiteSpace(query.SearchTerm); |
| | | 83 | | |
| | 0 | 84 | | var rawSearchTerm = query.SearchTerm.Trim().RemoveDiacritics(); |
| | 0 | 85 | | if (string.IsNullOrEmpty(rawSearchTerm)) |
| | | 86 | | { |
| | 0 | 87 | | return []; |
| | | 88 | | } |
| | | 89 | | |
| | 0 | 90 | | var cleanSearchTerm = rawSearchTerm.GetCleanValue(); |
| | 0 | 91 | | if (string.IsNullOrEmpty(cleanSearchTerm)) |
| | | 92 | | { |
| | 0 | 93 | | return []; |
| | | 94 | | } |
| | | 95 | | |
| | 0 | 96 | | var cleanPrefix = cleanSearchTerm + " "; |
| | | 97 | | // OriginalTitle is stored mixed-case and isn't pre-normalized like CleanName, |
| | | 98 | | // so match it via a case-insensitive LIKE rather than a per-row case conversion |
| | | 99 | | // that may not translate to SQL on every provider. |
| | 0 | 100 | | var likeOriginal = $"%{rawSearchTerm}%"; |
| | 0 | 101 | | var limit = query.Limit ?? DefaultSearchLimit; |
| | | 102 | | |
| | 0 | 103 | | var dbContext = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 104 | | await using (dbContext.ConfigureAwait(false)) |
| | | 105 | | { |
| | | 106 | | // Lightweight projection: select only what's needed to score and identify items. |
| | 0 | 107 | | var dbQuery = dbContext.BaseItems |
| | 0 | 108 | | .AsNoTracking() |
| | 0 | 109 | | .Where(e => e.Id != _placeholderId) |
| | 0 | 110 | | .Where(e => !e.IsVirtualItem) |
| | 0 | 111 | | .Where(e => e.CleanName!.Contains(cleanSearchTerm) |
| | 0 | 112 | | || (e.OriginalTitle != null && EF.Functions.Like(e.OriginalTitle, likeOriginal))); |
| | | 113 | | |
| | 0 | 114 | | dbQuery = ApplyTypeFilter(dbQuery, query.IncludeItemTypes, query.ExcludeItemTypes); |
| | 0 | 115 | | dbQuery = ApplyMediaTypeFilter(dbQuery, query.MediaTypes); |
| | 0 | 116 | | dbQuery = ApplyParentFilter(dbQuery, query.ParentId); |
| | 0 | 117 | | dbQuery = ApplyUserAccessFilter(dbContext, dbQuery, query.UserId); |
| | | 118 | | |
| | | 119 | | // Compute the score in SQL: the ternary translates to a CASE WHEN. CleanName is |
| | | 120 | | // the pre-normalized (lowercase, diacritic-stripped) form, so we score against it |
| | | 121 | | // directly without any per-row case conversion. Items that match only via |
| | | 122 | | // OriginalTitle fall through to the Contains tier. |
| | | 123 | | // Tie-break by Id for deterministic ordering so the explicit OrderBy + Take |
| | | 124 | | // satisfies EF Core's row-limiting-with-OrderBy requirement. |
| | 0 | 125 | | var scored = dbQuery.Select(e => new |
| | 0 | 126 | | { |
| | 0 | 127 | | e.Id, |
| | 0 | 128 | | Score = |
| | 0 | 129 | | (e.CleanName == cleanSearchTerm) ? ExactMatchScore |
| | 0 | 130 | | : e.CleanName!.StartsWith(cleanSearchTerm) ? PrefixMatchScore |
| | 0 | 131 | | : e.CleanName!.Contains(cleanPrefix) ? WordPrefixMatchScore |
| | 0 | 132 | | : ContainsMatchScore |
| | 0 | 133 | | }); |
| | | 134 | | |
| | 0 | 135 | | return await scored |
| | 0 | 136 | | .OrderByDescending(x => x.Score) |
| | 0 | 137 | | .ThenBy(x => x.Id) |
| | 0 | 138 | | .Take(limit) |
| | 0 | 139 | | .Select(x => new SearchResult(x.Id, x.Score)) |
| | 0 | 140 | | .ToArrayAsync(cancellationToken) |
| | 0 | 141 | | .ConfigureAwait(false); |
| | | 142 | | } |
| | 0 | 143 | | } |
| | | 144 | | |
| | | 145 | | private IQueryable<BaseItemEntity> ApplyTypeFilter( |
| | | 146 | | IQueryable<BaseItemEntity> query, |
| | | 147 | | BaseItemKind[] includeItemTypes, |
| | | 148 | | BaseItemKind[] excludeItemTypes) |
| | | 149 | | { |
| | 0 | 150 | | if (includeItemTypes.Length > 0) |
| | | 151 | | { |
| | 0 | 152 | | var includeTypeNames = MapKindsToTypeNames(includeItemTypes); |
| | 0 | 153 | | if (includeTypeNames.Count > 0) |
| | | 154 | | { |
| | 0 | 155 | | query = query.Where(e => includeTypeNames.Contains(e.Type)); |
| | | 156 | | } |
| | | 157 | | } |
| | 0 | 158 | | else if (excludeItemTypes.Length > 0) |
| | | 159 | | { |
| | 0 | 160 | | var excludeTypeNames = MapKindsToTypeNames(excludeItemTypes); |
| | 0 | 161 | | if (excludeTypeNames.Count > 0) |
| | | 162 | | { |
| | 0 | 163 | | query = query.Where(e => !excludeTypeNames.Contains(e.Type)); |
| | | 164 | | } |
| | | 165 | | } |
| | | 166 | | |
| | 0 | 167 | | return query; |
| | | 168 | | } |
| | | 169 | | |
| | | 170 | | private static IQueryable<BaseItemEntity> ApplyMediaTypeFilter( |
| | | 171 | | IQueryable<BaseItemEntity> query, |
| | | 172 | | MediaType[] mediaTypes) |
| | | 173 | | { |
| | 0 | 174 | | if (mediaTypes.Length == 0) |
| | | 175 | | { |
| | 0 | 176 | | return query; |
| | | 177 | | } |
| | | 178 | | |
| | 0 | 179 | | var mediaTypeNames = mediaTypes.Select(m => m.ToString()).ToArray(); |
| | 0 | 180 | | return query.Where(e => e.MediaType != null && mediaTypeNames.Contains(e.MediaType)); |
| | | 181 | | } |
| | | 182 | | |
| | | 183 | | private static IQueryable<BaseItemEntity> ApplyParentFilter( |
| | | 184 | | IQueryable<BaseItemEntity> query, |
| | | 185 | | Guid? parentId) |
| | | 186 | | { |
| | 0 | 187 | | if (!parentId.HasValue || parentId.Value.IsEmpty()) |
| | | 188 | | { |
| | 0 | 189 | | return query; |
| | | 190 | | } |
| | | 191 | | |
| | 0 | 192 | | var pid = parentId.Value; |
| | 0 | 193 | | return query.Where(e => e.ParentId == pid || e.Parents!.Any(p => p.ParentItemId == pid)); |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | private IQueryable<BaseItemEntity> ApplyUserAccessFilter( |
| | | 197 | | JellyfinDbContext dbContext, |
| | | 198 | | IQueryable<BaseItemEntity> query, |
| | | 199 | | Guid? userId) |
| | | 200 | | { |
| | 0 | 201 | | if (!userId.HasValue || userId.Value.IsEmpty()) |
| | | 202 | | { |
| | 0 | 203 | | return query; |
| | | 204 | | } |
| | | 205 | | |
| | 0 | 206 | | var user = _userManager.GetUserById(userId.Value); |
| | 0 | 207 | | if (user is null) |
| | | 208 | | { |
| | 0 | 209 | | return query; |
| | | 210 | | } |
| | | 211 | | |
| | 0 | 212 | | var accessFilter = new InternalItemsQuery(user); |
| | 0 | 213 | | _libraryManager.ConfigureUserAccess(accessFilter, user); |
| | 0 | 214 | | return _queryHelpers.ApplyAccessFiltering(dbContext, query, accessFilter); |
| | | 215 | | } |
| | | 216 | | |
| | | 217 | | private List<string> MapKindsToTypeNames(BaseItemKind[] kinds) |
| | | 218 | | { |
| | 0 | 219 | | var list = new List<string>(kinds.Length); |
| | 0 | 220 | | foreach (var kind in kinds) |
| | | 221 | | { |
| | 0 | 222 | | if (_itemTypeLookup.BaseItemKindNames.TryGetValue(kind, out var name) && name is not null) |
| | | 223 | | { |
| | 0 | 224 | | list.Add(name); |
| | | 225 | | } |
| | | 226 | | } |
| | | 227 | | |
| | 0 | 228 | | return list; |
| | | 229 | | } |
| | | 230 | | } |