| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using Azure.Storage.Blobs; |
| | | 4 | | using Chronicis.Shared.Extensions; |
| | | 5 | | using Microsoft.Extensions.Caching.Memory; |
| | | 6 | | |
| | | 7 | | namespace Chronicis.Api.Services.ExternalLinks; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// External link provider backed by Azure Blob Storage. |
| | | 11 | | /// Supports progressive category drill-down: typing "[[ros" shows top-level categories, |
| | | 12 | | /// "[[ros/bestiary" shows bestiary's children, and so on at any depth. |
| | | 13 | | /// Cross-category text search is supported at the top level (no slash). |
| | | 14 | | /// </summary> |
| | | 15 | | public class BlobExternalLinkProvider : IExternalLinkProvider |
| | | 16 | | { |
| | | 17 | | private readonly BlobExternalLinkProviderOptions _options; |
| | | 18 | | private readonly BlobContainerClient _containerClient; |
| | | 19 | | private readonly IMemoryCache _cache; |
| | | 20 | | private readonly ILogger<BlobExternalLinkProvider> _logger; |
| | | 21 | | |
| | 0 | 22 | | public BlobExternalLinkProvider( |
| | 0 | 23 | | BlobExternalLinkProviderOptions options, |
| | 0 | 24 | | IMemoryCache cache, |
| | 0 | 25 | | ILogger<BlobExternalLinkProvider> logger) |
| | | 26 | | { |
| | 0 | 27 | | _options = options ?? throw new ArgumentNullException(nameof(options)); |
| | 0 | 28 | | _cache = cache ?? throw new ArgumentNullException(nameof(cache)); |
| | 0 | 29 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | | 30 | | |
| | 0 | 31 | | var blobServiceClient = new BlobServiceClient(_options.ConnectionString); |
| | 0 | 32 | | _containerClient = blobServiceClient.GetBlobContainerClient(_options.ContainerName); |
| | | 33 | | |
| | 0 | 34 | | _logger.LogDebug( |
| | 0 | 35 | | "Initialized BlobExternalLinkProvider: Key={Key}, DisplayName={DisplayName}, RootPrefix={RootPrefix}", |
| | 0 | 36 | | _options.Key, _options.DisplayName, _options.RootPrefix); |
| | 0 | 37 | | } |
| | | 38 | | |
| | 0 | 39 | | public string Key => _options.Key; |
| | | 40 | | |
| | | 41 | | // ================================================================================== |
| | | 42 | | // PUBLIC API |
| | | 43 | | // ================================================================================== |
| | | 44 | | |
| | | 45 | | public async Task<IReadOnlyList<ExternalLinkSuggestion>> SearchAsync(string query, CancellationToken ct) |
| | | 46 | | { |
| | 0 | 47 | | query = query?.Trim() ?? string.Empty; |
| | | 48 | | |
| | 0 | 49 | | var slashIndex = query.IndexOf('/'); |
| | | 50 | | |
| | | 51 | | // Case A: No slash — top-level behavior |
| | | 52 | | // Empty query → show top-level categories only |
| | | 53 | | // Has text → cross-category search (categories + items) |
| | 0 | 54 | | if (slashIndex < 0) |
| | | 55 | | { |
| | 0 | 56 | | if (string.IsNullOrWhiteSpace(query)) |
| | | 57 | | { |
| | 0 | 58 | | return await GetTopLevelCategorySuggestionsAsync(ct); |
| | | 59 | | } |
| | | 60 | | |
| | 0 | 61 | | return await SearchAcrossAllCategoriesAsync(query, ct); |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | // Case B: Has slash — progressive drill-down |
| | | 65 | | // Split into path prefix and trailing text after last slash |
| | | 66 | | // Example: "bestiary/beast/abo" → pathPrefix="bestiary/beast", trailingText="abo" |
| | | 67 | | // Example: "bestiary/" → pathPrefix="bestiary", trailingText="" |
| | | 68 | | // Example: "bestiary/beast/" → pathPrefix="bestiary/beast", trailingText="" |
| | 0 | 69 | | var lastSlashIdx = query.LastIndexOf('/'); |
| | 0 | 70 | | var pathPrefix = query[..lastSlashIdx]; |
| | 0 | 71 | | var trailingText = query[(lastSlashIdx + 1)..]; |
| | | 72 | | |
| | | 73 | | // Get the children at the path prefix |
| | 0 | 74 | | var children = await GetChildrenAtPathAsync(pathPrefix, ct); |
| | | 75 | | |
| | 0 | 76 | | if (children == null) |
| | | 77 | | { |
| | | 78 | | // Path doesn't exist — try partial matching against parent's children |
| | | 79 | | // Example: "bestiary/bea" → parent is "", trailing is "bestiary/bea" |
| | | 80 | | // We need to find if "bestiary" partially matches a top-level folder |
| | 0 | 81 | | return await SearchPartialPathAsync(query, ct); |
| | | 82 | | } |
| | | 83 | | |
| | 0 | 84 | | var results = new List<ExternalLinkSuggestion>(); |
| | | 85 | | |
| | | 86 | | // Build child folder suggestions (always shown first) |
| | 0 | 87 | | var folderSuggestions = children.ChildFolders |
| | 0 | 88 | | .Where(f => string.IsNullOrWhiteSpace(trailingText) |
| | 0 | 89 | | || f.Slug.Contains(trailingText, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 90 | | .Select(folder => |
| | 0 | 91 | | { |
| | 0 | 92 | | var fullPath = string.IsNullOrEmpty(pathPrefix) ? folder.Slug : $"{pathPrefix}/{folder.Slug}"; |
| | 0 | 93 | | var title = BlobFilenameParser.PrettifySlug(folder.Slug); |
| | 0 | 94 | | return new ExternalLinkSuggestion |
| | 0 | 95 | | { |
| | 0 | 96 | | Source = _options.Key, |
| | 0 | 97 | | Id = $"_category/{fullPath}", |
| | 0 | 98 | | Title = title, |
| | 0 | 99 | | Subtitle = $"Browse {title}", |
| | 0 | 100 | | Category = "_category", |
| | 0 | 101 | | Icon = null, |
| | 0 | 102 | | Href = null |
| | 0 | 103 | | }; |
| | 0 | 104 | | }) |
| | 0 | 105 | | .ToList(); |
| | | 106 | | |
| | 0 | 107 | | results.AddRange(folderSuggestions); |
| | | 108 | | |
| | | 109 | | // Build child file suggestions (shown after folders) |
| | | 110 | | // Use multi-token AND search if trailing text contains spaces |
| | 0 | 111 | | var fileSuggestions = FilterChildFiles(children.ChildFiles, trailingText, pathPrefix) |
| | 0 | 112 | | .Take(_options.MaxSuggestions - results.Count) |
| | 0 | 113 | | .ToList(); |
| | | 114 | | |
| | 0 | 115 | | results.AddRange(fileSuggestions); |
| | | 116 | | |
| | 0 | 117 | | _logger.LogDebugSanitized( |
| | 0 | 118 | | "Drill-down search - Provider={Key}, Path={Path}, Trailing={Trailing}, Folders={FolderCount}, Files={FileCou |
| | 0 | 119 | | _options.Key, pathPrefix, trailingText, folderSuggestions.Count, fileSuggestions.Count); |
| | | 120 | | |
| | 0 | 121 | | return results; |
| | 0 | 122 | | } |
| | | 123 | | |
| | | 124 | | public async Task<ExternalLinkContent> GetContentAsync(string id, CancellationToken ct) |
| | | 125 | | { |
| | | 126 | | // Step 1: Validate ID format |
| | 0 | 127 | | if (!BlobIdValidator.IsValid(id, out var validationError)) |
| | | 128 | | { |
| | 0 | 129 | | _logger.LogWarningSanitized( |
| | 0 | 130 | | "Invalid content ID - Provider={Key}, Id={Id}, Error={Error}", |
| | 0 | 131 | | _options.Key, id, validationError); |
| | 0 | 132 | | return CreateEmptyContent(id); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | // Step 2: Parse category and slug |
| | 0 | 136 | | var (category, slug) = BlobIdValidator.ParseId(id); |
| | 0 | 137 | | if (string.IsNullOrWhiteSpace(category) || string.IsNullOrWhiteSpace(slug)) |
| | | 138 | | { |
| | 0 | 139 | | _logger.LogWarningSanitized( |
| | 0 | 140 | | "Failed to parse content ID after validation - Provider={Key}, Id={Id}", |
| | 0 | 141 | | _options.Key, id); |
| | 0 | 142 | | return CreateEmptyContent(id); |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | // Step 3: Check content cache |
| | 0 | 146 | | var cacheKey = BuildCacheKey("Content", id); |
| | 0 | 147 | | if (_cache.TryGetValue<ExternalLinkContent>(cacheKey, out var cached) && cached != null) |
| | | 148 | | { |
| | 0 | 149 | | _logger.LogDebugSanitized("Content cache hit - Provider={Key}, Id={Id}", _options.Key, id); |
| | 0 | 150 | | return cached; |
| | | 151 | | } |
| | | 152 | | |
| | | 153 | | // Step 4: Load category index to find the blob name |
| | | 154 | | // GetCategoryIndexAsync no longer validates against a flat category list — |
| | | 155 | | // it directly queries blob storage at the given path. |
| | 0 | 156 | | var index = await GetCategoryIndexAsync(category, ct); |
| | 0 | 157 | | var item = index.FirstOrDefault(i => i.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); |
| | | 158 | | |
| | 0 | 159 | | if (item == null) |
| | | 160 | | { |
| | 0 | 161 | | _logger.LogWarningSanitized( |
| | 0 | 162 | | "Content ID not found in category index - Provider={Key}, Id={Id}, Category={Category}, IndexCount={Inde |
| | 0 | 163 | | _options.Key, id, category, index.Count); |
| | 0 | 164 | | return CreateEmptyContent(id); |
| | | 165 | | } |
| | | 166 | | |
| | | 167 | | // Step 5: Fetch blob content and render |
| | | 168 | | try |
| | | 169 | | { |
| | 0 | 170 | | var blobClient = _containerClient.GetBlobClient(item.BlobName); |
| | 0 | 171 | | var response = await blobClient.DownloadContentAsync(ct); |
| | 0 | 172 | | var content = response.Value.Content; |
| | | 173 | | |
| | | 174 | | // Handle UTF-8 BOM |
| | 0 | 175 | | var jsonBytes = content.ToMemory(); |
| | 0 | 176 | | var span = jsonBytes.Span; |
| | 0 | 177 | | if (span.Length >= 3 && span[0] == 0xEF && span[1] == 0xBB && span[2] == 0xBF) |
| | | 178 | | { |
| | 0 | 179 | | jsonBytes = jsonBytes.Slice(3); |
| | | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | using var json = JsonDocument.Parse(jsonBytes); |
| | | 183 | | |
| | | 184 | | // Capture raw JSON for client-side structured rendering |
| | 0 | 185 | | var rawJson = System.Text.Encoding.UTF8.GetString(jsonBytes.Span); |
| | | 186 | | |
| | 0 | 187 | | var markdown = GenericJsonMarkdownRenderer.RenderMarkdown( |
| | 0 | 188 | | json, _options.DisplayName, item.Title); |
| | | 189 | | |
| | 0 | 190 | | var result = new ExternalLinkContent |
| | 0 | 191 | | { |
| | 0 | 192 | | Source = _options.Key, |
| | 0 | 193 | | Id = id, |
| | 0 | 194 | | Title = item.Title, |
| | 0 | 195 | | Kind = BlobFilenameParser.PrettifySlug(category), |
| | 0 | 196 | | Markdown = markdown, |
| | 0 | 197 | | Attribution = $"Source: {_options.DisplayName}", |
| | 0 | 198 | | ExternalUrl = null, |
| | 0 | 199 | | JsonData = rawJson |
| | 0 | 200 | | }; |
| | | 201 | | |
| | 0 | 202 | | _cache.Set(cacheKey, result, new MemoryCacheEntryOptions |
| | 0 | 203 | | { |
| | 0 | 204 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_options.ContentCacheTtl) |
| | 0 | 205 | | }); |
| | | 206 | | |
| | 0 | 207 | | _logger.LogDebugSanitized( |
| | 0 | 208 | | "Content retrieved and rendered - Provider={Key}, Id={Id}, BlobName={BlobName}", |
| | 0 | 209 | | _options.Key, id, item.BlobName); |
| | | 210 | | |
| | 0 | 211 | | return result; |
| | | 212 | | } |
| | 0 | 213 | | catch (Exception ex) |
| | | 214 | | { |
| | 0 | 215 | | _logger.LogErrorSanitized(ex, |
| | 0 | 216 | | "Failed to retrieve or render content - Provider={Key}, Id={Id}, BlobName={BlobName}", |
| | 0 | 217 | | _options.Key, id, item.BlobName); |
| | 0 | 218 | | return CreateEmptyContent(id); |
| | | 219 | | } |
| | 0 | 220 | | } |
| | | 221 | | |
| | | 222 | | private ExternalLinkContent CreateEmptyContent(string id) |
| | | 223 | | { |
| | 0 | 224 | | return new ExternalLinkContent |
| | 0 | 225 | | { |
| | 0 | 226 | | Source = _options.Key, |
| | 0 | 227 | | Id = id, |
| | 0 | 228 | | Title = "Content Not Found", |
| | 0 | 229 | | Kind = "Unknown", |
| | 0 | 230 | | Markdown = "The requested content could not be found.", |
| | 0 | 231 | | Attribution = $"Source: {_options.DisplayName}", |
| | 0 | 232 | | ExternalUrl = null |
| | 0 | 233 | | }; |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | // ================================================================================== |
| | | 237 | | // PRIVATE METHODS - Progressive Discovery |
| | | 238 | | // ================================================================================== |
| | | 239 | | |
| | | 240 | | /// <summary> |
| | | 241 | | /// Result of discovering direct children at a given path. |
| | | 242 | | /// ChildFolders carry both the original blob name and the lowercase slug for display/IDs. |
| | | 243 | | /// ChildFiles are CategoryItem records for JSON files at this level. |
| | | 244 | | /// </summary> |
| | 0 | 245 | | private record PathChildren(List<ChildFolder> ChildFolders, List<CategoryItem> ChildFiles); |
| | | 246 | | |
| | | 247 | | /// <summary> |
| | | 248 | | /// A subfolder discovered at a given path level. |
| | | 249 | | /// BlobName is the original casing as stored in blob (needed for subsequent queries). |
| | | 250 | | /// Slug is the lowercase-normalized name used in IDs and display. |
| | | 251 | | /// </summary> |
| | 0 | 252 | | private record ChildFolder(string BlobName, string Slug); |
| | | 253 | | |
| | | 254 | | /// <summary> |
| | | 255 | | /// Discovers the direct children (subfolders and files) at a given relative path |
| | | 256 | | /// within the provider's root prefix. Uses GetBlobsByHierarchy with "/" delimiter |
| | | 257 | | /// to get exactly one level of the hierarchy. |
| | | 258 | | /// |
| | | 259 | | /// Returns null if the path has no children (doesn't exist or is empty). |
| | | 260 | | /// Results are cached per path. |
| | | 261 | | /// </summary> |
| | | 262 | | /// <param name="relativePath"> |
| | | 263 | | /// Path relative to RootPrefix. Empty string for root level. |
| | | 264 | | /// Can be in original blob casing OR lowercase — the method resolves via cached mappings. |
| | | 265 | | /// Example: "bestiary" or "Bestiary" or "bestiary/beast" or "items/armor/light" |
| | | 266 | | /// </param> |
| | | 267 | | private async Task<PathChildren?> GetChildrenAtPathAsync(string relativePath, CancellationToken ct) |
| | | 268 | | { |
| | 0 | 269 | | var normalizedPath = relativePath.Trim('/'); |
| | | 270 | | |
| | | 271 | | // Resolve the path to its original blob casing |
| | 0 | 272 | | var blobPath = await ResolveBlobPathAsync(normalizedPath, ct); |
| | | 273 | | |
| | 0 | 274 | | var cacheKey = BuildCacheKey("Children", normalizedPath.ToLowerInvariant()); |
| | | 275 | | |
| | 0 | 276 | | if (_cache.TryGetValue<PathChildren>(cacheKey, out var cached) && cached != null) |
| | | 277 | | { |
| | 0 | 278 | | return cached; |
| | | 279 | | } |
| | | 280 | | |
| | | 281 | | // Build the blob prefix using the ORIGINAL casing from blob storage |
| | 0 | 282 | | var prefix = string.IsNullOrEmpty(blobPath) |
| | 0 | 283 | | ? _options.RootPrefix |
| | 0 | 284 | | : $"{_options.RootPrefix}{blobPath}/"; |
| | | 285 | | |
| | 0 | 286 | | var childFolders = new List<ChildFolder>(); |
| | 0 | 287 | | var childFiles = new List<CategoryItem>(); |
| | | 288 | | |
| | 0 | 289 | | await foreach (var item in _containerClient.GetBlobsByHierarchyAsync( |
| | 0 | 290 | | prefix: prefix, |
| | 0 | 291 | | delimiter: "/", |
| | 0 | 292 | | cancellationToken: ct)) |
| | | 293 | | { |
| | 0 | 294 | | if (item.IsPrefix && item.Prefix != null) |
| | | 295 | | { |
| | | 296 | | // Subfolder — extract the folder name in its ORIGINAL casing |
| | 0 | 297 | | var originalFolderName = item.Prefix[prefix.Length..].TrimEnd('/'); |
| | 0 | 298 | | if (!string.IsNullOrWhiteSpace(originalFolderName)) |
| | | 299 | | { |
| | 0 | 300 | | var slug = originalFolderName.ToLowerInvariant(); |
| | 0 | 301 | | childFolders.Add(new ChildFolder(originalFolderName, slug)); |
| | | 302 | | |
| | | 303 | | // Cache the slug → blob path mapping for this child |
| | 0 | 304 | | var childSlugPath = string.IsNullOrEmpty(normalizedPath) |
| | 0 | 305 | | ? slug |
| | 0 | 306 | | : $"{normalizedPath.ToLowerInvariant()}/{slug}"; |
| | 0 | 307 | | var childBlobPath = string.IsNullOrEmpty(blobPath) |
| | 0 | 308 | | ? originalFolderName |
| | 0 | 309 | | : $"{blobPath}/{originalFolderName}"; |
| | 0 | 310 | | CacheBlobPathMapping(childSlugPath, childBlobPath); |
| | | 311 | | } |
| | | 312 | | } |
| | 0 | 313 | | else if (item.IsBlob && item.Blob != null) |
| | | 314 | | { |
| | 0 | 315 | | var blobName = item.Blob.Name; |
| | 0 | 316 | | if (!blobName.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) |
| | | 317 | | continue; |
| | | 318 | | |
| | 0 | 319 | | if (item.Blob.Properties.ContentLength.HasValue && |
| | 0 | 320 | | item.Blob.Properties.ContentLength.Value > 5_000_000) |
| | | 321 | | continue; |
| | | 322 | | |
| | 0 | 323 | | var lastSlash = blobName.LastIndexOf('/'); |
| | 0 | 324 | | var filename = lastSlash >= 0 ? blobName[(lastSlash + 1)..] : blobName; |
| | 0 | 325 | | var slug = BlobFilenameParser.DeriveSlug(filename); |
| | | 326 | | |
| | 0 | 327 | | if (string.IsNullOrWhiteSpace(slug)) |
| | | 328 | | continue; |
| | | 329 | | |
| | | 330 | | // IDs are always lowercase |
| | 0 | 331 | | var id = string.IsNullOrEmpty(normalizedPath) |
| | 0 | 332 | | ? slug.ToLowerInvariant() |
| | 0 | 333 | | : $"{normalizedPath.ToLowerInvariant()}/{slug.ToLowerInvariant()}"; |
| | 0 | 334 | | var title = BlobFilenameParser.PrettifySlug(slug); |
| | | 335 | | |
| | 0 | 336 | | childFiles.Add(new CategoryItem(id, title, blobName, Pk: null)); |
| | | 337 | | } |
| | | 338 | | } |
| | | 339 | | |
| | 0 | 340 | | if (childFolders.Count == 0 && childFiles.Count == 0) |
| | | 341 | | { |
| | 0 | 342 | | return null; |
| | | 343 | | } |
| | | 344 | | |
| | 0 | 345 | | childFolders.Sort((a, b) => string.Compare(a.Slug, b.Slug, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 346 | | childFiles = childFiles |
| | 0 | 347 | | .OrderBy(f => f.Title, StringComparer.OrdinalIgnoreCase) |
| | 0 | 348 | | .ThenBy(f => f.Id) |
| | 0 | 349 | | .ToList(); |
| | | 350 | | |
| | 0 | 351 | | var result = new PathChildren(childFolders, childFiles); |
| | | 352 | | |
| | 0 | 353 | | _cache.Set(cacheKey, result, new MemoryCacheEntryOptions |
| | 0 | 354 | | { |
| | 0 | 355 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_options.CategoriesCacheTtl) |
| | 0 | 356 | | }); |
| | | 357 | | |
| | 0 | 358 | | _logger.LogDebugSanitized( |
| | 0 | 359 | | "Children discovered - Provider={Key}, Path={Path}, BlobPath={BlobPath}, Folders={FolderCount}, Files={FileC |
| | 0 | 360 | | _options.Key, normalizedPath, blobPath, childFolders.Count, childFiles.Count); |
| | | 361 | | |
| | 0 | 362 | | return result; |
| | 0 | 363 | | } |
| | | 364 | | |
| | | 365 | | /// <summary> |
| | | 366 | | /// Resolves a lowercase slug path back to its original blob casing. |
| | | 367 | | /// Uses cached mappings built during discovery. |
| | | 368 | | /// Falls back to the input path if no mapping exists (first-time root discovery). |
| | | 369 | | /// </summary> |
| | | 370 | | private async Task<string> ResolveBlobPathAsync(string slugPath, CancellationToken ct) |
| | | 371 | | { |
| | 0 | 372 | | if (string.IsNullOrEmpty(slugPath)) |
| | 0 | 373 | | return string.Empty; |
| | | 374 | | |
| | 0 | 375 | | var mappingKey = BuildCacheKey("BlobPathMap", slugPath.ToLowerInvariant()); |
| | 0 | 376 | | if (_cache.TryGetValue<string>(mappingKey, out var blobPath) && blobPath != null) |
| | | 377 | | { |
| | 0 | 378 | | return blobPath; |
| | | 379 | | } |
| | | 380 | | |
| | | 381 | | // No cached mapping — this can happen if the cache expired or on first access |
| | | 382 | | // to a deep path. Walk from root to rebuild mappings. |
| | 0 | 383 | | var segments = slugPath.Split('/'); |
| | 0 | 384 | | var currentSlugPath = ""; |
| | 0 | 385 | | var currentBlobPath = ""; |
| | | 386 | | |
| | 0 | 387 | | for (var i = 0; i < segments.Length; i++) |
| | | 388 | | { |
| | | 389 | | // Ensure parent is discovered (this populates child mappings) |
| | 0 | 390 | | var parentChildren = await GetChildrenAtPathAsync(currentBlobPath, ct); |
| | 0 | 391 | | if (parentChildren == null) |
| | | 392 | | { |
| | | 393 | | // Parent doesn't exist — return input as-is |
| | 0 | 394 | | return slugPath; |
| | | 395 | | } |
| | | 396 | | |
| | 0 | 397 | | var targetSlug = segments[i].ToLowerInvariant(); |
| | 0 | 398 | | var matchedFolder = parentChildren.ChildFolders |
| | 0 | 399 | | .FirstOrDefault(f => f.Slug.Equals(targetSlug, StringComparison.OrdinalIgnoreCase)); |
| | | 400 | | |
| | 0 | 401 | | if (matchedFolder == null) |
| | | 402 | | { |
| | | 403 | | // Segment not found — return input as-is |
| | 0 | 404 | | return slugPath; |
| | | 405 | | } |
| | | 406 | | |
| | 0 | 407 | | currentSlugPath = string.IsNullOrEmpty(currentSlugPath) |
| | 0 | 408 | | ? matchedFolder.Slug |
| | 0 | 409 | | : $"{currentSlugPath}/{matchedFolder.Slug}"; |
| | 0 | 410 | | currentBlobPath = string.IsNullOrEmpty(currentBlobPath) |
| | 0 | 411 | | ? matchedFolder.BlobName |
| | 0 | 412 | | : $"{currentBlobPath}/{matchedFolder.BlobName}"; |
| | 0 | 413 | | } |
| | | 414 | | |
| | 0 | 415 | | return currentBlobPath; |
| | 0 | 416 | | } |
| | | 417 | | |
| | | 418 | | /// <summary> |
| | | 419 | | /// Caches a mapping from lowercase slug path to original blob path. |
| | | 420 | | /// </summary> |
| | | 421 | | private void CacheBlobPathMapping(string slugPath, string blobPath) |
| | | 422 | | { |
| | 0 | 423 | | var mappingKey = BuildCacheKey("BlobPathMap", slugPath.ToLowerInvariant()); |
| | 0 | 424 | | _cache.Set(mappingKey, blobPath, new MemoryCacheEntryOptions |
| | 0 | 425 | | { |
| | 0 | 426 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_options.CategoriesCacheTtl) |
| | 0 | 427 | | }); |
| | 0 | 428 | | } |
| | | 429 | | |
| | | 430 | | /// <summary> |
| | | 431 | | /// Returns suggestions for top-level categories only (no children expanded). |
| | | 432 | | /// Used when the user types "[[ros" with no slash and no text. |
| | | 433 | | /// </summary> |
| | | 434 | | private async Task<List<ExternalLinkSuggestion>> GetTopLevelCategorySuggestionsAsync(CancellationToken ct) |
| | | 435 | | { |
| | 0 | 436 | | var children = await GetChildrenAtPathAsync("", ct); |
| | 0 | 437 | | if (children == null) |
| | | 438 | | { |
| | 0 | 439 | | return new List<ExternalLinkSuggestion>(); |
| | | 440 | | } |
| | | 441 | | |
| | 0 | 442 | | var suggestions = new List<ExternalLinkSuggestion>(); |
| | | 443 | | |
| | 0 | 444 | | foreach (var folder in children.ChildFolders) |
| | | 445 | | { |
| | 0 | 446 | | var title = BlobFilenameParser.PrettifySlug(folder.Slug); |
| | 0 | 447 | | suggestions.Add(new ExternalLinkSuggestion |
| | 0 | 448 | | { |
| | 0 | 449 | | Source = _options.Key, |
| | 0 | 450 | | Id = $"_category/{folder.Slug}", |
| | 0 | 451 | | Title = title, |
| | 0 | 452 | | Subtitle = $"Browse {title}", |
| | 0 | 453 | | Category = "_category", |
| | 0 | 454 | | Icon = null, |
| | 0 | 455 | | Href = null |
| | 0 | 456 | | }); |
| | | 457 | | } |
| | | 458 | | |
| | | 459 | | // Also include any files at the root level (unlikely but possible) |
| | 0 | 460 | | foreach (var file in children.ChildFiles.Take(_options.MaxSuggestions - suggestions.Count)) |
| | | 461 | | { |
| | 0 | 462 | | suggestions.Add(new ExternalLinkSuggestion |
| | 0 | 463 | | { |
| | 0 | 464 | | Source = _options.Key, |
| | 0 | 465 | | Id = file.Id, |
| | 0 | 466 | | Title = file.Title, |
| | 0 | 467 | | Subtitle = _options.DisplayName, |
| | 0 | 468 | | Category = "", |
| | 0 | 469 | | Icon = null, |
| | 0 | 470 | | Href = null |
| | 0 | 471 | | }); |
| | | 472 | | } |
| | | 473 | | |
| | 0 | 474 | | return suggestions; |
| | 0 | 475 | | } |
| | | 476 | | |
| | | 477 | | /// <summary> |
| | | 478 | | /// Handles partial path matching when the typed path doesn't match a real folder. |
| | | 479 | | /// Example: "besti" → finds "bestiary" in parent's children. |
| | | 480 | | /// Example: "bestiary/bea" → finds "beast" under "bestiary". |
| | | 481 | | /// </summary> |
| | | 482 | | private async Task<List<ExternalLinkSuggestion>> SearchPartialPathAsync(string query, CancellationToken ct) |
| | | 483 | | { |
| | 0 | 484 | | return await SearchPartialPathInternalAsync(query, 0, ct); |
| | 0 | 485 | | } |
| | | 486 | | |
| | | 487 | | private async Task<List<ExternalLinkSuggestion>> SearchPartialPathInternalAsync( |
| | | 488 | | string query, int depth, CancellationToken ct) |
| | | 489 | | { |
| | 0 | 490 | | if (depth > _options.MaxDrillDownDepth) |
| | 0 | 491 | | return new List<ExternalLinkSuggestion>(); |
| | | 492 | | |
| | | 493 | | // Split into parent path and partial segment |
| | 0 | 494 | | var lastSlashIdx = query.LastIndexOf('/'); |
| | 0 | 495 | | var parentPath = lastSlashIdx >= 0 ? query[..lastSlashIdx] : ""; |
| | 0 | 496 | | var partialSegment = lastSlashIdx >= 0 ? query[(lastSlashIdx + 1)..] : query; |
| | | 497 | | |
| | 0 | 498 | | var children = await GetChildrenAtPathAsync(parentPath, ct); |
| | 0 | 499 | | if (children == null) |
| | | 500 | | { |
| | | 501 | | // Parent path doesn't exist either — recurse up if there's still a slash |
| | 0 | 502 | | if (lastSlashIdx > 0) |
| | | 503 | | { |
| | 0 | 504 | | return await SearchPartialPathInternalAsync(parentPath, depth + 1, ct); |
| | | 505 | | } |
| | | 506 | | |
| | 0 | 507 | | return new List<ExternalLinkSuggestion>(); |
| | | 508 | | } |
| | | 509 | | |
| | 0 | 510 | | var results = new List<ExternalLinkSuggestion>(); |
| | | 511 | | |
| | | 512 | | // Match folders that contain the partial segment |
| | 0 | 513 | | var matchingFolders = children.ChildFolders |
| | 0 | 514 | | .Where(f => f.Slug.Contains(partialSegment, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 515 | | .ToList(); |
| | | 516 | | |
| | 0 | 517 | | foreach (var folder in matchingFolders) |
| | | 518 | | { |
| | 0 | 519 | | var fullPath = string.IsNullOrEmpty(parentPath) ? folder.Slug : $"{parentPath}/{folder.Slug}"; |
| | 0 | 520 | | var title = BlobFilenameParser.PrettifySlug(folder.Slug); |
| | 0 | 521 | | results.Add(new ExternalLinkSuggestion |
| | 0 | 522 | | { |
| | 0 | 523 | | Source = _options.Key, |
| | 0 | 524 | | Id = $"_category/{fullPath}", |
| | 0 | 525 | | Title = title, |
| | 0 | 526 | | Subtitle = $"Browse {title}", |
| | 0 | 527 | | Category = "_category", |
| | 0 | 528 | | Icon = null, |
| | 0 | 529 | | Href = null |
| | 0 | 530 | | }); |
| | | 531 | | } |
| | | 532 | | |
| | | 533 | | // Also match files at this level |
| | 0 | 534 | | var matchingFiles = children.ChildFiles |
| | 0 | 535 | | .Where(f => f.Title.Contains(partialSegment, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 536 | | .Take(_options.MaxSuggestions - results.Count); |
| | | 537 | | |
| | 0 | 538 | | foreach (var file in matchingFiles) |
| | | 539 | | { |
| | 0 | 540 | | results.Add(new ExternalLinkSuggestion |
| | 0 | 541 | | { |
| | 0 | 542 | | Source = _options.Key, |
| | 0 | 543 | | Id = file.Id, |
| | 0 | 544 | | Title = file.Title, |
| | 0 | 545 | | Subtitle = BlobFilenameParser.PrettifySlug(parentPath), |
| | 0 | 546 | | Category = parentPath, |
| | 0 | 547 | | Icon = null, |
| | 0 | 548 | | Href = null |
| | 0 | 549 | | }); |
| | | 550 | | } |
| | | 551 | | |
| | 0 | 552 | | return results; |
| | 0 | 553 | | } |
| | | 554 | | |
| | | 555 | | /// <summary> |
| | | 556 | | /// Searches across ALL leaf categories for items matching the query. |
| | | 557 | | /// Also returns matching category names at the top. |
| | | 558 | | /// Used only for top-level text search (no slash in query). |
| | | 559 | | /// </summary> |
| | | 560 | | private async Task<List<ExternalLinkSuggestion>> SearchAcrossAllCategoriesAsync(string query, CancellationToken ct) |
| | | 561 | | { |
| | 0 | 562 | | var results = new List<ExternalLinkSuggestion>(); |
| | | 563 | | |
| | | 564 | | // Part 1: Check top-level categories that match the query text |
| | 0 | 565 | | var topChildren = await GetChildrenAtPathAsync("", ct); |
| | 0 | 566 | | if (topChildren != null) |
| | | 567 | | { |
| | 0 | 568 | | var matchingFolders = topChildren.ChildFolders |
| | 0 | 569 | | .Where(f => f.Slug.Contains(query, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 570 | | .ToList(); |
| | | 571 | | |
| | 0 | 572 | | foreach (var folder in matchingFolders) |
| | | 573 | | { |
| | 0 | 574 | | var title = BlobFilenameParser.PrettifySlug(folder.Slug); |
| | 0 | 575 | | results.Add(new ExternalLinkSuggestion |
| | 0 | 576 | | { |
| | 0 | 577 | | Source = _options.Key, |
| | 0 | 578 | | Id = $"_category/{folder.Slug}", |
| | 0 | 579 | | Title = title, |
| | 0 | 580 | | Subtitle = $"Browse {title}", |
| | 0 | 581 | | Category = "_category", |
| | 0 | 582 | | Icon = null, |
| | 0 | 583 | | Href = null |
| | 0 | 584 | | }); |
| | | 585 | | } |
| | | 586 | | } |
| | | 587 | | |
| | | 588 | | // Part 2: Search items across all leaf categories |
| | 0 | 589 | | var leafCategories = await GetAllLeafCategoriesAsync(ct); |
| | | 590 | | |
| | 0 | 591 | | var itemResults = new List<ExternalLinkSuggestion>(); |
| | 0 | 592 | | foreach (var leafPath in leafCategories) |
| | | 593 | | { |
| | 0 | 594 | | var index = await GetCategoryIndexAsync(leafPath, ct); |
| | | 595 | | |
| | 0 | 596 | | var matchingItems = index |
| | 0 | 597 | | .Where(item => item.Title.Contains(query, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 598 | | .Take(5) |
| | 0 | 599 | | .Select(item => new ExternalLinkSuggestion |
| | 0 | 600 | | { |
| | 0 | 601 | | Source = _options.Key, |
| | 0 | 602 | | Id = item.Id, |
| | 0 | 603 | | Title = item.Title, |
| | 0 | 604 | | Subtitle = BlobFilenameParser.PrettifySlug(leafPath), |
| | 0 | 605 | | Category = leafPath, |
| | 0 | 606 | | Icon = null, |
| | 0 | 607 | | Href = null |
| | 0 | 608 | | }); |
| | | 609 | | |
| | 0 | 610 | | itemResults.AddRange(matchingItems); |
| | 0 | 611 | | } |
| | | 612 | | |
| | 0 | 613 | | results.AddRange(itemResults.Take(_options.MaxSuggestions - results.Count)); |
| | | 614 | | |
| | 0 | 615 | | _logger.LogDebugSanitized( |
| | 0 | 616 | | "Cross-category search - Provider={Key}, Query={Query}, LeafCategories={LeafCount}, ItemMatches={ItemCount}" |
| | 0 | 617 | | _options.Key, query, leafCategories.Count, itemResults.Count); |
| | | 618 | | |
| | 0 | 619 | | return results; |
| | 0 | 620 | | } |
| | | 621 | | |
| | | 622 | | /// <summary> |
| | | 623 | | /// Recursively discovers all leaf category paths (folders that contain files). |
| | | 624 | | /// A leaf category is a path where GetChildrenAtPathAsync returns files. |
| | | 625 | | /// Cached for CategoriesCacheTtl minutes. |
| | | 626 | | /// </summary> |
| | | 627 | | private async Task<List<string>> GetAllLeafCategoriesAsync(CancellationToken ct) |
| | | 628 | | { |
| | 0 | 629 | | var cacheKey = BuildCacheKey("AllLeafCategories"); |
| | | 630 | | |
| | 0 | 631 | | if (_cache.TryGetValue<List<string>>(cacheKey, out var cached) && cached != null) |
| | | 632 | | { |
| | 0 | 633 | | return cached; |
| | | 634 | | } |
| | | 635 | | |
| | 0 | 636 | | var sw = Stopwatch.StartNew(); |
| | 0 | 637 | | var leaves = new List<string>(); |
| | | 638 | | |
| | 0 | 639 | | await CollectLeafCategoriesAsync("", leaves, 0, ct); |
| | | 640 | | |
| | 0 | 641 | | leaves.Sort(StringComparer.OrdinalIgnoreCase); |
| | | 642 | | |
| | 0 | 643 | | sw.Stop(); |
| | 0 | 644 | | _logger.LogDebug( |
| | 0 | 645 | | "Leaf categories discovered - Provider={Key}, Count={Count}, Elapsed={Elapsed}ms", |
| | 0 | 646 | | _options.Key, leaves.Count, sw.ElapsedMilliseconds); |
| | | 647 | | |
| | 0 | 648 | | _cache.Set(cacheKey, leaves, new MemoryCacheEntryOptions |
| | 0 | 649 | | { |
| | 0 | 650 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_options.CategoriesCacheTtl) |
| | 0 | 651 | | }); |
| | | 652 | | |
| | 0 | 653 | | return leaves; |
| | 0 | 654 | | } |
| | | 655 | | |
| | | 656 | | /// <summary> |
| | | 657 | | /// Recursive helper to walk the folder tree and collect all paths that contain files. |
| | | 658 | | /// </summary> |
| | | 659 | | private async Task CollectLeafCategoriesAsync( |
| | | 660 | | string path, List<string> leaves, int depth, CancellationToken ct) |
| | | 661 | | { |
| | 0 | 662 | | if (depth > _options.MaxDrillDownDepth) |
| | | 663 | | { |
| | 0 | 664 | | _logger.LogWarningSanitized( |
| | 0 | 665 | | "Max drill-down depth reached - Provider={Key}, Path={Path}, Depth={Depth}", |
| | 0 | 666 | | _options.Key, path, depth); |
| | 0 | 667 | | return; |
| | | 668 | | } |
| | | 669 | | |
| | 0 | 670 | | var children = await GetChildrenAtPathAsync(path, ct); |
| | 0 | 671 | | if (children == null) |
| | 0 | 672 | | return; |
| | | 673 | | |
| | | 674 | | // If this path has files and is not root, it's a leaf (or mixed) category |
| | | 675 | | // Skip root-level files since they'd produce IDs without a category prefix |
| | 0 | 676 | | if (children.ChildFiles.Count > 0 && !string.IsNullOrEmpty(path)) |
| | | 677 | | { |
| | 0 | 678 | | leaves.Add(path); |
| | | 679 | | } |
| | | 680 | | |
| | | 681 | | // Recurse into subfolders |
| | 0 | 682 | | foreach (var folder in children.ChildFolders) |
| | | 683 | | { |
| | 0 | 684 | | var childPath = string.IsNullOrEmpty(path) ? folder.Slug : $"{path}/{folder.Slug}"; |
| | 0 | 685 | | await CollectLeafCategoriesAsync(childPath, leaves, depth + 1, ct); |
| | | 686 | | } |
| | 0 | 687 | | } |
| | | 688 | | |
| | | 689 | | // ================================================================================== |
| | | 690 | | // PRIVATE METHODS - Index Building & Filtering |
| | | 691 | | // ================================================================================== |
| | | 692 | | |
| | | 693 | | private string BuildCacheKey(string type, string? key = null) |
| | | 694 | | { |
| | 0 | 695 | | var cacheKey = $"ExternalLinks:{_options.Key}:{type}"; |
| | 0 | 696 | | if (!string.IsNullOrEmpty(key)) |
| | | 697 | | { |
| | 0 | 698 | | cacheKey += $":{key}"; |
| | | 699 | | } |
| | 0 | 700 | | return cacheKey; |
| | | 701 | | } |
| | | 702 | | |
| | | 703 | | /// <summary> |
| | | 704 | | /// Builds and caches the index of files for a specific category path. |
| | | 705 | | /// Delegates to GetChildrenAtPathAsync to ensure consistent blob path resolution |
| | | 706 | | /// (handling mixed-case folder names in blob storage). |
| | | 707 | | /// Returns only the files (not subfolders) at the given path. |
| | | 708 | | /// </summary> |
| | | 709 | | private async Task<List<CategoryItem>> GetCategoryIndexAsync(string category, CancellationToken ct) |
| | | 710 | | { |
| | 0 | 711 | | var cacheKey = BuildCacheKey("CategoryIndex", category.ToLowerInvariant()); |
| | | 712 | | |
| | 0 | 713 | | if (_cache.TryGetValue<List<CategoryItem>>(cacheKey, out var cached) && cached != null) |
| | | 714 | | { |
| | 0 | 715 | | return cached; |
| | | 716 | | } |
| | | 717 | | |
| | | 718 | | // Delegate to GetChildrenAtPathAsync which handles blob path resolution |
| | 0 | 719 | | var children = await GetChildrenAtPathAsync(category, ct); |
| | 0 | 720 | | if (children == null) |
| | | 721 | | { |
| | 0 | 722 | | _logger.LogDebugSanitized( |
| | 0 | 723 | | "Category index empty (path not found) - Provider={Key}, Category={Category}", |
| | 0 | 724 | | _options.Key, category); |
| | 0 | 725 | | return new List<CategoryItem>(); |
| | | 726 | | } |
| | | 727 | | |
| | | 728 | | // The ChildFiles are already sorted and have correct lowercase IDs |
| | 0 | 729 | | var items = children.ChildFiles; |
| | | 730 | | |
| | 0 | 731 | | _logger.LogDebugSanitized( |
| | 0 | 732 | | "Category index built (via children) - Provider={Key}, Category={Category}, Count={Count}", |
| | 0 | 733 | | _options.Key, category, items.Count); |
| | | 734 | | |
| | 0 | 735 | | _cache.Set(cacheKey, items, new MemoryCacheEntryOptions |
| | 0 | 736 | | { |
| | 0 | 737 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(_options.CategoryIndexCacheTtl) |
| | 0 | 738 | | }); |
| | | 739 | | |
| | 0 | 740 | | return items; |
| | 0 | 741 | | } |
| | | 742 | | |
| | | 743 | | /// <summary> |
| | | 744 | | /// Filters child files by search term and converts to suggestions. |
| | | 745 | | /// Supports multi-token AND search (space-separated tokens all must match). |
| | | 746 | | /// Empty search term returns all files. |
| | | 747 | | /// </summary> |
| | | 748 | | private IEnumerable<ExternalLinkSuggestion> FilterChildFiles( |
| | | 749 | | List<CategoryItem> files, |
| | | 750 | | string searchTerm, |
| | | 751 | | string categoryPath) |
| | | 752 | | { |
| | 0 | 753 | | if (string.IsNullOrWhiteSpace(searchTerm)) |
| | | 754 | | { |
| | 0 | 755 | | return files.Select(item => new ExternalLinkSuggestion |
| | 0 | 756 | | { |
| | 0 | 757 | | Source = _options.Key, |
| | 0 | 758 | | Id = item.Id, |
| | 0 | 759 | | Title = item.Title, |
| | 0 | 760 | | Subtitle = BlobFilenameParser.PrettifySlug(categoryPath), |
| | 0 | 761 | | Category = categoryPath, |
| | 0 | 762 | | Icon = null, |
| | 0 | 763 | | Href = null |
| | 0 | 764 | | }); |
| | | 765 | | } |
| | | 766 | | |
| | 0 | 767 | | var tokens = searchTerm |
| | 0 | 768 | | .Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 0 | 769 | | .Where(t => !string.IsNullOrWhiteSpace(t)) |
| | 0 | 770 | | .ToList(); |
| | | 771 | | |
| | 0 | 772 | | if (tokens.Count == 0) |
| | 0 | 773 | | return Enumerable.Empty<ExternalLinkSuggestion>(); |
| | | 774 | | |
| | 0 | 775 | | return files |
| | 0 | 776 | | .Where(item => tokens.All(token => |
| | 0 | 777 | | item.Title.Contains(token, StringComparison.OrdinalIgnoreCase))) |
| | 0 | 778 | | .Select(item => new ExternalLinkSuggestion |
| | 0 | 779 | | { |
| | 0 | 780 | | Source = _options.Key, |
| | 0 | 781 | | Id = item.Id, |
| | 0 | 782 | | Title = item.Title, |
| | 0 | 783 | | Subtitle = BlobFilenameParser.PrettifySlug(categoryPath), |
| | 0 | 784 | | Category = categoryPath, |
| | 0 | 785 | | Icon = null, |
| | 0 | 786 | | Href = null |
| | 0 | 787 | | }); |
| | | 788 | | } |
| | | 789 | | } |