15 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
11 changed files with 224 additions and 48 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

@@ -80,20 +80,21 @@ public class CategoryController : ControllerBase
// GET /api/v1/categories // GET /api/v1/categories
/// <summary> /// <summary>
/// [AUTHED] 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/>
/// Unlike GET /api/v1/categories/page/..., requires authorization with a JWT. /// <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]
[Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)] [ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
public async Task<IActionResult> GetQuotePage() public async Task<IActionResult> GetEveryCategory()
{ {
// 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
// //

View File

@@ -139,7 +139,7 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
{ {
string _model = model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude"; string _model = model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
float _temp = temp ?? 0.6f; // sane default float _temp = temp ?? 0.8f; // sane default
string _included_sample = string.Empty; string _included_sample = string.Empty;
string _prompt = prompt ?? _appsettings.GetSection("LlmIntegration")["DefaultPrompt"] ?? string _prompt = prompt ?? _appsettings.GetSection("LlmIntegration")["DefaultPrompt"] ??
"Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat? " + "Cześć, czy jesteś w stanie wymyślić i stworzyć jeden oryginalny cytat? " +
@@ -233,7 +233,12 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
else else
{ {
// Handle the error // Handle the error
JObject error = JObject.Parse(await response.Content.ReadAsStringAsync());
Console.WriteLine($"[QuotifyBE] Error: response status code from API was {response.StatusCode}."); 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; return null;
} }
} }

View File

@@ -20,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
@@ -46,7 +48,7 @@ public class QuotesController : ControllerBase
/// <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 = 1, string? sort = "desc", [FromQuery] string? category_id = null) public async Task<IActionResult> GetQuotePage(int page_no = 1, string? sort = "desc", [FromQuery] string? category_id = null)
{ {
@@ -113,7 +115,7 @@ public class QuotesController : ControllerBase
} }
var result = pageQuotes var result = pageQuotes
.Select(q => q.ToQuoteShortDTO()) .Select(q => q.ToQuoteCompleteDTO())
.ToList(); .ToList();
return Ok(result); return Ok(result);
@@ -125,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)
{ {
@@ -148,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
@@ -386,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?
@@ -536,6 +538,8 @@ public class QuotesController : ControllerBase
request.CustomPrompt, request.Model, request.Temperature, request.CategoryId, request.UseSampleQuote request.CustomPrompt, request.Model, request.Temperature, request.CategoryId, request.UseSampleQuote
); );
string llmUsed = request.Model ?? _appsettings.GetSection("LlmIntegration")["DefaultModel"] ?? "deepclaude";
// Check if any errors occurred // Check if any errors occurred
if (generatedResponse == null) if (generatedResponse == null)
{ {
@@ -550,7 +554,7 @@ public class QuotesController : ControllerBase
return StatusCode(500, new ErrorDTO { Status = "error", Error_msg = "Unexpected API response" }); return StatusCode(500, new ErrorDTO { Status = "error", Error_msg = "Unexpected API response" });
// Otherwise, return the response // Otherwise, return the response
return Ok(new { Status = "ok", BotResponse = llmResponse }); return Ok(new { Status = "ok", BotResponse = llmResponse, Model = llmUsed });
} }
} }

View File

@@ -20,6 +20,7 @@ public class UserContentController : ControllerBase
private readonly IConfiguration _appsettings; private readonly IConfiguration _appsettings;
private readonly ApplicationDbContext _db; private readonly ApplicationDbContext _db;
private readonly GeneralUseHelpers guhf; 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) public UserContentController(IConfiguration appsettings, ApplicationDbContext db, GeneralUseHelpers GUHF)
{ {
@@ -37,7 +38,7 @@ public class UserContentController : ControllerBase
/// Requires authorization with a JWT, has CORS set. /// Requires authorization with a JWT, has CORS set.
/// </remarks> /// </remarks>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
[HttpGet] [HttpGet("images")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(typeof(List<Image>), 200)] [ProducesResponseType(typeof(List<Image>), 200)]
@@ -60,59 +61,183 @@ public class UserContentController : ControllerBase
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Allows authorized users to publish images. /// Allows authorized users to publish images.
/// A user-reachable path is returned on success.<br/> /// A user-reachable path and image id is returned on success.<br/>
/// </remarks> /// </remarks>
/// <response code="200">Returned on valid request</response> /// <response code="200">Returned on valid request</response>
/// <response code="400">Returned when file extension is unknown</response> /// <response code="400">Returned when request does not contain a file or the file is blank</response>
/// <response code="406">Returned when request does not follow user-provided config</response> /// <response code="413">Returned when image size is too large</response>
[HttpPost] /// <response code="415">Returned when file extension/mimetype is unknown</response>
[HttpPost("images")]
[Authorize] [Authorize]
[EnableCors] [EnableCors]
[ProducesResponseType(200)] [ProducesResponseType(200)]
[ProducesResponseType(typeof(ErrorDTO), 400)] [ProducesResponseType(typeof(ErrorDTO), 400)]
[ProducesResponseType(typeof(ErrorDTO), 406)] [ProducesResponseType(typeof(ErrorDTO), 413)]
[ProducesResponseType(typeof(ErrorDTO), 415)]
public IActionResult PostNewImage(IFormFile file) public IActionResult PostNewImage(IFormFile file)
{ {
// Obsługa braku pliku
// Ideally, a hash of the file would be stored somewhere if (file == null || file.Length == 0)
// in the database to have a basic redundancy check, {
// but this will do for now. ~eee4 return BadRequest(new ErrorDTO
{
// A good idea would be to also check the Content-Type
// of submitted files. ~eee4
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
string fileExtension = Path.GetExtension(file.FileName);
if (!allowedExtensions.Contains(fileExtension.ToLower())) {
return BadRequest(new ErrorDTO {
Status = "error", Status = "error",
Error_msg = $"Unknown file extension. Please use one of the following: {string.Join(", ", allowedExtensions)}" Error_msg = "No file was uploaded."
}); });
} }
// TODO: // Dozwolone rozszerzenia
// https://www.youtube.com/watch?v=6-FNejMrVuk string fileExtension = Path.GetExtension(file.FileName).ToLower();
// Sprawdź, czy plik spełnia ograniczenia: if (!_allowedExtensions.Contains(fileExtension))
// 1. Czy rozmiar jest mniejszy od _appsettings["UserContent"]["MaxFileSize"] ? {
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."
});
}
// Jeśli nie, zwróć ErrorDTO ze wiadomością: $"File size exceeds {_appsettings["UserContent"]["MaxFileSize"]}" // 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);
// Zapisz plik na dysku z pseudolosową nazwą GUID // 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);
}
// Wrzucić go do folderu "uploads/images/" // 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
});
}
// Stwórz URL postaci: "/uploads/images/<nazwa pliku>.<rozszerzenie>" // 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" });
// Zwróć powyższy URL // If succeded, remove the image:
return Ok(new { Status = "ok", Filepath = "miejsce na wspomniany URL" }); // - 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" });
} }
} }

View File

@@ -2,8 +2,8 @@ namespace QuotifyBE.DTOs;
public record class AskLLMInDTO public record class AskLLMInDTO
{ {
public string? CustomPrompt { get; set; } public string? CustomPrompt { get; set; } = null;
public string? Model { get; set; } = "deepclaude"; public string? Model { get; set; } = null;
public float? Temperature { get; set; } = 0.8f; public float? Temperature { get; set; } = 0.8f;
public int? CategoryId { get; set; } = null; public int? CategoryId { get; set; } = null;
public bool? UseSampleQuote { get; set; } = false; 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

@@ -37,7 +37,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="uploads\images\" /> <Folder Include="wwwroot\uploads\images\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB