30 Commits

Author SHA1 Message Date
75beb7a8a1 fix: allow for image deletion (by leaving blank url) 2025-07-30 11:14:12 +02:00
d81a6b961c feat: endpoint for getting server restrictions 2025-07-29 13:40:22 +02:00
56bd82f6a2 fix: do not assume a default model in DTO 2025-07-29 13:07:04 +02:00
870fcf7573 feat: send model used as in llm quote generation 2025-07-29 11:11:58 +02:00
e9b36b5d49 feat: print error message on failed llm quote generation attempt 2025-07-29 11:11:28 +02:00
8a8aac77da feat: return creation/update time 2025-07-28 14:09:51 +02:00
98dc591dce fix: disable authentication for GET /api/v1/categories
allows unauthenticated users to select a category for random draw
2025-07-28 10:42:09 +02:00
b892aeceae chore: ignore user uploads for versioning 2025-07-26 18:36:59 +02:00
b603f96ec5 fix: de-authorize endpoint for history retrieval 2025-07-24 13:57:31 +02:00
8324ba8456 chore: mention deletion of reference in endpoint documentation 2025-07-24 13:26:11 +02:00
89a4140b53 fix: remove references to deleted images from quotes 2025-07-24 13:20:15 +02:00
12f489749a Merge branch 'user_content' 2025-07-24 11:40:16 +02:00
11d24dcc11 feat: image deletion endpoint
handles image deletion from disk as well, if a file is sourced locally
2025-07-24 11:39:59 +02:00
bb9bdcfaa0 fix: add images to db, minor status codes tweaks 2025-07-24 11:09:33 +02:00
601d99bccd zdjęcia 2025-07-24 10:47:20 +02:00
3e823fb37b feat: LLM API endpoint 2025-07-23 18:45:03 +02:00
9e9017717a feat: helper function for generating LLM responses 2025-07-23 18:28:28 +02:00
bc05e91790 chore: add core dependency, and a DTO for user input 2025-07-23 18:24:35 +02:00
df4cd1c8a7 fix: include .jpeg as an allowed file extension 2025-07-23 12:48:05 +02:00
f60f613969 feat: template for image upload 2025-07-23 12:19:29 +02:00
ceb1829eb9 fix: load images for randomly drawn quotes 2025-07-23 09:58:28 +02:00
a1086b94f1 feat: bring back categories endpoint with no pagination
now it requires authorization
2025-07-23 09:44:56 +02:00
ba162c34cc chore: nitpicky details 2025-07-22 14:08:37 +02:00
197918e526 fix: keep API path names consistent 2025-07-22 14:01:32 +02:00
ac80061437 feat: paginate categories 2025-07-22 13:28:27 +02:00
e7cebc32a4 feat: naive sanity check for image URLs 2025-07-22 13:09:13 +02:00
9e1e9c86d3 feat: sort the quotes from newest first by default 2025-07-22 12:43:35 +02:00
10d2a35e61 Merge branch 'main' into Tydz3,-losowanie-z-kategoria 2025-07-22 12:06:44 +02:00
ca78f43f73 chore: documentation for category modification 2025-07-22 12:06:22 +02:00
3a82e4291e edycja kategorii 2025-07-22 11:45:48 +02:00
13 changed files with 661 additions and 30 deletions

3
.gitignore vendored
View File

@@ -417,3 +417,6 @@ FodyWeavers.xsd
# ---------- # ----------
# Files storing credentials # Files storing credentials
appsettings.json appsettings.json
# User uploads
wwwroot/uploads/images

View File

@@ -27,21 +27,74 @@ public class CategoryController : ControllerBase
guhf = GUHF; guhf = GUHF;
} }
// GET /api/v1/categories/page/1
/// <summary>
/// Get a category page
/// </summary>
/// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/>
/// Has CORS set.
/// </remarks>
/// <param name="page_no">The page number</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")]
[EnableCors]
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetCategoryPage(int page_no = 1)
{
// The following seems to be a bad idea, so I leave it as is. ~eee4
//
// int totalCategories = await _db.Categories.CountAsync();
//
// if (totalCategories <= 0)
// {
// return NoContent(new ErrorDTO { Status = "error", Error_msg = "No categories to list" });
// }
const int PageSize = 10;
if (page_no <= 0)
{
return NotFound(new ErrorDTO { Status = "error", Error_msg = "Numer strony musi być większy niż 0" });
}
// Get all the categories
//List<Category> categories = await _db.Categories
// .ToListAsync();
List<Category> categories = await _db.Categories
.Skip((page_no - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
// Convert them to a list of DTO
List<CategoryShortDTO> result = categories
.Select(c => c.ToCategoryShortDTO())
.ToList();
// Return to user
return Ok(result);
}
// GET /api/v1/categories // GET /api/v1/categories
/// <summary> /// <summary>
/// Get every category /// Get every category
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Can (and will) return an empty list if no categories are found in DB. <br/> /// Can (and will) return an empty list if no categories are found in DB. <br/><br/>
/// <s>Unlike GET /api/v1/categories/page/..., requires authorization with a JWT.</s>
/// Not the case anymore, as choosing a quote from a category requires the user to know
/// of existing categories.<br/><br/>
/// Has CORS set. /// Has CORS set.
/// </remarks> /// </remarks>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
// /// <response code="404">Returned when there are no categories to list</response> // /// <response code="404">Returned when there are no categories to list</response>
[HttpGet] [HttpGet]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)] [ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
// [ProducesResponseType(typeof(ErrorDTO), 404)] public async Task<IActionResult> GetEveryCategory()
public async Task<IActionResult> GetQuotePage()
{ {
// The following seems to be a bad idea, so I leave it as is. ~eee4 // The following seems to be a bad idea, so I leave it as is. ~eee4
// //
@@ -66,6 +119,7 @@ public class CategoryController : ControllerBase
} }
// POST /api/v1/categories // POST /api/v1/categories
/// <summary> /// <summary>
/// [AUTHED] Create a new category /// [AUTHED] Create a new category
@@ -155,8 +209,49 @@ public class CategoryController : ControllerBase
return Ok(new { Status = "ok" }); return Ok(new { Status = "ok" });
} }
// TODO: Update category
// PATCH /api/v1/categories/1 // PATCH /api/v1/categories/1
/// <summary>
/// [AUTHED] Modify an existing category
/// </summary>
/// <remarks>
/// Allows authorized users to modify categories.
/// <br/><br/>
/// Has CORS set.
/// </remarks>
/// <param name="id">Id of the category which shall be modified</param>
/// <param name="updatedCategory">DTO with new name and description. Id and creation date are ignored.</param>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when category name is empty or null</response>
/// <response code="404">Returned when no such category exists</response>
[HttpPatch("{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> EditCategory(int id, [FromBody] CategoryShortDTO updatedCategory)
{
// Find the category to modify
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == id);
// Failed?
if (cat == null)
return NotFound(new { status = "error", error_msg = "Category not found" });
// Otherwise, ensure the category name is not empty or null
if (string.IsNullOrWhiteSpace(updatedCategory.Name))
return BadRequest(new ErrorDTO { Status = "error", Error_msg = "Category name cannot be empty." });
// Update the fields
cat.Name = updatedCategory.Name;
cat.Description = updatedCategory.Description;
// Note the user cannot modify the createdAt field,
// and we do not store last modification date.
await _db.SaveChangesAsync();
// Return the modified category to user
return Ok(cat.ToCategoryShortDTO());
}
} }

View File

@@ -1,5 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QuotifyBE.Data; using QuotifyBE.Data;
using QuotifyBE.Entities; using QuotifyBE.Entities;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
@@ -132,4 +134,113 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
return new JwtSecurityTokenHandler().WriteToken(token); return new JwtSecurityTokenHandler().WriteToken(token);
} }
public async Task<JObject?> GenerateLLMResponse(string? prompt, string? model, float? temp, int? includedCategory, bool? includeCategorySample)
{
string _model = model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
float _temp = temp ?? 0.8f; // sane default
string _included_sample = string.Empty;
string _prompt = prompt ?? _appsettings.GetSection("LlmIntegration")["DefaultPrompt"] ??
"Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat? " +
"Zastanów się nad jego puentą, a kiedy będziesz gotów - zwróć sam cytat. " +
"Nie pytaj mnie co o nim sądzę, ani nie używaj emotikonów (emoji). " +
"Pamiętaj, że dobre cytaty są krótkie, zwięzłe.";
if (includedCategory != null)
{
// Check if category to be included is present.
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == includedCategory.Value);
// It isn't?
if (cat == null) return null;
// It is?
_prompt += $" Niech należy on do kategorii o nazwie \"{cat.Name}\" ({cat.Description}).";
}
// Sanity check
if (includeCategorySample != null && includeCategorySample == true)
{
if (includedCategory == null)
{
// Can't append something that we're not given.
return null;
}
else
{
// Try to find the category in question.
Category? cat = await _db.Categories.FirstOrDefaultAsync(c => c.Id == includedCategory.Value);
// Failed?
if (cat == null)
{
return null;
}
else
{
IQueryable<Quote> query = _db.Quotes
.Include(q => q.QuoteCategories!)
.Where(q => q.QuoteCategories
.Any(qc => qc.Category == cat)
);
int totalQuotes = await query.CountAsync();
if (totalQuotes > 0) {
Random random = new();
int skip = random.Next(0, totalQuotes);
Quote? quote = await query
.Skip(skip)
.Take(1)
.FirstOrDefaultAsync();
if (quote != null) {
_prompt += $" Przykładowy cytat z tej kategorii brzmi: \"{quote.Text} ~ {quote.Author}\".\n";
}
}
}
}
}
List<Dictionary<string, string>> promptMessages =
[
new() { { "role", "user" }, {"content", _prompt } }
];
// Will throw error if not present
string apiUrl = _appsettings.GetSection("LlmIntegration")["ApiUrl"] + "/chat/completions"
?? throw new MissingFieldException("API URL missing in LlmIntegration section of appsettings.json!");
string apiKey = _appsettings.GetSection("LlmIntegration")["ApiKey"]
?? throw new MissingFieldException("API key missing in LlmIntegration section of appsettings.json!");
using (var client = new HttpClient())
{
// Not the best practice if we want reusable connections
// https://stackoverflow.com/a/40707446
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
var json = JsonConvert.SerializeObject(new
{
model = _model,
temperature = _temp,
max_tokens = (includeCategorySample ?? false) ? 2000 : 1000,
messages = promptMessages
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
string receivedResponse = await response.Content.ReadAsStringAsync();
return JObject.Parse(receivedResponse);
}
else
{
// Handle the error
JObject error = JObject.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine($"[QuotifyBE] Error: response status code from API was {response.StatusCode}.");
if (error != null && error["error"] != null && error["error"]!["message"] != null)
{
Console.WriteLine($" Error message: {error["error"]!["message"]}");
}
return null;
}
}
}
} }

View File

@@ -1,14 +1,12 @@
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update.Internal; using Newtonsoft.Json.Linq;
using QuotifyBE.Data; using QuotifyBE.Data;
using QuotifyBE.DTOs; using QuotifyBE.DTOs;
using QuotifyBE.Entities; using QuotifyBE.Entities;
using QuotifyBE.Mapping; using QuotifyBE.Mapping;
using System.Reflection.Metadata.Ecma335;
using System.Security.Claims; using System.Security.Claims;
namespace QuotifyBE.Controllers; namespace QuotifyBE.Controllers;
@@ -22,11 +20,13 @@ public class QuotesController : ControllerBase
private readonly ApplicationDbContext _db; private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf; private readonly GeneralUseHelpers guhf;
private readonly IConfiguration _appsettings;
public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF) public QuotesController(ApplicationDbContext db, GeneralUseHelpers GUHF, IConfiguration appsettings)
{ {
_db = db; _db = db;
guhf = GUHF; guhf = GUHF;
_appsettings = appsettings;
} }
// GET /api/v1/quotes // GET /api/v1/quotes
@@ -41,15 +41,16 @@ public class QuotesController : ControllerBase
/// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random. /// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
/// </remarks> /// </remarks>
/// <param name="page_no">The page number</param> /// <param name="page_no">The page number</param>
/// <param name="sort">How to sort the results (desc/asc)</param>
/// <param name="category_id">(Optional) Standalone category id or comma separated ids (e.g. "1" or "1,2,3")</param> /// <param name="category_id">(Optional) Standalone category id or comma separated ids (e.g. "1" or "1,2,3")</param>
/// <returns>A page (&lt;= 10 quotes)</returns> /// <returns>A page (&lt;= 10 quotes)</returns>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response> /// <response code="404">Returned when requested page is invalid (page_no &lt;= 0)</response>
[HttpGet("page/{page_no}")] [HttpGet("page/{page_no}")]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)] [ProducesResponseType(typeof(List<QuoteCompleteDTO>), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuotePage(int page_no, [FromQuery] string? category_id = null) public async Task<IActionResult> GetQuotePage(int page_no = 1, string? sort = "desc", [FromQuery] string? category_id = null)
{ {
var totalQuotes = await _db.Quotes.CountAsync(); var totalQuotes = await _db.Quotes.CountAsync();
const int PageSize = 10; const int PageSize = 10;
@@ -80,8 +81,15 @@ public class QuotesController : ControllerBase
.Include(q => q.QuoteCategories!) .Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category) .ThenInclude(qc => qc.Category)
.Include(q => q.User) .Include(q => q.User)
.Include(q => q.Image) .Include(q => q.Image);
.OrderBy(q => q.Id);
// Sort the results in ascending/descending order by id
IOrderedQueryable<Quote>? orderedQuery;
if (sort != null && sort.Equals("asc"))
orderedQuery = baseQuery.OrderBy(q => q.Id);
else
// Sort in descending order by default
orderedQuery = baseQuery.OrderByDescending(q => q.Id);
// Botched solution // Botched solution
List<Quote> pageQuotes; List<Quote> pageQuotes;
@@ -89,7 +97,7 @@ public class QuotesController : ControllerBase
// Filtrowanie przed pobraniem strony // Filtrowanie przed pobraniem strony
if (categories != null) if (categories != null)
{ {
pageQuotes = await baseQuery pageQuotes = await orderedQuery
.Where(q => q.QuoteCategories! .Where(q => q.QuoteCategories!
.Any(qc => categories.Contains(qc.CategoryId)) .Any(qc => categories.Contains(qc.CategoryId))
//.Any(qc => qc.CategoryId == category_id.Value) //.Any(qc => qc.CategoryId == category_id.Value)
@@ -100,14 +108,14 @@ public class QuotesController : ControllerBase
} }
else else
{ {
pageQuotes = await baseQuery pageQuotes = await orderedQuery
.Skip((page_no - 1) * PageSize) .Skip((page_no - 1) * PageSize)
.Take(PageSize) .Take(PageSize)
.ToListAsync(); .ToListAsync();
} }
var result = pageQuotes var result = pageQuotes
.Select(q => q.ToQuoteShortDTO()) .Select(q => q.ToQuoteCompleteDTO())
.ToList(); .ToList();
return Ok(result); return Ok(result);
@@ -119,15 +127,14 @@ public class QuotesController : ControllerBase
/// [AUTHED] Get specified quote summary /// [AUTHED] Get specified quote summary
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// As per project's guidelines, requires a JWT. /// <s>As per project's guidelines, requires a JWT.</s> We need this endpoint to check previous draws for draw history.
/// </remarks> /// </remarks>
/// <param name="id">The quote id in question</param> /// <param name="id">The quote id in question</param>
/// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns> /// <returns>A quote: id, quote content and author, imageUrl and categories if successful, otherwise: error message</returns>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when quote id is invalid or simply doesn't exist</response> /// <response code="404">Returned when quote id is invalid or simply doesn't exist</response>
[HttpGet("{id}")] [HttpGet("{id}")]
[Authorize] [ProducesResponseType(typeof(QuoteCompleteDTO), 200)]
[ProducesResponseType(typeof(QuoteShortDTO), 200)]
[ProducesResponseType(typeof(ErrorDTO), 404)] [ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> GetQuoteById(int id) public async Task<IActionResult> GetQuoteById(int id)
{ {
@@ -142,7 +149,7 @@ public class QuotesController : ControllerBase
if (quote == null) if (quote == null)
return NotFound(new { status = "error", error_msg = "Quote not found" }); return NotFound(new { status = "error", error_msg = "Quote not found" });
return Ok(quote.ToQuoteShortDTO()); return Ok(quote.ToQuoteCompleteDTO());
} }
// POST /api/v1/quotes/new // POST /api/v1/quotes/new
@@ -150,32 +157,50 @@ public class QuotesController : ControllerBase
/// [AUTHED] Add a new quote /// [AUTHED] Add a new quote
/// </summary> /// </summary>
/// <returns>Newly created quote's id</returns> /// <returns>Newly created quote's id</returns>
/// <remarks>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </remarks>
/// <param name="request">Form data containing required quote information</param> /// <param name="request">Form data containing required quote information</param>
/// <response code="201">Returned on valid request</response> /// <response code="201">Returned on valid request</response>
/// <response code="400">Returned when any of the categories does not exist</response> /// <response code="400">Returned when any of the categories does not exist</response>
/// <response code="403">Returned when user's id does not match the creator's id</response> /// <response code="403">Returned when user's id does not match the creator's id</response>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPost("new")] [HttpPost("new")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(201)] [ProducesResponseType(201)]
[ProducesResponseType(typeof(ErrorDTO), 400)] [ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 403)] [ProducesResponseType(typeof(ErrorDTO), 403)]
[ProducesResponseType(typeof(ErrorDTO), 406)]
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request) public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
{ {
// Get user ID from claims // Get user ID from claims
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId)) if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
// https://stackoverflow.com/a/47708867 // https://stackoverflow.com/a/47708867
return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" }); return StatusCode(403, new ErrorDTO { Status = "error", Error_msg = "Invalid user ID" });
// Find or create image // Try to find the image inside the DB
Image? image = null; Image? image = null;
if (!string.IsNullOrEmpty(request.ImageUrl)) if (!string.IsNullOrEmpty(request.ImageUrl))
{ {
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl); image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
// Failed? Just insert it yourself
if (image == null) if (image == null)
{ {
// Simple (naive) sanity check for image URLs
if ( !request.ImageUrl.StartsWith("http://")
&& !request.ImageUrl.StartsWith("https://")
&& !request.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
image = new Image { Url = request.ImageUrl }; image = new Image { Url = request.ImageUrl };
_db.Images.Add(image); _db.Images.Add(image);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -232,7 +257,8 @@ public class QuotesController : ControllerBase
{ {
IQueryable<Quote> query = _db.Quotes IQueryable<Quote> query = _db.Quotes
.Include(q => q.QuoteCategories!) .Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category); .ThenInclude(qc => qc.Category)
.Include(q => q.Image);
if (category_id.HasValue) if (category_id.HasValue)
{ {
@@ -255,8 +281,6 @@ public class QuotesController : ControllerBase
var skip = random.Next(0, totalQuotes); var skip = random.Next(0, totalQuotes);
var quote = await query var quote = await query
.Include(q => q.QuoteCategories!)
.ThenInclude(qc => qc.Category)
.Skip(skip) .Skip(skip)
.Take(1) .Take(1)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
@@ -339,13 +363,19 @@ public class QuotesController : ControllerBase
/// While "categories = null" will not alter the quote's categories, /// While "categories = null" will not alter the quote's categories,
/// "categories = []" will (and in turn, empty each and every present category)!<br/> /// "categories = []" will (and in turn, empty each and every present category)!<br/>
/// Be careful when handling user-provided categories! /// Be careful when handling user-provided categories!
/// <br/><br/>
/// <b>Note</b>:
/// User-provided image URLs are validated by checking
/// if they start with "https://", "http://" or "/".
/// This is rather a naive solution.
/// </remarks> /// </remarks>
/// <returns>Newly modified quote as a DTO</returns> /// <returns>Newly modified quote as a DTO</returns>
/// <param name="id">Quote to be modified</param> /// <param name="id">Quote to be modified</param>
/// <param name="updatedQuote">Updated quote form data</param> /// <param name="updatedQuote">Updated quote form data. Id is ignored.</param>
/// <response code="204">Returned on valid request</response> /// <response code="204">Returned on valid request</response>
/// <response code="400">Returned when request text or author is empty (or whitespace)</response> /// <response code="400">Returned when request text or author is empty (or whitespace)</response>
/// <response code="404">Returned when no such quote exists</response> /// <response code="404">Returned when no such quote exists</response>
/// <response code="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
[HttpPatch("{id}")] [HttpPatch("{id}")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
@@ -357,6 +387,7 @@ public class QuotesController : ControllerBase
// Try to find the quote in question // Try to find the quote in question
Quote? quote = await _db.Quotes Quote? quote = await _db.Quotes
.Include(q => q.QuoteCategories) .Include(q => q.QuoteCategories)
.Include(q => q.Image)
.FirstOrDefaultAsync(q => q.Id == id); .FirstOrDefaultAsync(q => q.Id == id);
// Failed? // Failed?
@@ -377,9 +408,19 @@ public class QuotesController : ControllerBase
if (!string.IsNullOrEmpty(updatedQuote.ImageUrl)) if (!string.IsNullOrEmpty(updatedQuote.ImageUrl))
{ {
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl); image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl);
// Failed? Just insert it yourself // Failed? Just insert it yourself
if (image == null) if (image == null)
{ {
// Simple (naive) sanity check for image URLs
if ( !updatedQuote.ImageUrl.StartsWith("http://")
&& !updatedQuote.ImageUrl.StartsWith("https://")
&& !updatedQuote.ImageUrl.StartsWith("/"))
return StatusCode(406, new ErrorDTO {
Status = "error",
Error_msg = "Image URLs should point to http/https url or a local resource"
});
image = new Image { Url = updatedQuote.ImageUrl }; image = new Image { Url = updatedQuote.ImageUrl };
_db.Images.Add(image); _db.Images.Add(image);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -443,4 +484,77 @@ public class QuotesController : ControllerBase
return Ok(quote.ToQuoteShortDTO()); return Ok(quote.ToQuoteShortDTO());
} }
// POST /api/v1/quotes/ai
/// <summary>
/// [AUTHED] Request a LLM-generated quote
/// </summary>
/// <returns>Generated quote's text</returns>
/// <remarks>
/// <b>Notes</b>:<br/>
///
/// <ul>
/// If <i>customPrompt</i> is passed:
/// <li>The default prompt is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>model</i> is passed:
/// <li>The default large language model is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>temperature</i> is passed:
/// <li>The default temperature (= 0.8) is overriden by whatever has been passed by the user.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>categoryId</i> is passed:
/// <li>The prompt is appended with an instruction in Polish to generate quotes based on the provided category
/// (both name and description get passed to the model).</li>
/// <li><b>Heads up!</b> The text is appended even if <i>customPrompt</i> has been provided.</li>
/// </ul><br/>
///
/// <ul>
/// If <i>useSampleQuote</i> is passed:
/// <li>The prompt will be appended with a randomly chosen quote from the categoryId (if any exist),
/// thus passing categoryId becomes a prerequisite.</li>
/// <li><b>Heads up!</b> The request will fail returning status code 400 if categoryId isn't provided!</li>
/// </ul>
/// </remarks>
/// <param name="request">Form data containing required quote information</param>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when generation failed due to remote server error (likely because of a bad request)</response>
/// <response code="500">Returned when response has been generated, but couldn't be parsed (likely because of incompatible server or bad URL)</response>
[HttpPost("ai")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 500)]
public async Task<IActionResult> CreateLLMQuote([FromBody] AskLLMInDTO request)
{
JObject? generatedResponse = await guhf.GenerateLLMResponse(
request.CustomPrompt, request.Model, request.Temperature, request.CategoryId, request.UseSampleQuote
);
string llmUsed = request.Model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
// Check if any errors occurred
if (generatedResponse == null)
{
return StatusCode(400, new ErrorDTO { Status = "error", Error_msg = "Generation failed most likely due to bad request" });
}
// Parse JSON to get the bot reply
string? llmResponse = generatedResponse["choices"]?[0]?["message"]?["content"]?.ToString().Trim('"');
// If response string is not where we expect it, return 500
if (llmResponse == null)
return StatusCode(500, new ErrorDTO { Status = "error", Error_msg = "Unexpected API response" });
// Otherwise, return the response
return Ok(new { Status = "ok", BotResponse = llmResponse, Model = llmUsed });
}
} }

View File

@@ -10,12 +10,12 @@ namespace QuotifyBE.Controllers;
[EnableCors] [EnableCors]
[Route("api/v1/stats")] [Route("api/v1/stats")]
[Produces("application/json")] [Produces("application/json")]
public class StatisticController : ControllerBase public class StatisticsController : ControllerBase
{ {
private readonly ApplicationDbContext _db; private readonly ApplicationDbContext _db;
public StatisticController( ApplicationDbContext db) public StatisticsController( ApplicationDbContext db)
{ {
_db = db; _db = db;
} }

View File

@@ -0,0 +1,244 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using QuotifyBE.DTOs;
using QuotifyBE.Mapping;
using Microsoft.AspNetCore.Cors;
using Microsoft.EntityFrameworkCore;
namespace QuotifyBE.Controllers;
[ApiController]
[EnableCors]
[Route("api/v1/uc")]
[Produces("application/json")]
public class UserContentController : ControllerBase
{
private readonly IConfiguration _appsettings;
private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf;
List<string> _allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
public UserContentController(IConfiguration appsettings, ApplicationDbContext db, GeneralUseHelpers GUHF)
{
_appsettings = appsettings;
_db = db;
guhf = GUHF;
}
// GET /api/v1/uc/images
/// <summary>
/// [AUTHED] Get every image
/// </summary>
/// <remarks>
/// Can (and will) return an empty list if no images are found in DB. <br/>
/// Requires authorization with a JWT, has CORS set.
/// </remarks>
/// <response code="200">Returned on valid request</response>
[HttpGet("images")]
[Authorize]
[EnableCors]
[ProducesResponseType(typeof(List<Image>), 200)]
public async Task<IActionResult> GetImages()
{
// Get all the images
List<Image> images = await _db.Images
.ToListAsync();
// Return to user
return Ok(images);
}
// POST /api/v1/uc/images
/// <summary>
/// [AUTHED] Upload an image and get an its URI
/// </summary>
/// <remarks>
/// Allows authorized users to publish images.
/// A user-reachable path and image id is returned on success.<br/>
/// </remarks>
/// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when request does not contain a file or the file is blank</response>
/// <response code="413">Returned when image size is too large</response>
/// <response code="415">Returned when file extension/mimetype is unknown</response>
[HttpPost("images")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 413)]
[ProducesResponseType(typeof(ErrorDTO), 415)]
public IActionResult PostNewImage(IFormFile file)
{
// Obsługa braku pliku
if (file == null || file.Length == 0)
{
return BadRequest(new ErrorDTO
{
Status = "error",
Error_msg = "No file was uploaded."
});
}
// Dozwolone rozszerzenia
string fileExtension = Path.GetExtension(file.FileName).ToLower();
if (!_allowedExtensions.Contains(fileExtension))
{
return StatusCode(415, new ErrorDTO
{
Status = "error",
Error_msg = $"Unknown file extension. Allowed: {string.Join(", ", _allowedExtensions)}"
});
}
// Sprawdzenie typu MIME (opcjonalnie dokładniejsze)
if (!file.ContentType.StartsWith("image/"))
{
return StatusCode(415, new ErrorDTO
{
Status = "error",
Error_msg = "Uploaded file is not an image."
});
}
// Ograniczenie rozmiaru pliku do tego, ustawionego przez użytkownika
int MaxFileSize = int.TryParse(_appsettings.GetSection("UserContent")["MaxFileSize"], out int r)
? r
: 5 * 1024 * 1024;
if (file.Length > MaxFileSize)
{
return StatusCode(413, new ErrorDTO
{
Status = "error",
Error_msg = $"File size exceeds {MaxFileSize / 1024 / 1024} MB."
});
}
// Generowanie unikalnej nazwy
string uniqueFileName = $"{Guid.NewGuid()}{fileExtension}";
string relativePath = $"/uploads/images/{uniqueFileName}";
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
// Upewnij się, że katalog istnieje
Directory.CreateDirectory(Path.GetDirectoryName(absolutePath)!);
// Zapis pliku na dysk
using (var stream = new FileStream(absolutePath, FileMode.Create))
{
file.CopyTo(stream);
}
// Dodaj do bazy
Image image = new Image { Url = relativePath };
_db.Images.Add(image);
_db.SaveChanges();
// Zwracany adres URL (np. do użytku w cytacie)
return Ok(new
{
Status = "ok",
Filepath = relativePath,
ImageId = image.Id
});
}
// GET /api/v1/uc/restrictions
/// <summary>
/// [AUTHED] Get server restrictions for file upload
/// </summary>
/// <remarks>
/// Returns a list of allowed file extensions and mimetypes for upload.
/// </remarks>
/// <response code="200">Returned on valid request</response>
[HttpGet("restrictions")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
public IActionResult GetFileUploadRestrictions()
{
return Ok(new
{
Status = "ok",
AllowedMimeTypes = new List<string>
{
"image/" // this could be done dynamically ~eee4
},
AllowedExtensions = _allowedExtensions,
MaxFileSize = int.TryParse(_appsettings.GetSection("UserContent")["MaxFileSize"], out int r)
? r
: 5 * 1024 * 1024
});
}
// DELETE /api/v1/uc/images/{id}
/// <summary>
/// [AUTHED] Delete an image
/// </summary>
/// <remarks>
/// Deletes an image, granted it exists.
/// <br/><br/>
/// <b>Note</b>:
/// If the image is a file on disk, it's also deleted.
/// <br/><br/>
/// <b>Warning</b>:
/// Any reference to deleted image in Quotes table will also be deleted (nullified).
/// </remarks>
/// <returns>Json with status</returns>
/// <param name="id">Image id which will be deleted</param>
/// <response code="200">Returned on valid request</response>
/// <response code="404">Returned when no such image exists</response>
[HttpDelete("images/{id}")]
[Authorize]
[EnableCors]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 404)]
public async Task<IActionResult> DeleteImage(int id)
{
// (Attempt to) find the image
Image? image = await _db.Images
.FirstOrDefaultAsync(q => q.Id == id);
// Failed?
if (image == null)
return NotFound(new { status = "error", error_msg = "Image not found" });
// If succeded, remove the image:
// - from disk - if saved locally
if (!string.IsNullOrEmpty(image.Url)) {
if (image.Url.StartsWith("/uploads/images/")) {
// delete from disk
int fileNameStart = image.Url.LastIndexOf('/');
string uniqueFileName = image.Url.Substring(fileNameStart + 1);
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads", "images", uniqueFileName);
System.IO.File.Delete(absolutePath);
}
}
// - from db
// - first, from any quotes that reference it
List<Quote> quotesToModify = await _db.Quotes
.Include(q => q.Image)
.Where(q => q.Image == image)
.ToListAsync();
foreach (Quote quote in quotesToModify)
{
quote.Image = null;
}
// - finally, from images table
_db.Images.Remove(image);
await _db.SaveChangesAsync();
// Return ok
return Ok(new { Status = "ok" });
}
}

12
DTOs/AskLLMInDTO.cs Normal file
View File

@@ -0,0 +1,12 @@
namespace QuotifyBE.DTOs;
public record class AskLLMInDTO
{
public string? CustomPrompt { get; set; } = null;
public string? Model { get; set; } = null;
public float? Temperature { get; set; } = 0.8f;
public int? CategoryId { get; set; } = null;
public bool? UseSampleQuote { get; set; } = false;
};

14
DTOs/QuoteCompleteDTO.cs Normal file
View File

@@ -0,0 +1,14 @@
namespace QuotifyBE.DTOs;
public record class QuoteCompleteDTO
{
public int Id { get; set; }
public string Text { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public string? ImageUrl { get; set; }
public List<string>? Categories { get; set; } = new();
public DateTime? createDate { get; set; }
public DateTime? updateDate { get; set; }
};

View File

@@ -29,4 +29,28 @@ public static class QuoteMapping
Categories = categoryNames Categories = categoryNames
}; };
} }
public static QuoteCompleteDTO ToQuoteCompleteDTO(this Quote quote)
{
List<string> categoryNames = [];
if (quote.QuoteCategories != null)
{
foreach (QuoteCategory quoteCategory in quote.QuoteCategories)
{
categoryNames.Add(quoteCategory.Category!.Name ?? $"Unnamed category {quoteCategory.CategoryId}");
}
}
return new QuoteCompleteDTO
{
Id = quote.Id,
Text = quote.Text,
Author = quote.Author,
ImageUrl = quote.Image?.Url,
Categories = categoryNames,
createDate = quote.CreatedAt,
updateDate = quote.LastUpdatedAt
};
}
} }

View File

@@ -151,5 +151,5 @@ app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllers(); app.MapControllers();
app.UseStaticFiles();
app.Run(); app.Run();

View File

@@ -29,10 +29,15 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" /> <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.3" /> <PackageReference Include="Npgsql" Version="9.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" /> <PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\uploads\images\" />
</ItemGroup>
</Project> </Project>

View File

@@ -2,8 +2,17 @@
"JwtSecret": "this is a sample jwt secret token required for quotify - it needs to have at least 256 bits (32 bytes long)", "JwtSecret": "this is a sample jwt secret token required for quotify - it needs to have at least 256 bits (32 bytes long)",
"DomainName": "example.com", "DomainName": "example.com",
"CorsOrigins": [ "CorsOrigins": [
"http://localhost:5259", "http://localhost:5258", "http://example.com" "https://localhost:7029", "http://localhost:5259", "http://localhost:5258", "http://localhost:3000", "http://example.com"
], ],
"UserContent": {
"MaxFileSize": 5242880
},
"LlmIntegration": {
"ApiUrl": "URL to OpenAI-compatible API server, e.g. https://example.com/api/v1",
"ApiKey": "FILL ME for AI-generation capabilities",
"DefaultPrompt": "Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat?\nZastanów się nad jego puentą, a kiedy będziesz gotów - zwróć sam cytat.\nNie pytaj mnie co o nim sądzę, ani nie używaj emotikonów (emoji).\nPamiętaj, że dobre cytaty są krótkie, zwięzłe.",
"DefaultModel": "deepclaude"
},
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret" "DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
}, },

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB