| | | 1 | | using System.Text.Json; |
| | | 2 | | using GistBackend.Handlers.ChromaDbHandler; |
| | | 3 | | using GistBackend.Handlers.MariaDbHandler; |
| | | 4 | | using GistBackend.Types; |
| | | 5 | | using GistBackend.Utils; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | using Microsoft.Extensions.DependencyInjection; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | using static GistBackend.Utils.LogEvents; |
| | | 10 | | |
| | | 11 | | namespace GistBackend.Controllers; |
| | | 12 | | |
| | | 13 | | public static class RoutingConstants |
| | | 14 | | { |
| | | 15 | | public const string GistsRoute = "/api/v1/gists"; |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | [ApiController] |
| | | 19 | | [Route(RoutingConstants.GistsRoute)] |
| | 10 | 20 | | public class GistsController( |
| | 10 | 21 | | [FromKeyedServices(StartUp.GistsControllerMariaDbHandlerOptionsName)] IMariaDbHandler mariaDbHandler, |
| | 10 | 22 | | IChromaDbHandler chromaDbHandler, |
| | 10 | 23 | | ILogger<GistsController>? logger) : ControllerBase |
| | | 24 | | { |
| | | 25 | | [HttpGet] |
| | | 26 | | public async Task<IActionResult> GetGistsQueryAsync( |
| | | 27 | | [FromQuery] int take = 20, |
| | | 28 | | [FromQuery] int? lastGist = null, |
| | | 29 | | [FromQuery] string? tags = null, |
| | | 30 | | [FromQuery] string? q = null, |
| | | 31 | | [FromQuery] string? disabledFeeds = null, |
| | | 32 | | [FromQuery] LanguageMode? languageMode = null, |
| | | 33 | | [FromQuery] bool? includeSponsoredContent = null, |
| | | 34 | | CancellationToken ct = default) |
| | | 35 | | { |
| | | 36 | | try |
| | | 37 | | { |
| | 5 | 38 | | var gists = await mariaDbHandler.GetPreviousConstructedGistsAsync(take, lastGist, ParseTags(tags), q, |
| | 5 | 39 | | ParseDisabledFeeds(disabledFeeds), languageMode, includeSponsoredContent, ct); |
| | 5 | 40 | | return Ok(gists); |
| | | 41 | | } |
| | 0 | 42 | | catch (Exception e) |
| | | 43 | | { |
| | | 44 | | const string message = "Could not get gists from the database"; |
| | 0 | 45 | | logger?.LogError(ErrorInHttpRequest, e, message); |
| | 0 | 46 | | return Problem(message); |
| | | 47 | | } |
| | 5 | 48 | | } |
| | | 49 | | |
| | | 50 | | [HttpGet("search")] |
| | | 51 | | public async Task<IActionResult> SearchSimilarGistsAsync( |
| | | 52 | | [FromQuery] string? q = null, |
| | | 53 | | [FromQuery] string? disabledFeeds = null, |
| | | 54 | | [FromQuery] LanguageMode? languageMode = null, |
| | | 55 | | CancellationToken ct = default) |
| | | 56 | | { |
| | | 57 | | try |
| | | 58 | | { |
| | 0 | 59 | | if (string.IsNullOrEmpty(q)) return BadRequest("Query parameter 'q' cannot be empty."); |
| | 0 | 60 | | var similarDocuments = |
| | 0 | 61 | | await chromaDbHandler.SearchSimilarEntriesByQueryAsync(q, 20, ParseDisabledFeeds(disabledFeeds), ct); |
| | 0 | 62 | | var gists = await Task.WhenAll(similarDocuments.Select(sd => mariaDbHandler.GetConstructedGistByReference(sd |
| | 0 | 63 | | var searchResults = gists.Zip(similarDocuments) |
| | 0 | 64 | | .Select(zipped => new GistSearchResult(zipped.First!, zipped.Second.Similarity)).ToList(); |
| | 0 | 65 | | return Ok(searchResults); |
| | | 66 | | } |
| | 0 | 67 | | catch (Exception e) |
| | | 68 | | { |
| | | 69 | | const string message = "Could not get gists from the database"; |
| | 0 | 70 | | logger?.LogError(ErrorInHttpRequest, e, message); |
| | 0 | 71 | | return Problem(message); |
| | | 72 | | } |
| | 0 | 73 | | } |
| | | 74 | | |
| | | 75 | | [HttpGet("health")] |
| | | 76 | | public Task<IActionResult> GetHealthAsync(CancellationToken ct = default) => |
| | 2 | 77 | | GetGistsQueryAsync(1, null, null, null, null, null, null, ct); |
| | | 78 | | |
| | | 79 | | [HttpGet("{id:int}")] |
| | | 80 | | public async Task<IActionResult> GetGistWithFeedByIdAsync( |
| | | 81 | | int id, |
| | | 82 | | [FromQuery] LanguageMode? languageMode = null, |
| | | 83 | | CancellationToken ct = default) |
| | | 84 | | { |
| | | 85 | | try |
| | | 86 | | { |
| | 0 | 87 | | var gist = await mariaDbHandler.GetConstructedGistByIdAsync(id, languageMode, ct); |
| | 0 | 88 | | if (gist is null) return NotFound(); |
| | 0 | 89 | | return Ok(gist); |
| | | 90 | | } |
| | 0 | 91 | | catch (Exception e) |
| | | 92 | | { |
| | | 93 | | const string message = "Could not get gist with feed by ID from the database"; |
| | 0 | 94 | | logger?.LogError(ErrorInHttpRequest, e, message); |
| | 0 | 95 | | return Problem(message); |
| | | 96 | | } |
| | 0 | 97 | | } |
| | | 98 | | |
| | | 99 | | [HttpGet("{id:int}/similar")] |
| | | 100 | | public async Task<IActionResult> GetSimilarGistsWithFeedAsync( |
| | | 101 | | int id, |
| | | 102 | | [FromQuery] string? disabledFeeds = null, |
| | | 103 | | [FromQuery] LanguageMode? languageMode = null, |
| | | 104 | | CancellationToken ct = default) |
| | | 105 | | { |
| | | 106 | | try |
| | | 107 | | { |
| | 3 | 108 | | var gistWithFeed = await mariaDbHandler.GetConstructedGistByIdAsync(id, languageMode, ct); |
| | 4 | 109 | | if (gistWithFeed is null) return NotFound(); |
| | 2 | 110 | | var similarityResults = |
| | 2 | 111 | | await chromaDbHandler.GetReferenceAndScoreOfSimilarEntriesAsync(gistWithFeed.Reference, 5, |
| | 2 | 112 | | ParseDisabledFeeds(disabledFeeds), ct); |
| | 2 | 113 | | var gistsWithFeed = new List<SimilarGistWithFeed>(); |
| | 10 | 114 | | foreach (var similarityResult in similarityResults) |
| | | 115 | | { |
| | 3 | 116 | | gistsWithFeed.Add(await GetSimilarGistWithFeedFromDatabaseAsync(similarityResult, languageMode, ct)); |
| | | 117 | | } |
| | 2 | 118 | | return Ok(gistsWithFeed); |
| | | 119 | | } |
| | 0 | 120 | | catch (Exception e) |
| | | 121 | | { |
| | | 122 | | const string message = "Could not get similar gists from the database"; |
| | 0 | 123 | | logger?.LogError(ErrorInHttpRequest, e, message); |
| | 0 | 124 | | return Problem(message); |
| | | 125 | | } |
| | 3 | 126 | | } |
| | | 127 | | |
| | | 128 | | private async Task<SimilarGistWithFeed> GetSimilarGistWithFeedFromDatabaseAsync(SimilarDocument similarDocument, |
| | | 129 | | LanguageMode? languageMode, CancellationToken ct) |
| | | 130 | | { |
| | 3 | 131 | | var gistWithFeed = await mariaDbHandler.GetConstructedGistByReference(similarDocument.Reference, languageMode, c |
| | 3 | 132 | | if (gistWithFeed is null) |
| | | 133 | | { |
| | 0 | 134 | | throw new KeyNotFoundException( |
| | 0 | 135 | | $"Similar gist with reference {similarDocument.Reference} not found in database"); |
| | | 136 | | } |
| | 3 | 137 | | return new SimilarGistWithFeed(gistWithFeed, similarDocument.Similarity); |
| | 3 | 138 | | } |
| | | 139 | | |
| | | 140 | | [HttpGet("feeds")] |
| | | 141 | | public async Task<IActionResult> GetAllFeedsAsync(CancellationToken ct) |
| | | 142 | | { |
| | | 143 | | try |
| | | 144 | | { |
| | 2 | 145 | | var feeds = await mariaDbHandler.GetAllFeedInfosAsync(ct); |
| | 2 | 146 | | return Ok(feeds); |
| | | 147 | | } |
| | 0 | 148 | | catch (Exception e) |
| | | 149 | | { |
| | | 150 | | const string message = "Could not get all feeds from the database"; |
| | 0 | 151 | | logger?.LogError(ErrorInHttpRequest, e, message); |
| | 0 | 152 | | return Problem(message); |
| | | 153 | | } |
| | 2 | 154 | | } |
| | | 155 | | |
| | | 156 | | [HttpGet("recap/daily")] |
| | | 157 | | public Task<IActionResult> GetDailyRecapAsync([FromQuery] LanguageMode languageMode, CancellationToken ct) => |
| | 0 | 158 | | GetRecapAsync(RecapType.Daily, languageMode, ct); |
| | | 159 | | |
| | | 160 | | [HttpGet("recap/weekly")] |
| | | 161 | | public Task<IActionResult> GetWeeklyRecapAsync([FromQuery] LanguageMode languageMode, CancellationToken ct) => |
| | 0 | 162 | | GetRecapAsync(RecapType.Weekly, languageMode, ct); |
| | | 163 | | |
| | | 164 | | private async Task<IActionResult> GetRecapAsync(RecapType type, LanguageMode languageMode, CancellationToken ct) |
| | | 165 | | { |
| | | 166 | | try |
| | | 167 | | { |
| | 0 | 168 | | if (languageMode == LanguageMode.Original) |
| | | 169 | | { |
| | 0 | 170 | | throw new ArgumentException("Language mode 'Original' is not supported for recaps"); |
| | | 171 | | } |
| | 0 | 172 | | var serializedRecap = await mariaDbHandler.GetLatestRecapAsync(type, ct); |
| | 0 | 173 | | if (serializedRecap is null) return NotFound("No recap found in the database"); |
| | 0 | 174 | | var serializedRecapSections = |
| | 0 | 175 | | languageMode == LanguageMode.En ? serializedRecap.RecapEn : serializedRecap.RecapDe; |
| | 0 | 176 | | var recapSections = |
| | 0 | 177 | | JsonSerializer.Deserialize<IEnumerable<RecapSection>>(serializedRecapSections, |
| | 0 | 178 | | SerializerDefaults.JsonOptions); |
| | 0 | 179 | | if (recapSections is null) |
| | | 180 | | { |
| | 0 | 181 | | throw new JsonException($"Could not deserialize recap from this JSON: {serializedRecapSections}"); |
| | | 182 | | } |
| | | 183 | | |
| | 0 | 184 | | recapSections = recapSections.ToList(); |
| | 0 | 185 | | var gistTitlesById = new Dictionary<int, string>(); |
| | 0 | 186 | | var gistIds = recapSections.SelectMany(s => s.Related).Distinct().ToList(); |
| | 0 | 187 | | foreach (var gistId in gistIds) |
| | | 188 | | { |
| | 0 | 189 | | var gistWithFeed = await mariaDbHandler.GetConstructedGistByIdAsync(gistId, LanguageMode.Original, ct); |
| | 0 | 190 | | if (gistWithFeed is not null) gistTitlesById[gistId] = gistWithFeed.Title; |
| | | 191 | | } |
| | | 192 | | |
| | 0 | 193 | | var deserializedRecapSections = recapSections.Select(s => new DeserializedRecapSection(s.Heading, |
| | 0 | 194 | | s.Recap, |
| | 0 | 195 | | s.Related.Where(r => gistTitlesById.ContainsKey(r)) |
| | 0 | 196 | | .Select(r => new RelatedGistInfo(r, gistTitlesById[r])))); |
| | 0 | 197 | | var deserializedRecap = new DeserializedRecap(serializedRecap.Created, deserializedRecapSections, |
| | 0 | 198 | | serializedRecap.Id ?? -1); |
| | 0 | 199 | | return Ok(deserializedRecap); |
| | | 200 | | } |
| | 0 | 201 | | catch (Exception e) |
| | | 202 | | { |
| | | 203 | | const string message = "Could not get recap from the database"; |
| | 0 | 204 | | logger?.LogError(CouldNotGetRecap, e, message); |
| | 0 | 205 | | return Problem(message); |
| | | 206 | | } |
| | 0 | 207 | | } |
| | | 208 | | |
| | 5 | 209 | | private static List<string> ParseTags(string? tags) => string.IsNullOrWhiteSpace(tags) |
| | 5 | 210 | | ? [] |
| | 5 | 211 | | : tags |
| | 5 | 212 | | .Split(";;", StringSplitOptions.RemoveEmptyEntries) |
| | 2 | 213 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 7 | 214 | | .Select(tag => tag.Trim()).ToList(); |
| | | 215 | | |
| | 7 | 216 | | private static List<int> ParseDisabledFeeds(string? disabledFeeds) => string.IsNullOrWhiteSpace(disabledFeeds) |
| | 7 | 217 | | ? [] |
| | 7 | 218 | | : disabledFeeds |
| | 7 | 219 | | .Split(',', StringSplitOptions.RemoveEmptyEntries) |
| | 8 | 220 | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | 8 | 221 | | .Select(id => id.Trim()) |
| | 7 | 222 | | .Select(int.Parse) |
| | 7 | 223 | | .ToList(); |
| | | 224 | | } |