mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 08:10:07 +01:00
Compare commits
16 Commits
Tydz3,-los
...
12f489749a
| Author | SHA1 | Date | |
|---|---|---|---|
| 12f489749a | |||
| 11d24dcc11 | |||
| bb9bdcfaa0 | |||
| 601d99bccd | |||
| 3e823fb37b | |||
| 9e9017717a | |||
| bc05e91790 | |||
| df4cd1c8a7 | |||
| f60f613969 | |||
| ceb1829eb9 | |||
| a1086b94f1 | |||
| ba162c34cc | |||
| 197918e526 | |||
| ac80061437 | |||
| e7cebc32a4 | |||
| 9e1e9c86d3 |
@@ -27,20 +27,72 @@ public class CategoryController : ControllerBase
|
||||
guhf = GUHF;
|
||||
}
|
||||
|
||||
// GET /api/v1/categories
|
||||
// GET /api/v1/categories/page/1
|
||||
/// <summary>
|
||||
/// Get every category
|
||||
/// 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 <= 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
|
||||
/// <summary>
|
||||
/// [AUTHED] Get every category
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Can (and will) return an empty list if no categories are found in DB. <br/>
|
||||
/// Unlike GET /api/v1/categories/page/..., requires authorization with a JWT.
|
||||
/// Has CORS set.
|
||||
/// </remarks>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
// /// <response code="404">Returned when there are no categories to list</response>
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(typeof(CategoryShortDTO), 200)]
|
||||
// [ProducesResponseType(typeof(ErrorDTO), 404)]
|
||||
[ProducesResponseType(typeof(List<CategoryShortDTO>), 200)]
|
||||
public async Task<IActionResult> GetQuotePage()
|
||||
{
|
||||
// The following seems to be a bad idea, so I leave it as is. ~eee4
|
||||
@@ -66,6 +118,7 @@ public class CategoryController : ControllerBase
|
||||
|
||||
}
|
||||
|
||||
|
||||
// POST /api/v1/categories
|
||||
/// <summary>
|
||||
/// [AUTHED] Create a new category
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.Entities;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
@@ -132,4 +134,108 @@ public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettin
|
||||
|
||||
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.6f; // 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
|
||||
Console.WriteLine($"[QuotifyBE] Error: response status code from API was {response.StatusCode}.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Infrastructure;
|
||||
using Microsoft.AspNetCore.Cors;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Update.Internal;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using QuotifyBE.Data;
|
||||
using QuotifyBE.DTOs;
|
||||
using QuotifyBE.Entities;
|
||||
using QuotifyBE.Mapping;
|
||||
using System.Reflection.Metadata.Ecma335;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace QuotifyBE.Controllers;
|
||||
@@ -41,6 +39,7 @@ public class QuotesController : ControllerBase
|
||||
/// Has CORS set, unlike e.g. GET /api/v1/quote/{id} or GET /api/v1/quote/random.
|
||||
/// </remarks>
|
||||
/// <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>
|
||||
/// <returns>A page (<= 10 quotes)</returns>
|
||||
/// <response code="200">Returned on valid request</response>
|
||||
@@ -49,7 +48,7 @@ public class QuotesController : ControllerBase
|
||||
[EnableCors]
|
||||
[ProducesResponseType(typeof(List<QuoteShortDTO>), 200)]
|
||||
[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();
|
||||
const int PageSize = 10;
|
||||
@@ -80,8 +79,15 @@ public class QuotesController : ControllerBase
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Include(q => q.User)
|
||||
.Include(q => q.Image)
|
||||
.OrderBy(q => q.Id);
|
||||
.Include(q => q.Image);
|
||||
|
||||
// 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
|
||||
List<Quote> pageQuotes;
|
||||
@@ -89,7 +95,7 @@ public class QuotesController : ControllerBase
|
||||
// Filtrowanie przed pobraniem strony
|
||||
if (categories != null)
|
||||
{
|
||||
pageQuotes = await baseQuery
|
||||
pageQuotes = await orderedQuery
|
||||
.Where(q => q.QuoteCategories!
|
||||
.Any(qc => categories.Contains(qc.CategoryId))
|
||||
//.Any(qc => qc.CategoryId == category_id.Value)
|
||||
@@ -100,7 +106,7 @@ public class QuotesController : ControllerBase
|
||||
}
|
||||
else
|
||||
{
|
||||
pageQuotes = await baseQuery
|
||||
pageQuotes = await orderedQuery
|
||||
.Skip((page_no - 1) * PageSize)
|
||||
.Take(PageSize)
|
||||
.ToListAsync();
|
||||
@@ -150,32 +156,50 @@ public class QuotesController : ControllerBase
|
||||
/// [AUTHED] Add a new quote
|
||||
/// </summary>
|
||||
/// <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>
|
||||
/// <response code="201">Returned on valid request</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="406">Returned when image url is invalid (does not start with "https://", "http://", or "/")</response>
|
||||
[HttpPost("new")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
[ProducesResponseType(201)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 400)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 403)]
|
||||
[ProducesResponseType(typeof(ErrorDTO), 406)]
|
||||
public async Task<IActionResult> CreateQuote([FromBody] CreateQuoteDTO request)
|
||||
{
|
||||
// Get user ID from claims
|
||||
|
||||
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
|
||||
// https://stackoverflow.com/a/47708867
|
||||
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;
|
||||
if (!string.IsNullOrEmpty(request.ImageUrl))
|
||||
{
|
||||
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == request.ImageUrl);
|
||||
|
||||
// Failed? Just insert it yourself
|
||||
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 };
|
||||
_db.Images.Add(image);
|
||||
await _db.SaveChangesAsync();
|
||||
@@ -232,7 +256,8 @@ public class QuotesController : ControllerBase
|
||||
{
|
||||
IQueryable<Quote> query = _db.Quotes
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category);
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Include(q => q.Image);
|
||||
|
||||
if (category_id.HasValue)
|
||||
{
|
||||
@@ -255,8 +280,6 @@ public class QuotesController : ControllerBase
|
||||
var skip = random.Next(0, totalQuotes);
|
||||
|
||||
var quote = await query
|
||||
.Include(q => q.QuoteCategories!)
|
||||
.ThenInclude(qc => qc.Category)
|
||||
.Skip(skip)
|
||||
.Take(1)
|
||||
.FirstOrDefaultAsync();
|
||||
@@ -339,13 +362,19 @@ public class QuotesController : ControllerBase
|
||||
/// While "categories = null" will not alter the quote's categories,
|
||||
/// "categories = []" will (and in turn, empty each and every present category)!<br/>
|
||||
/// 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>
|
||||
/// <returns>Newly modified quote as a DTO</returns>
|
||||
/// <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="400">Returned when request text or author is empty (or whitespace)</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}")]
|
||||
[Authorize]
|
||||
[EnableCors]
|
||||
@@ -377,9 +406,19 @@ public class QuotesController : ControllerBase
|
||||
if (!string.IsNullOrEmpty(updatedQuote.ImageUrl))
|
||||
{
|
||||
image = await _db.Images.FirstOrDefaultAsync(i => i.Url == updatedQuote.ImageUrl);
|
||||
|
||||
// Failed? Just insert it yourself
|
||||
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 };
|
||||
_db.Images.Add(image);
|
||||
await _db.SaveChangesAsync();
|
||||
@@ -443,4 +482,75 @@ public class QuotesController : ControllerBase
|
||||
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
|
||||
);
|
||||
|
||||
// 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 });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -10,12 +10,12 @@ namespace QuotifyBE.Controllers;
|
||||
[EnableCors]
|
||||
[Route("api/v1/stats")]
|
||||
[Produces("application/json")]
|
||||
public class StatisticController : ControllerBase
|
||||
public class StatisticsController : ControllerBase
|
||||
{
|
||||
|
||||
private readonly ApplicationDbContext _db;
|
||||
|
||||
public StatisticController( ApplicationDbContext db)
|
||||
public StatisticsController( ApplicationDbContext db)
|
||||
{
|
||||
_db = db;
|
||||
}
|
||||
|
||||
200
Controllers/UserContentController.cs
Normal file
200
Controllers/UserContentController.cs
Normal file
@@ -0,0 +1,200 @@
|
||||
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;
|
||||
|
||||
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
|
||||
List<string> allowedExtensions = new List<string>() { ".jpg", ".jpeg", ".jfif", ".png", ".gif", ".avif", ".webp" };
|
||||
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
|
||||
});
|
||||
}
|
||||
|
||||
// DELETE /api/v1/uc/images/{id}
|
||||
/// <summary>
|
||||
/// [AUTHED] Delete an image
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deletes an image, granted it exists. <br/>
|
||||
/// <b>Note</b>:
|
||||
/// If the image is a file on disk, it's also deleted.
|
||||
/// </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
|
||||
_db.Images.Remove(image);
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
// Return ok
|
||||
return Ok(new { Status = "ok" });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
12
DTOs/AskLLMInDTO.cs
Normal file
12
DTOs/AskLLMInDTO.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace QuotifyBE.DTOs;
|
||||
|
||||
public record class AskLLMInDTO
|
||||
{
|
||||
public string? CustomPrompt { get; set; }
|
||||
public string? Model { get; set; } = "deepclaude";
|
||||
public float? Temperature { get; set; } = 0.8f;
|
||||
public int? CategoryId { get; set; } = null;
|
||||
public bool? UseSampleQuote { get; set; } = false;
|
||||
|
||||
};
|
||||
|
||||
@@ -151,5 +151,5 @@ app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.Run();
|
||||
|
||||
@@ -29,10 +29,15 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<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.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="9.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\uploads\images\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -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)",
|
||||
"DomainName": "example.com",
|
||||
"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": {
|
||||
"DefaultConnection": "Server=server-host;Database=db-name;Username=quotify-user;Password=user-secret"
|
||||
},
|
||||
|
||||
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
BIN
wwwroot/uploads/images/42cbadf4-7804-4fde-991c-d56eb1f4a1b4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 141 KiB |
Reference in New Issue
Block a user